Previous | Home | Next |
- The null keyword in java programming language is a reserved word that is used to represent no value.
- Null is not a keyword in Java. It is a reference literal value.
- Primitive data types such as byte, short, int, long, char, float, double, Boolean cannot have a null type.
- Reference variable is refer 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.
- null is a case sensitive, you cannot write null as Null or NULL, compiler will not recognize them and give error.
- Unlike common misconception, null is not Object or neither a type. It's just a special value, which can be assigned to any reference type and you can type cast null to any type
- 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.
- 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.
Object obj = NULL; // Not Ok Object obj1 = null //Ok
String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error
Example :
class Rectangle { double length; double breadth; } class NullRectangle { public static void main(String args[]) { Rectangle myrect1; System.out.println(myrect1.length); } }
output :
NullRectangle.java:13: error: variable myrect1 might not have been initialized System.out.println(myrect1.length); ^ 1 error
myrect1 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.
Example :
class Rectangle { double length; double breadth; } class NullRectangle1 { public static void main(String args[]) { Rectangle myrect1; if(myrect1 == null) { myrect1 = new Rectangle(); } } }
output :
NullRectangle1.java:14: error: variable myrect1 might not have been initialized if(myrect1 == null) ^ 1 error
Class Level null Value
Rectangle myrect1;
is similar to-
Rectangle myrect1 = null;
Method Level null value
Valid Declaration :
Rectangle myrect1 = null;
Invalid Declaration :
Rectangle myrect1 ;
Previous | Home | Next |