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
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
}
}
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))
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
String s= "";
int i=0;
i=Integer.parseInt(s+0);
System.out.println(i);
Try this
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);
}
}
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;
}