3

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?

11
  • 10
    There's never any reason to choose the first one. Commented Jan 24, 2017 at 8:33
  • 1
    You should never set any collection type to null in te first place! Doing so will force you to do null checks later which are not needed otherwise. Commented Jan 24, 2017 at 8:35
  • 2
    @TimothyTruckle That's not a collection type, that's an array type. Your statement is false in other ways too. Commented Jan 24, 2017 at 8:36
  • 1
    @TimothyTruckle Or why don't we all just say wrong things here, because you don't need to be precise in programming. Let's call arrays collections and say stupid claims that you should never set collection types to null. Or we could try to make sure that the information given here is correct, what do you think? Commented Jan 24, 2017 at 8:40
  • 1
    @TimothyTruckle If you don't want to be corrected, don't make wrong statements. The array type is distinct from a collection, even if you can store elements in both. On the other hand, saying that you should never assign a null to (either) one is just plain wrong. Commented Jan 24, 2017 at 8:57

1 Answer 1

13

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);
Sign up to request clarification or add additional context in comments.

2 Comments

And, casting to String or Integer will invoke an appropriate cast.
same also happens if you have a single method with varargs public void doSomethingElse(String... values) - if passing null is not possible to distinct between values being null, or its first element being null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.