How to check if an int is a 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
.
Integer id;
String name;
public Integer getId() { return id; }
Besides, the statement if(person.equals(null))
can't be true because if person
is null, then a NullPointerException
will be thrown. So the correct expression is if (person == null)
why int can't be compared to null but Integer can be compared to null
int a,b,c;
if (a == null) {
//code here
}
This code doesn't make sense, because primitive int
types cannot be null. Even if you considered auto-boxing, int a
is guaranteed to have a value before being boxed.
Integer a,b,c;
if (a == null) {
//code here
}
This code makes sense, because Object Integer
types can be null (no value).
As far as the functionality, the Object vs built-in types actually do make a bit of a difference (due to their different natures).
Integer a,b,c;
if (a == b) {
// a and b refer to the same instance.
// for small integers where a and b are constructed with the same values,
// the JVM uses a factory and this will mostly work
//
// for large integers where a and b are constructed with the same values,
// you could get a == b to fail
}
while
int a,b,c;
if (a == b) {
// for all integers were a and b contain the same value,
// this will always work
}
What is the cleanest way to compare an int with a potentially null Integer in Java?
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"))
How to check whether an Integer is null or zero in Java?
Since StringUtils
class is mentioned in the question, I assume that Apache Commons lib is already used in the project.
Then you can use the following:
if (0 != ObjectUtils.defaultIfNull(myInteger, 0)) { ... }
Or using static import:
if (0 != defaultIfNull(myInteger, 0)) { ... }
Why comparing Integer with int can throw NullPointerException in Java?
The Short Answer
The key point is this:
==
between two reference types is always reference comparison- More often than not, e.g. with
Integer
andString
, you'd want to useequals
instead
- More often than not, e.g. with
==
between a reference type and a numeric primitive type is always numeric comparison- The reference type will be subjected to unboxing conversion
- Unboxing
null
always throwsNullPointerException
- While Java has many special treatments for
String
, it is in fact NOT a primitive type
The above statements hold for any given valid Java code. With this understanding, there is no inconsistency whatsoever in the snippet you presented.
The Long Answer
Here are the relevant JLS sections:
JLS 15.21.3 Reference Equality Operators
==
and!=
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.
This explains the following:
Integer i = null;
String str = null;
if (i == null) { // Nothing happens
}
if (str == null) { // Nothing happens
}
if (str == "0") { // Nothing happens
}
Both operands are reference types, and that's why the ==
is reference equality comparison.
This also explains the following:
System.out.println(new Integer(0) == new Integer(0)); // "false"
System.out.println("X" == "x".toUpperCase()); // "false"
For ==
to be numerical equality, at least one of the operand must be a numeric type:
JLS 15.21.1 Numerical Equality Operators
==
and!=
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible to numeric type, binary numeric promotion is performed on the operands. If the promoted type of the operands is
int
orlong
, then an integer equality test is performed; if the promoted type isfloat or
double`, then a floating-point equality test is performed.Note that binary numeric promotion performs value set conversion and unboxing conversion.
This explains:
Integer i = null;
if (i == 0) { //NullPointerException
}
Here's an excerpt from Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives:
In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the
==
operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throwNullPointerException
. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.
References
- JLS 4.2. Primitive Types and Values
- "The numeric types are the integral types and the floating-point types."
- JLS 5.1.8 Unboxing Conversion
- "A type is said to be convertible to a numeric type if it is a numeric type, or it is a reference type that may be converted to a numeric type by unboxing conversion."
- "Unboxing conversion converts [...] from type
Integer
to typeint
" - "If
r
isnull
, unboxing conversion throws aNullPointerException
"
- Java Language Guide/Autoboxing
- JLS 15.21.1 Numerical Equality Operators
==
and!=
- JLS 15.21.3 Reference Equality Operators
==
and!=
- JLS 5.6.2 Binary Numeric Promotion
Related questions
- When comparing two
Integers
in Java does auto-unboxing occur? - Why are these
==
but notequals()
? - Java: What’s the difference between autoboxing and casting?
Related questions
- What is the difference between an int and an Integer in Java/C#?
- Is it guaranteed that new Integer(i) == i in Java? (YES!!! The box is unboxed, not other way around!)
- Why does
int num = Integer.getInteger("123")
throwNullPointerException
? (!!!) - Java noob: generics over objects only? (yes, unfortunately)
- Java
String.equals
versus==
How does comparison operator works with null int?
According to MSDN - it's down the page in the "Operators" section:
When you perform comparisons with nullable types, if the value of one of the nullable types is
null
and the other is not, all comparisons evaluate tofalse
except for!=
So both a > b
and a < b
evaluate to false
since a
is null...
Why type int is never equal to 'null'?
If you want your integer variable to allow null values, declare it to be a nullable type:
int? n = 0;
Note the ?
after int, which means that type can have the value null
. Nullable types were introduced with v2.0 of the .NET Framework.
Compare nullable Integer to 0
x
is a field in your class, so when you create it without making it to reference to any Integer
object (Integer x = new Integer(7)
for example), the compiler gives it a null
for you (the default values for Object references). It seems like you have hence: Integer x = null;
So to compare it just use the equals()
method that is implemented by Integer wrapper class.
new Integer(0).equals(x)
Can an int be null in Java?
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>
Related Topics
How to Update Ms Access Database Table Using Update and Sum() Function
Mongodb and Postgresql Thoughts
Postgresql Return a Function with a Custom Data Type
Splitting String Using SQL Statement (Ip Address)
How to Check All Stored Procedure Is Ok in SQL Server
Select All Threads and Order by the Latest One
Oracle Delete Rows Matching on Multiple Values
Is Golang's SQL Package Incapable of Ad Hoc/Exploratory Queries
Conditional SQLite Check Constraint
Is It a Bad Idea to Use Guids as Primary Keys in Ms SQL
Percentage from Total Sum After Group by SQL Server
What Is Difference Between Inner Join and Outer Join
Difference Between Stored Procedures and User Defined Functions