0

can you please explain me why the following piece of code doesn't increment the element resulted from an array extraction on a specific position.

public class ArrayTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int i =1;
        int x = getArray()[i]++;
        System.out.println(x); // it should not be 10 displayed, instead of 9 as it is?


    }

    public static int[] getArray (){
        return new int [] {1,9,8,};
    }

}

The value of local variable i should not be increased to 10 when it's displayed after post incrementation?

I understand how post and pre increment works. You post increment a value and next time it will call it it will have that value updated. Moreover if u pre increment a value the value is incremented and new value is updated on spot. However in my case the value is not updated when at next call, as it should be with post incrementation.

I am missing something, it's something different with returning from an array ?

Sincerely,

SocketM
  • 564
  • 1
  • 19
  • 34
  • 5
    Read about post-increment and pre-increment operator. – Mritunjay May 25 '17 at 07:13
  • 1
    int x = ++getArray()[i]; will give you your desired result..go through operators to understand the concepts – Akshay May 25 '17 at 07:15
  • int x = ++getArray()[i]; System.out.println(x); – Kangkan May 25 '17 at 07:17
  • I understand how post and pre increment works. You post increment a value and next time it will call it it will have that value updated. Moreover if u pre increment a value the value is incremented and new value is updated on spot. However in my case the value is not updated when at next call, as it should be with post incrementation. I am missing something, it's something different with returning from an array ? – SocketM May 25 '17 at 07:47
  • Yes pre incrementation works on my value returned from an array however why not post incrementation. – SocketM May 25 '17 at 07:48
  • I solved myself the issue. The calls returns a value not a variable, therefore you can't use a post increment on a value. Post and pre-increment works only on variables. – SocketM May 26 '17 at 08:14

1 Answers1

0

If you changed the line

int x = getArray()[i]++;

to

int x = ++getArray()[i];

You will know the differences. (post-increment and pre-increment operator)

PSo
  • 958
  • 9
  • 25