how to check an int ( not from DataBase) is null - java

such as int a, how can I judge a is null? a is not from DataBase.
As when the data is transferred from Internet, the value of a may be missing.
I need to check whether a is null.
-----add-----
Such As Class A has a private int a, not initial. A has a SetA() function.
May be transfer from Internet, can the A != null but A.a is not value?

You can use ResultSet.getObject() to return a Java Object instead of working with a primitive int:
Integer val = resultSet.getObject("val") != null ? resultSet.getInt("val") : null;
In this case, a null value will really correspond to a null in your database table, and a value of 0 will correspond to this exact value.
Note that if you try something like this:
int val = resultSet.getInt("val");
if (val == 0) {
// but 0 can mean null OR the actual value 0...
}
then you won't be able to distinguish a null value from the actual value 0.

For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
And Most Importantly
int can't be null, but Integer can.
Try this
if(a == null){
//try something
}
here the a instant of Integer.

Default value of primitive cannot be null. For int it should be 0.
As for data transferred from internet the value may be in string format initially. You can check if the string is null before parsing it to int.

Related

Delete value for previously assigned int field [duplicate]

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Check if array entry was already exists in Java

I have a rather simple question: How to check for an (int) array, whether the current entry array[i] was already assigned or not.
It is a dynamic programming task, where I store results for sub-tasks in an array. Thus the array is filled continuously.
I tried: if(a[i] != null) do stuff; but I got an error that "!=" is a bad operator in this case.
What would be the best(robust) solution to check this?
If a is an int array, you can't ask this:
if (a[i] != null)
Because an int value cannot be null. In an empty int array, the uninitialized positions will have 0 as value. Maybe this will work for your use case?
if (a[i] != 0)
If that doesn't solve the problem, then consider explicitly initializing the array with a different value (for example: -1), at the beginning of your program, and testing against it in the condition.
(a[i] != null) is an error for the int type. This is because int is a primitive type and cannot be null. As explained in another answer and some comments, you can fill the array with a set value such as -1 or Integer.MIN_VALUE which would flag an unused element.
If you need a value that can be null and passed as an object, perhaps an array of Integer will do.
It is initialized almost the same:
Integer[] a = new Integer[N]; // N is a constant indicating the length of the array
This creates an array that can hold Integer objects, all of which are initialized to null. You can put an Integer into the array with:
a[i] = new Integer(x);
This will work fine in your if statement:
if (a[i] != null) {...do something...}
will work fine.

Why isn't Integer.MIN_VALUE equal to stored Integer.MIN_VALUE in variable?

I made an Interval class with the following fields:
...
private static final Integer MINF = Integer.MIN_VALUE;
Integer head,tail;
...
when I make an instance of this class, making this.head = Integer.MIN_VALUE, and I want to check if the value of head is equal to MINF, it says that they aren't equal.
Interval i = new Interval(Integer.MIN_VALUE,10);
System.out.println(i.toString()); //[-2147483648,10]
So I went ahead and tried to print the values,
public String toString() {
...
//What the hell?
System.out.println("MINF == Integer.MIN_VALUE: " + (MINF == Integer.MIN_VALUE)); //true
System.out.println("MINF == this.head: " + (MINF == this.head)); //false
System.out.println("Integer.MIN_VALUE == this.head: " + (Integer.MIN_VALUE == this.head)); //true
...
return "*insert interval in format*";
}
Which says
MINF == Integer.MIN_VALUE is true
MINF == this.head is false, although this.head = -2147483648
Integer.MIN_VALUE == this.head is true
Am I missing something for why the second one is false?
Integer is the wrapping class, child of Object and containing an int value.
If you use only the primitive type int, == does a numerical comparison and not an object address comparison.
Mind that Integer.MIN_VALUE of course is an int too.
You are missing the fact that when stored in Integer (that is, you store Integer.MIN_VALUE in two different integers) and using == between them, the comparison is not of the values, but of the objects.
The objects are not identical because they are two different objects.
When each object is compared to Integer.MIN_VALUE, since Integer.MIN_VALUE is an int, the object is autounboxed and compared using int comparison.
No one here has addressed the REASON why they're different objects. Obviously:
System.out.println(new Integer(10) == new Integer(10));
outputs false, for reasons that have been discussed to death in the other answers to this question and in Comparing Integer objects
But, why is that happening here? You don't appear to be calling new Integer. The reason is that:
Integer.MIN_VALUE returns an int, not an Integer.
You have defined MINF to be an Integer
Autoboxing uses valueOf. See Does autoboxing call valueOf()?
valueOf calls new Integer if the int is not in the integer cache,
The cache is only the values -128 -> 127 inclusive.
And that is why you are seeing the "two Integer objects are not == behavior", because of autoboxing. Autoboxing is also why equality does not appear to be transitive here.
You can fix this problem by instead using:
private static final int MINF = Integer.MIN_VALUE;
And, in general: don't use Integer for simple fields.; only use it as a generic type where you actually need the object.
You are using Integer objects. The use of == should be used as a comparison of individual primitive's values only. Since you used the Integer class rather than the primitive int then it is comparing the object's references between the two variables rather than their values.
Because MINF is a separate object to head you are receiving false for a direct comparison using ==.

