How to check whether a int is not null or empty?
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 m开发者_如何转开发ethods.
Is there any way to do it?
Actually, variable comes from a browser with a null
value.
I cannot change the int
declaration to Integer
. Because it has it own consequences.
Any suggestions?
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.
I think you are asking about code like this.
int count = (request.getParameter("counter") == null) ? 0 : Integer.parseInt(request.getParameter("counter"));
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
.
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..
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
Possibly browser returns String representation of some integer value? Actually int can't be null. May be you could check for null, if value is not null, then transform String representation to int.
int cannot be null. If you are not assigning any value to int default value will be 0. If you want to check for null then make int as Integer in declaration. Then Integer object can be null. So, you can check where it is null or not. Even in javax bean validation you won't be able to get error for @NotNull annotation until the variable is declared as Integer.
If you are receiving integer input, I would suggest checking if the text itself isn't empty, and then making a variable equal to it .toInt()
An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.
Example:
int x;
// Some Code...
if (x <= 0 || x > 0){
// What you want the code to do if x has a value
} else {
// What you want the code to do if x has no value
}
Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.
精彩评论