Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a "char" when creating a new array: int[] a = new int['a'] [duplicate]

Tags:

java

arrays

While creating an array, we can pass short, char, byte, int. So, [why] is int[] a = new int['a'] valid? It doesn't throw a compile time error.

What does an array declaration in this form mean?

like image 432
kwishna Avatar asked Sep 14 '18 20:09

kwishna


People also ask

What does new int [] do?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

What does int [] do in Java?

Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].

How do you declare a character array?

Declaration of a char array is similar to the declaration of a regular array in java. “char[] array_name” or “char array_name[]” are the syntaxes to be followed for declaration. After declaration, the next thing we need to do is initialization. “array_name = new char[array_length]” is the syntax to be followed.


1 Answers

From JLS Sec 15.10.1:

The type of each dimension expression within a DimExpr must be a type that is convertible (§5.1.8) to an integral type, or a compile-time error occurs.

Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.

And from JLS Sec 5.6.1:

If the operand is of compile-time type Byte, Short, Character, or Integer, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of type int by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).

and

Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

So, any of Byte, Short, Character, Integer, byte, short, char or int are acceptable.

Hence 'a', a char literal, is allowed, and is promoted to the int value 97.

like image 102
Andy Turner Avatar answered Sep 30 '22 21:09

Andy Turner