Page 1 of 1

Array Access

Posted: Fri Mar 01, 2013 12:42 pm
by Sweetpin2
public class Test_Array2 {

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


public static void main(String[] args) {


int index = 1;
int t;
try {
t = getArray()[index=2]++;
System.out.println(t);
}
catch (Exception e) { e.printStackTrace();} // empty catch
System.out.println("index = " + index);

}


}

Why for above code the o/p for t is 0, shouldn't it be 1 after post increment?

When i change the code to t = getArray()[index=2]+ 1; i am getting o/p for t as 1

Re: Array Access

Posted: Fri Mar 01, 2013 2:46 pm
by admin
post increment increments the number after the original value is used for the assignment. So the new incremented value is lost in this case.
When you use + 1 instead of ++, you increment the value and then do the assignment.