Why should I use null (string []) in Java?

In some fragments, I noticed that the array is initialized by converting null values into string arrays, such as:

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

Generally, null is used to initialize variables, such as a string array, such as:

String[] array = null;

When or why should null values be converted to string arrays or any other similar data type?

Solution

No need to use

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

If you pass a null value to an overloaded method (that is, one of multiple methods with the same name) and you want the compiler to choose a method that accepts the string [] parameter, you may have to use (string []) null

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) does not pass compilation because the compiler does not know which method to choose

Calling dosomething ((string []) null) will execute the third method

Of course, you can assign null to the string [] variable and avoid conversion:

String[] arr = null;
doSomething (arr);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>