Array Access

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Array Access

Post 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

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Array Access

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests