How to Check if an Int is a Null in Java

Java is a language that requires programmers to produce variables referencing null. Any variable that is stated yet left uninitialized will automatically be referenced as null. The other Java language constructs like try/catch force the variables to be declared in the external range where null is the only valid selection.

In Java, an array is a thing that holds comparable types of information. It can be null just if it is not instantiated or indicate a null reference.

Null Types

Null is not an object neither it is a type. It is a unique worth that can be assigned to any reference type and also the customer can case null to any other type.

// null can be assigned to a String

String str = null;   

// you can assign null to Integer also

Integer itr = null;   

// null can also be assigned to Double

Double dbl = null;

// null can be typecast to String

String myStr = (String) null;

// it can also be type cast to Integer

Integer myItr = (Integer) null;

// yes it's possible, no error

Double myDbl = (Double) null;

Check for Null in Java

An int is not null. It can be absolutely no if left uninitialized. If you want an integer to be able to null, after that you have to utilize Integer rather than int.

Integer id;

    String name;

    public Integer getId() {

    return id;

    }

In this instance, we have produced 2 varieties. The range arr is proclaimed however not instantiated. It does not hold any data and describes a null reference (default worth) assigned by the compiler. The variety arr2 is proclaimed and also explicitly appointed to null to create a null variety.

We can use this instance to examine whether the range is null or not.

public class SimpleTesting
{

 String[] arr;
 String[] arr2 = null;
 
 public static null main(String[] args)
                {
  SimpleTesting obj = new SimpleTesting();
  if(obj.arr == null)
                                {
   System.out.println("The array is null");
  }
  if(obj.arr2 == null) 
                                {
   System.out.println("The array2 is null");
  }
 }
}

Output

The array is null
The array2 is 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 a null value. default have for an int is 0.



Leave a reply



Submit