null Keyword : Null Reference
- null keyword remove garbage value.
- 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.
- 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 : Null Value
- Initialize integer i
- In the above example again Re Initialize.
- Default value inside is null , means it does not contain any reference.
- 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
- No need to initialize instance variable with null.
- Instance Variable contain default value as “null”.
- 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
- Suppose we have to create any object inside “Method” then we must initialize instance variable with Null value.
- 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 ;
Comments
Post a Comment