4

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

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
user2975747
  • 107
  • 7

1 Answers1

11

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.

Eran
  • 387,369
  • 54
  • 702
  • 768