Check if an int is a null in Java

In this post, I will be sharing how to check if an int is null in java. int is a primitive data type and Integer is a wrapper class in Java.

Read Also:  How to convert int to Integer in Java

Check if an int is a null in Java

int stores the values in the memory in the form of binary by default. It means they can't be null. Primitive data type int can not be checked for a null value. On the other hand, Integer is an object and it can have a null value as shown below in the example.

Difference between int and Integer in Java


Integer wrapper class is just like any other class in Java. Using variables of the Integer type, we store references to Integer objects. There are more functionalities associated with the Integer class, for example, we can use the parseInt() method to parse the valid string to static int.
The Integer is a java class that contains a single field type int. Whenever we need int to be treated as objects, we can use the Integer class. This is why Integer is a wrapper class of int.

Java Code Example


 public class CheckIfIntIsNull {
    public static void main(String args[]) {
      // Integer primtive data type     
      int empId = 23;
      // Integer wrapper class
      Integer empId2 = new Integer(34);
      System.out.println("Primitive int empId is: "+ empId);
      System.out.println("Wrapper class Integer object is: "+ empId2);
      /* Can not check for null property for int, We can check for 
      null property for Integer */
      if (empId2 == null) {
        System.out.println("Integer wrapper class object is NULL");
      }
      else {
        System.out.println("Integer wrapper class object is NOT NULL");
      }
    }
}


Output:

Primitive integer empId is: 23
Wrapper class Integer object is: 34
Integer wrapper class object is NOT NULL


As shown in the above example, Integer is an object that can be checked for null property whereas int can not be null.

That's all for today. Please mention in the comments in case you still have any questions regarding check if an int is a null in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry