Skip to main content

Null Keyword in java

null Keyword : Null Reference

  1. null keyword remove garbage value.
  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.
  3. Declaration of String x = null ;

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:Zubair>javac RectangleDemo.java
RectangleDemo.java:10: variable myrect1 might not have
been initialized
  System.out.println(myrect1.length);
                     ^
1 error
Explanation with Example why error occurs

Explanation : Null Value

  1. Initialize integer i 
  2. In the above example again Re Initialize.
  3. Default value inside 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

  • We can check null value using “==”  , "!="operator.

Output : Hello

Ways Of Null Value Statements :

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 rect;
is similar to –
Rectangle rect = 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 rect = null;
Invalid Declaration :
Rectangle rect ;

Null Object


Comments