0

Printing single java array element

I have several variations of the same program, each slightly different from the one before. Can someone give me an explanation why these produce the particular output for each individual implementation. 1) public class Main { public static void main(String[] args) { int x = 0; int[] arr = {2, 3, 5}; x = arr[x]; System.out.println(arr[x]); } } Output: 5 2) public class Main { public static void main(String[] args) { int x = 0; int[] arr = {2, 3, 5}; arr[x] = x; System.out.println(arr[x]); } } Output: 0 3) public class Main { public static void main(String[] args) { int x = 0; int[] arr = {2, 3, 5}; arr[x] = x++; System.out.println(arr[x]); } } Output: 3 4) public class Main { public static void main(String[] args) { int x = 0; int[] arr = {2, 3, 5}; arr[x] = ++x; System.out.println(arr[x]); } } Output: 3 I am especially confused about the last two implementations, with the use of "++x" vs "x++", and why they both produce the same result.

26th Aug 2019, 6:37 PM
Joshua Stamps
Joshua Stamps - avatar
4 ответов
+ 1
So I hope you know how array access operators work. If you don't, you should finish or redo the class lesson on Java arrays. You will understand the first two after that. Next, finish or redo the Java lesson on basic operations and learn about the prefix and postfix increment operators: ++a and a++. Having said that, I will explain the last two, but please review the lesson again :D arr[x] = x++; arr[x] is accessing arr[0] and setting it to x, which is zero. THEN, because of the postfix, x is incremented to 1. Now arr[x] is arr[1], which is 3. arr[x] = ++x; x is 0, so arr[0] is being set to 1, because the prefix increment happens in place. Now x is 1, so arr[1] is still 3.
26th Aug 2019, 6:57 PM
Zeke Williams
Zeke Williams - avatar
+ 1
Joshua Stamps I would have thought #2 was the easiest, and I don't know how I can explain it more than the code already is, but here I go: arr[x] = x is the same as arr[0] = 0 Then arr[x] is printed when x is still 0. It's like saying a = 0. b = a. What is b? Zero
26th Aug 2019, 9:11 PM
Zeke Williams
Zeke Williams - avatar
0
Zeke Williams Thank you, that makes sense for the last two. however, im still confused why in #2, “arr[x] = x;” outputs 0. Why would it not output the 0 element in the Array, which is 2? It seems that when we add an incrementer, whether pre or post, it pulls from the array, but when assigning arr[x] to x, it prints the value of x, which is 0. Why is this?
26th Aug 2019, 7:22 PM
Joshua Stamps
Joshua Stamps - avatar
0
1. x=arr[x]=arr[0]=2; print(arr[x]=arr[2]=5); 2. arr[x]=arr[0]=0; 3. arr[x]=arr[0]=0; x=0+1; print(arr[x]=arr[1]=3); 4. arr[x]=arr[0]=0+1; print(arr[x]=arr[1]=3);
26th Aug 2019, 8:36 PM
Solo
Solo - avatar