One Two Three
One Two Three

Reputation: 23547

Array initialisation in java

I noticed one could write code like this, which is perfectly normal, by the way:

int arrays[] = {1, 2, 3};
for (int n : arrays)
   System.out.println(n);

But I don't see how the following is illegal:

for (int n : {1, 2, 3})
   System.out.println(n);

From a compiler writer's point of view, this does not introduce any ambiguity, does it? The type of the array can be expected to be the same type as the element declared previously. In other words, n is declared as int, so the array must be int[]

Upvotes: 33

Views: 3264

Answers (5)

Sumit Sharma
Sumit Sharma

Reputation: 1867

I think whenever we create a variable , the compiler automatically allocates memory to it.The amount of memory created depends upon the type of compiler which you are using.In the first statement you declare an array with the inputs, compiler automatically create space for the array element present in the array but when you declare the array in for loop it create only 2 byte of each run.

For ex.

int x; // create 2 bytes of memory

This space is permanently allocated to int x whether you insert value in this space or not.

int x = "123"; // This code also take 2 bytes of memory and contain value = 123

Similarly,

int a[] ={1,2,3} // create 6 byte of space in memory, 2 byte for each integer variable.

On the other hand when you declare the array in for loop without using the new identifier the compiler assume that it is an int variable and create only 2 bytes of memory space and program gives error.

for (int n : {1, 2, 3}) // create only 2 bytes of memory

So by using the new identifier we allocate a new memory space and insert values which is given in the curly braces.

Upvotes: 0

user2282158
user2282158

Reputation: 23

To be honest, the only fallacy I see in your explanation is how can you tell a computer to go through an object/memory that does not exist?

You have to create something to let go through it first, here, you have created nothing and the logical fallacy exists in your head because you have thought more deep than the creation rules of Java itself.

Don't worry, I find myself in situations like you but the most important thing is to learn how Java was programmed first!

Upvotes: -1

Makoto
Makoto

Reputation: 106508

From the Java Language Specification, §10.6 - Array Initializers:

An array initializer is written as a comma-separated list of expressions, enclosed by braces { and }.

A trailing comma may appear after the last expression in an array initializer and is ignored.

Each variable initializer must be assignment-compatible (§5.2) with the array's component type, or a compile-time error occurs.

It is a compile-time error if the component type of the array being initialized is not reifiable (§4.7).

An array initializer is part of an array creation expression, which does define that you require one of these four forms to successfully initialize an array:

ArrayCreationExpression:
    new PrimitiveType DimExprs Dimsopt
    new ClassOrInterfaceType DimExprs Dimsopt
    new PrimitiveType Dims ArrayInitializer 
    new ClassOrInterfaceType Dims ArrayInitializer

Again, from the specs:

It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7). Otherwise, the ClassOrInterfaceType may name any named reference type, even an abstract class type (§8.1.1.1) or an interface type (§9).

This is why you require the syntax new int[] {1, 2, 3}.

EDIT: To get more into the nuances of your question:

From a compiler writer's point of view, this does not introduce any ambiguity, does it? The type of the array can be expected to be the same type as the element declared previously. In other words, n is declared as int, so the array must be int[]

No. There is ambiguity. As a for-instance, what is the difference between the following two statements?

int[] arr1 = new int[] {1, 2, 3};
short[] arr2 = new short[] {1, 2, 3};

The major difference is what they compile down to in bytecode. One is obviously an int, the other is obviously a short. However, without the ability to tell which data type is which (without the values in the array exceeding Short.MAX_VALUE), it would be impossible to assert that, this array, beyond a shadow of a doubt, is an int. Recall that a short falls into the range of an int, so you can easily get into some tricky/bizarre scenarios when using that.

It gets more fun: this is valid code.

for(int i : arr2) {
    System.out.println(i);
}

Again, as long as the elements in arr2 don't exceed Short.MAX_VALUE, you can get away with this ambiguous reference between short and int.

This is another reason why the compiler can't just infer that you mean int. You could mean short.*

*: Not that many people ever would, but that's just in case there are that do.

Upvotes: 36

Chris Chambers
Chris Chambers

Reputation: 1365

Because arrays are objects, and have to be instantiated. Java does not recognize {} by itself as an array. It does, however, permit you to use a code block (i.e. code in {..}) to define the initial elements of the array.

The way you accomplish this is described by the answer above.

Upvotes: 7

Eng.Fouad
Eng.Fouad

Reputation: 117675

You need this syntax:

for(int n : new int[]{1, 2, 3})
   System.out.println(n);

Upvotes: 36

Related Questions