Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java arrays - Why is the output '1' ?

Tags:

Why is the output in this example 1?

public static void main(String[] args){  int[] a = { 1, 2, 3, 4 };     int[] b = { 2, 3, 1, 0 };     System.out.println( a [ (a = b)[3] ] );    } 

I thought it would be 2. i.e., the expression is evaluated as:

a[(a=b)[3]] a[b[3]]    //because a is now pointing to b a[0]    

Shouldn't a[0] be 2 because a is pointing to b?

Thanks in advance.

like image 917
ziggy Avatar asked Dec 04 '11 11:12

ziggy


People also ask

What is the point of an array in Java?

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

How do you initialize an array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

How do you declare an empty array in Java?

Use List. clear() method to empty an array.


1 Answers

The arguments to each operator are evaluated left-to-right. I.e., the a in front of the [...] is evaluated before its contents, at which point it still refers to the first array.

like image 114
Marcelo Cantos Avatar answered Oct 21 '22 15:10

Marcelo Cantos