null is a very important concept in java.
1) null is not a keyword in java,it is actually a literal just like true and false.
Click here to get a better idea.
2) null is default value for any reference variable in java
static Object obj;
public static void main(String ar[]){
System.out.println("Value of Object is "+obj);
}
Output: Value of Object is null
public static void main(String ar[]){
System.out.println("Value of Object is "+obj);
}
Output: Value of Object is null
3) null cannot be assigned to any primitive datatype
int i=null //type mismatch : cannot convert from null to int
float i=null //type mismatch : cannot convert from null to float
4) null can be assigned to any wrapper class
Integer i=null //no error
int j=i //This is ok at compile time but at run time it will throw a NullPointerException.
Above is because at run time Java unbox Integer to int and supply its value to variable j then it will throw a NullPointerException.
5) We cannot call a non static method on reference variable with value zero since it will throw a NullPointerException. But we can call a static variable on reference variable with value 0.
public class MyClass{
public static void staticMethod(){
System.out.println("I am in static method");
}
public void nonStaticMethod(){
System.out.println("I am in non static method");
}
public static void main(String ar[]){
MyClass obj=null;
obj.staticMethod();
obj.nonStaticMethod();
}
}
Output:
I am in static method
Exception in thread "main" java.lang.NullPointerException at MyClass.main(MyClass.java:13)
0 comments:
Post a Comment