The null Keyword : Null Reference inside Instance Variable
- A reference variable refers to an object.
- 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.
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
- As explained in the previous chapter , Creating Object is two step process.
- In the above example myrect is not initialized.
- Default value inside myrect1 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
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
- 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 myrect1;
is similar to –
Rectangle myrect1 = 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 myrect1 = null;
Invalid Declaration :
Rectangle myrect1 ;
0 comments:
Post a Comment
Let us know your responses and feedback