programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# SCJP Preparation

Ashish Soni
Greenhorn
Posts: 24
All ,

I am going through one of the SCJP Mock test and encountered a question on array and having tough time to understand the result , Please help and explain ..

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

The ans is 1

Deepak Bala
Bartender
Posts: 6663
5
Take it step by step

x = y assigns y to x. So now x and y are the same

2 3 1 0

The third index in this array is 0.

x[0] is 1.

Dont worry about getting questions like this. This is pretty twisted. Good luck

Roopa Maheshkumar
Greenhorn
Posts: 26
Hi... i have a little confusion here.

it seems to me that x[0] is 2 since x=y = {2,3,1,0}. Please clarify.

Meena Ajay
Ranch Hand
Posts: 38
Originally posted by Roopa Maheshkumar:
Hi... i have a little confusion here.

it seems to me that x[0] is 2 since x=y = {2,3,1,0}. Please clarify.

--------------------------------------------------
Please check if this explanation helps
if someone finds this incorrect, please correct me

Consider the left to right evaluation order in x[ (x=y)[3] ];
First the value of outermost x is evaluated which is reference to the first array {1,2,3,4}
Now the assigment is considered x=y which is reference to the second array { 2,3,1,0}
so value of (x=y)[3] is 0 which is the element at index 3 in the second array
Now the value is substituted ...so x[(x=y)[3]] becomes x[0]
Now the value of the x[0] as per the first array is 1
After the execution of this statement, the x and y references both point to the second array only.

To understand better, introduce a print statement
System.out.println( x[ 0] );
after the System.out.println( x[ (x=y)[3] ] );
That will give a different result 2..because now reference x also points to second array after the assignment..
[ May 31, 2008: Message edited by: Meena MeenakshiSubramanian ]

niveditha ramana
Greenhorn
Posts: 6
Originally posted by Roopa Maheshkumar:
class SCJPTest
{
public static void main(String[ ] args)
{
int[] x = { 1, 2, 3, 4 };
int[] y = { 2, 3, 1, 0 };
System.out.println( x [ (x = y)[3] ] );
}
}

(x=y) is within the scope of x[(x=y)[3] ]

so x[ (x=y)[3] ] will give x[0] first and there scope of x=y is over
and x[0] is now 1

thank you

Deepak Bala
Bartender
Posts: 6663
5
"Ashish Soni " what is the source of this question ? You need to quote it when you post here

Ashish Soni
Greenhorn
Posts: 24
This is from enthuware mock exam.