What is the use of the null type for any reference type in JAVA?

Is there anything that can be achieved by typing null to indicate the type of string String?

String s = null;
String t = (String) null;

Both are doing the same.

sysout(s) displays null

sysout((String)null) displays null

+4
source share
1 answer

Suppose you have overloaded methods that take one parameter, and you want to call one of them and pass null to it.

public void method1 (String param) {}

public void method1 (StringBuilder param) {}

If you call

method1 (null);

the code will not pass the compilation, since both methods accept the link null, and the compiler has no preference between two overloads.

If you call

method1 ((String) null);

the first method will be called.

If you call

method1 ((StringBuilder) null);

the second method will be called.

+9
source

All Articles