Java null keyword



The null Keyword : Null Reference inside Instance Variable

  1. A reference variable refers to an object.
  2. When a reference variable does not have a value (it is not referencing an object) such a reference variable is said to have a null value.

Declaring Class Instance in Java Programming Language

Live Example : Null Value

class Rectangle {
  double length;
  double breadth;
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle myrect1;
  System.out.println(myrect1.length);

  }
}

Output :

C:Priteshjava>javac RectangleDemo.java
RectangleDemo.java:10: variable myrect1 might not have
been initialized
  System.out.println(myrect1.length);
                     ^
1 error

[468×60]

Explanation : Null Value

  1. As explained in the previous chapter , Creating Object is two step process.
  2. In the above example myrect is not initialized.
  3. Default value inside myrect1 is null , means it does not contain any reference.
  4. If you are declaring reference variable at “Class Level” then you don’t need to initialize instance variable with null. (Above Error Message : error is at println stetement)

Checking null Value

class Rectangle {
  double length;
  double breadth;
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle myrect1;

  if(myrect1 == null)
     {
     myrect1 = new Rectangle();
     }

  }
}
  • We can check null value using “==” operator.

Different Ways Of Null Value Statements :

Way 1 : Class Level null Value

  1. No need to initialize instance variable with null.
  2. Instance Variable contain default value as “null”.
  3. Meaning of “null” is that – Instance Variable does not reference to any object.
Rectangle myrect1;

is similar to –

Rectangle myrect1 = null;

Way 2 : Method Level null Value

  1. Suppose we have to create any object inside “Method” then we must initialize instance variable with Null value.
  2. If we forgot to initialize instance variable with null then it will throw compile time error.

Valid Declaration :

Rectangle myrect1 = null;

Invalid Declaration :

Rectangle myrect1 ;

[336×280]