Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of type casting 'null' to any reference type in JAVA? [duplicate]

Tags:

java

null

Is there anything which can be achieved by type casting null to say String ref type?

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

Both does the same thing.

sysout(s) displays null

sysout((String)null) displays null

like image 494
user2975747 Avatar asked Dec 18 '22 15:12

user2975747


1 Answers

Suppose you have overloaded methods that take a single 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 make a call

method1 (null);

the code won't pass compilation, since both methods accept a null reference, and the compiler has no preference between the 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.

like image 194
Eran Avatar answered May 17 '23 06:05

Eran