How to check whether a int is not null or empty?
Solution 1
int
variables can't be null
If a null
is to be converted to int
, then it is the converter which decides whether to set 0
, throw exception, or set another value (like Integer.MIN_VALUE
). Try to plug your own converter.
Solution 2
I think you are asking about code like this.
int count = (request.getParameter("counter") == null) ? 0 : Integer.parseInt(request.getParameter("counter"));
Solution 3
I think you can initialize the variables a value like -1
,
because if the int
type variables is not initialized it can't be used.
When you want to check if it is not the value you want you can check if it is -1
.
Solution 4
if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..
Solution 5
public class Demo {
private static int i;
private static Integer j;
private static int k = -1;
public static void main(String[] args) {
System.out.println(i+" "+j+" "+k);
}
}
OutPut: 0 null -1
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
I really dont know if this is possible or not. But I am strucking in a place where I want to check an int value is
null
or not, to call different methods.Is there any way to do it?
Actually, variable comes from a browser with a
null
value. I cannot change theint
declaration toInteger
. Because it has it own consequences.Any suggestions?