Can an int be null in Java?



No, In Java int cannot be null. There are some primitive data types and int is the one of the primitive data types in Java programming. The default value for an int data type is 0 and it cannot not be null.

The different primitive data types have their different default values, but the objects in Java can be null.

There is no null reference concept for the primitive data types (such as int, float, etc.).

Example

For example, if you try to assign null to an int variable. It will generate an error.

int myInt = null;

How You can Assign null to an Integer?

If there is a need of variable that can represent null, you can use the Integer class because Integer class hold the null values as it is an Object.

Example

The following example can be used to store null to an integer class object:

public class Main {
  public static void main(String[] args) {
    // Declare an object of Integer class
    Integer int_var = null;

    // Checking whether int_var is null or not
    if (int_var == null) {
      System.out.println("int_var is null");
    } else {
      System.out.println("int_var value: " + int_var);
    }
  }
}

Here is the output:

int_var is null
Updated on: 2024-09-19T23:01:21+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements