Is the following Java variable declaration valid?

I mistakenly declared an array of strings as follows:

String[] tokens[]; 

Eclipse does not highlight this as an error, but instead considers this to be equivalent:

 String[][] tokens; 

Is this the correct behavior or error?

+4
source share
6 answers

Correct behavior - arrays can be defined using brackets after the object type name or .

 String[] tokens; 

and

 String tokens[]; 

match up. This, however, is a confusing way to write a 2D array so that I don't intentionally use it;)

If you consider arrays as objects (that they are technically), and the square brackets as syntactic sugar for the new keyword and an empty constructor, you can present your "error" as:

 tokens = new Array<String>(new Array<String>()); 

as

 String[] tokens; 

and

 String tokens[]; 

both would be equivalent

 new Array<String>(); 
+3
source

Yes, that's right. They are equivalent:

 String[] tokens[]; String tokens[][]; String[][] tokens; 

For clarity, you should declare "[]" on the type of the variable, not its name, but other than that it is normal.

+2
source

This is a valid ad. You can also declare it as String tokens[][];

+1
source

Trust Eclipse. All of the following equivalents:

 String tokens[][]; String[] tokens[]; String [][]tokens; 
+1
source

According to the Java tutorial, you can (but traditionally shouldn't) declare arrays with square brackets after the variable name:

You can also put square brackets after the array name:

  // this form is discouraged
 float anArrayOfFloats []; 

However, the convention discourages this form; brackets determine the type of array and should appear with a type designation.

Considering this and your observations, it is safe to say that Eclipse allows you to mix those forms of declarations that in your case lead to an array of arrays.

+1
source

This is a recollection of older languages ​​such as C / C ++.

Actually, for how type checking and JVM works in Java, the declaration

 String[][] tokens; 

more coherent.

This is because you declare tokens with the type "two-dimensional array of String objects", so String[][] can be thought of as a declaration of the same type.

0
source

Source: https://habr.com/ru/post/1398617/


All Articles