What is the cleanest way to compare an int with a potentially null Integer in Java?

Map<String,Integer> m;
m = new TreeMap<String,Integer>();
Is it good practice to add the following cast just to avoid the null pointer exception when m.get() is null.
System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false
Alternatively with a prior null check it starts to look a bit ugly.
System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );
Is there a better way to write this? Thanks.
The == operator doesn't compare values, but references.
You should use the .equals() method, instead, applied to the Integer variable (for which you are sure that is not null and NPE won't be thrown):
Integer eight = 8; //autoboxed
System.out.println(eight.equals(m.get("null")));
This will print false even the m.get("null") returns null.
No, because it will not work. You can't compare two Integer with ==, as that compares references and not the integer values. See more info in this question
You'll need a helper method, such as:
boolean safeIntegerCompare(Integer a, int b)
{
if (a != null)
return a.intValue() == b;
return false;
}
I try to avoid casts whenever possible, so I'd rather use the following, which also looks nicer in my opinion:
Integer.valueOf(8).equals(m.get("null"))
If only one of the arguments may be null (as is the case when you're comparing an unknown value to a constant), use equals() like this:
Integer foo = Integer.valueOf(8); // you could write Integer foo = 8; here too but I prefer to avoid autoboxing
if (foo.equals(m.get("x"))) { //will never throw an NPE because foo is never null
...
}
Note that your example isn't going to work in general because comparing non-primitive values with == only returns true if they refer to the same object instance. (Which in this case might even be true for very specific reasons but most of the time it isn't.)
To expand the accepted answer: i find myself having to check the equality of 2 Integer variables which might or might not be null.
So my solution would be:
boolean equals =
Optional.ofNullable(objectA.getNullableInteger()).equals(Optional.ofNullable(objectB.getNullableInteger());
You can use Objects.equals
int foo = 1;
Integer bar = null;
Objects.equals(foo, bar);

How to set to int value null? Java Android [duplicate]

This question already has answers here:
What is the difference between an int and an Integer in Java and C#?
(26 answers)
Closed 9 years ago.
which is the best way to set already defined int to null?
private int xy(){
int x = 5;
x = null; //-this is ERROR
return x;
}
so i choose this
private int xy(){
Integer x = 5;
x = null; //-this is OK
return (int)x;
}
Then i need something like :
if(xy() == null){
// do something
}
And my second question can i safely cast Integer to int?
Thanks for any response.
You can't. int is a primitive value type - there's no such concept as a null value for int.
You can use null with Integer because that's a class instead of a primitive value.
It's not really clear what your method is trying to achieve, but you simply can't represent null as an int.
In this case, I would avoid using null all together.
Just use -1 as your null
If you need -1 to be an acceptable (not null) value, then use a float instead. Since all your real answers are going to be integers, make your null 0.1
Or, find a value that the x will never be, like Integer.MAX_VALUE or something.
Only objects can be null. Primitives (like int) can't.
can i safely cast Integer to int?
You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:
Integer i = 5;
int j = i; //ok
Integer k = null;
int n = k; //Exception
Your method compiles, but will throw NullPointerException when trying to unbox the Integer...
The choice between Integer and int depends on what you are trying to achieve. Do you really need an extra state indicating "no value"? If this is a legitimate state, use Integer. Otherwise use int.

Categories