What is null ?
null in JAVA is a literal and in JAVA keywords are case sensitive. So, we don’t write Java null as NULL or Null.
[sourcecode language=”java”]
public class Sample
{
public static void main(String[] a) throws java.lang.Exception
{
//Compile-time error: can’t find symbol ‘NULL’
Object ob = NULL;
//Executed successfully
Object ob = null;
}
}
[/sourcecode]
error: cannot find symbol
can’t find symbol ‘NULL’
^
variable NULL
class Sample
1 error
What is the type of null?
How can we assign any specific type to null ?
We can assign specific type to null by any of the two ways:1. To assign to a Variable.
[sourcecode language=”java”]
String s= null;
Integer I = null;
int[ ] a = null;
//Compile- time error because null is not specified to any type.
System.out.print( null);
[/sourcecode]
error: reference to println is ambiguous
System.out.println(null);
^
both method println(char[]) in PrintStream and method println(String) in PrintStream match
1 error
2. Using cast operator
[sourcecode language=”java”]
(String)null;
(Integer)null;
(int [ ] ) null;
[/sourcecode]
What is the default value of any reference variable in JAVA?
Any reference variable has a null value as default value.
[sourcecode language=”java”]
public class Sample{
private static Object ob;
public static void main(String a[])
{
// it will print null;
System.out.println("Value of object ob is : " + ob);
}
}
[/sourcecode]
== & != Operator in JAVA with null
[sourcecode language=”java”]
public class Sample{
public static void main(String []a)
{
System.out.println(null==null);//prints true
System.out.println(null!=null);//prints false
}
}
[/sourcecode]