Cast a Null String into Integer

前端 未结 7 938
闹比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 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;
    }
    

提交回复
热议问题