File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why will I get this output? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why will I get this output?" Watch "Why will I get this output?" New topic
Author

Why will I get this output?

Jayes Herryl
Greenhorn

Joined: Jun 09, 2006
Posts: 7
Hello all,

Could someone help to explain why I am getting such output from running this piece of code?

class Test{
public static void main(string[] args){
int[] arr = {1, 2, 3, 4};
for(int i : arr) {
arr[i] = 0;
System.out.println(i + " " + arr[i]);
}
for(int i : arr)
System.out.print(i);
}
}
OUTPUT:
1 0
0 0
3 0
0 0
0030

How come the first loop gives 1 as the first value for i and gives 0 to the first i at the second loop? After the first loop, elements in arr are all initialized to zero, then why shouldn't the second loop output 0000??
Is it because i is not initialized?

Thanks for any advice in advance!!
Michael Valentino
Ranch Hand

Joined: Nov 01, 2005
Posts: 96
<hr></blockquote>

first loop:
in the first iteration, i is assigned the value of arr[0], which is 1. the line arr[i] = 0 is executed, so now arr[1] = 0. arr is now {1, 0, 3, 4 }. The output to the screen is: 1 0

Second iteration, i = arr[1], so i = 0. arr[i] = 0 executes so now arr[0] = 0. arr is now {0, 0, 3, 4 }. The output to the screen is: 0 0

Third iteration: i = arr[2] so i = 3. arr[i] = 0 executes so now arr[3] = 0. arr is now {0, 0, 3, 0}. The output to the screen is: 3 0

Last iteration: i = arr[3] so i = 0. arr[i] = 0 executes so arr[0] = 0. arr is now {0, 0, 3, 0}. The output to the screen is: 0 0


Finally, the second for loop executes and prints out the modified array. In the code, at each iteration, i is assigned the next value of arr[]. If you followed the first loop, the values in the array at this point should be clear: 0030.

So the final output should look like this:


Make sense?
[ June 13, 2006: Message edited by: Michael Valentino ]

SCJP 1.4, SCWCD J2EE 1.4, SCJD J2SE 1.5, SCBCD J2EE 1.3, SCDJWS (In Progress)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why will I get this output?