taiyebur
taiyebur

Reputation: 429

Why should I use (String[])null over null in java?

In some snippets, I noticed that the array is initialized by casting the null value to String array like:

String[] array = (String[])null;

Generally, null is used to initialize variables e.g. an array of strings like:

String[] array = null;

When or why should I cast null values to string array or any other data type like this?

Upvotes: 3

Views: 210

Answers (1)

Eran
Eran

Reputation: 393781

There is no need to use

String[] array = (String[]) null;

You might have to use (String[]) null if you pass a null value to an overloaded method (i.e. one of multiple methods having the same name) and you want the method that accepts a String[] argument to be chosen by the compiler.

For example, if you have the following methods :

public void doSomething (Integer i) {}
public void doSomething (String s) {}
public void doSomething (String[] arr) {}

Calling doSomething (null) will not pass compilation, since the compiler won't know which method to choose.

Calling doSomething ((String[]) null) will execute the 3rd method.

Of course, you can assign the null to a String[] variable, and avoid the casting :

String[] arr = null;
doSomething (arr);

Upvotes: 13

Related Questions