Cast a Null String into Integer

前端 未结 7 879
闹比i
闹比i 2021-01-01 18:40

Is there any way to cast a null to Integer. The null is actually a String, which i am passing in my service layer that accepts it as an Integer. So, whenever i try to cast a

相关标签:
7条回答
  • 2021-01-01 18:51

    You cannot cast from String to Integer.
    Java data types are of two kinds: primitive and reference. Primitive types are: byte, short, int, long, char, float, double. The reference types are: class, interface, array.
    byte -> short -> int -> long -> float -> double. is allow, Or The casting may be of its own type or to one of its subclass or superclasss types or interfaces.
    So this is a ex. of function take a look

        public int getInteger(String no) {
        if (no != null) {
            return Integer.parseInt(no); //convert your string into integer 
        } else {
            return 0; // or what you want to return if string is Null
        }
    }
    
    0 讨论(0)
  • 2021-01-01 18:51

    Try below code:application will return 0 if the string is null else it will parse the string to int if string contains a number alone..

    Code:

    (str.equals("null")?0:Integer.parseInt(str))
    
    0 讨论(0)
  • 2021-01-01 18:53

    If you are sure you only have to handle nulls,

    int i=0;
    i=(str==null?i:Integer.parseInt(str));
    System.out.println(i);
    

    for non integer strings it will throw Numberformat exception

    0 讨论(0)
  • 2021-01-01 18:57
    String s= "";  
    int i=0;
    i=Integer.parseInt(s+0);
    System.out.println(i);
    

    Try this

    0 讨论(0)
  • 2021-01-01 19:01

    What about this ?

    private static void castTest() {
        System.out.println(getInteger(null));
        System.out.println(getInteger("003"));
        int a = getInteger("55");
        System.out.println(a);
    }
    
    private static Integer getInteger(String str) {
        if (str == null) {
            return new Integer(0);
        } else {
            return Integer.parseInt(str);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 19:02

    You cannot cast from String to Integer. However, if you are trying to convert string into integer and if you have to provide an implementation for handling null Strings, take a look at this code snippet:

    String str = "...";
    // suppose str becomes null after some operation(s).
    int number = 0;
    try
    {
        if(str != null)
          number = Integer.parseInt(str);
    }
    catch (NumberFormatException e)
    {
        number = 0;
    }
    
    0 讨论(0)
提交回复
热议问题