Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# Arrays

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.
geeta vemula
Ranch Hand

Joined: Jul 18, 2008
Posts: 208
see te following part of code and its execution

{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;

}

a[1]=0 ---> {1,0,3,4}
a[0]=0 --->{0,0,3,4}
a[3]=0 ---> {0,0,3,0}
a[0]=0 --->{0,0,3,0}

iterate through the loop and print the value which gives 0030

Hopw this helps you.

Geeta Vemula
Patel Chintan
Ranch Hand

Joined: Mar 01, 2007
Posts: 80
Originally posted by Abhi vijay:
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.

Hi abhi here is explaination :

Intial Values:
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4

Now, how for loop executes:
1) step
i=arr[0]=1
that means =>arr[i]=arr[1]=0
arr[0]=1
arr[1]=0 <--- Effected
arr[2]=3
arr[3]=4

2) step
i=arr[1]=0
that means =>arr[i]=arr[0]=0
arr[0]=0 <--- Effected
arr[1]=0
arr[2]=3
arr[3]=4

3) step
i=arr[2]=3
that means =>arr[i]=arr[3]=0
arr[0]=0
arr[1]=0
arr[2]=3
arr[3]=0 <--- Effected

now Just print in next for looop.

Chintan Patel, SCJP1.5, http://datewithjava.blogspot.com
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Thanks a lot guys.

I agree. Here's the link: http://aspose.com/file-tools

subject: Arrays