0

I started learning Java this month and am currently trying to understand arrays. I'm testing myself with small exercises and got stuck in this problem. Before running the code, I wrote my own expectations of what should the results be as comments. Everything was fine except the first one, why is it printing 4 instead of 2? Where did this 4 come from, could anyone please explain? Here's the code:

public class Exercise1 {
public static void main(String[] args) {
    int[] array = {9, 5, 8, 1, 11, 3, 10};
    array[0] = 2;          // should be 2
    array[1]++;              //it was 5 now a[1]++ is 6
    array[2] = array[0] + array[1];         // a[0] is 2 and a[1] is now 6 so answer is 8
    array[3] = array[2-1];       //array[1]=6
    array[4] = array.length;    //array.length not same as index, so length's actually 7, only index from 0 to 6, so7
    array[5] = ++array[0];          //array[0]=2 so ++that is 3
    array[6] = array[0]++;         //array[0]=2 s0 that++ is 3
    for (int i = 0; i < array.length; i++)
        System.out.println(array[i]);
  
}

and output on Intellij is: 4 6 8 6 7 3 3

Sammie
  • 17
  • 5

0 Answers0