Java – initializing arrays with values – should classes be displayed explicitly?
•
Java
I often see arrays initialized like this:
String[] array = new String[] { "foo","bar","baz" };
However, reading language basics – arrays shows that short syntax does not need to explicitly instantiate constructors:
Therefore, suppose these two initialization methods:
String[] array = new String[] { "foo","baz" }; String[] array2 = { "foo","baz" };
What's the difference between these? Both seem to be the same. In this case, should I assume that the second implicitly calls the new string [], and the first is just a more lengthy way, or behind the scenes?
Start with Java, so sorry if this is too stupid a question, but I didn't find anything about this on the network
Solution
The two methods are equivalent Note, however, that the concise syntax can only be used for variable declarations External variable declaration must use detailed syntax:
String[] array; array = new String[] { "foo","baz" }; // OK String[] array2; array2 = { "foo","baz" }; // ERROR
For further discussion, see this answer
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
二维码