# PrePostDemo

ornages
Offline
Joined: 2009-04-11

Hi!

Im doing the tutorial at the moment and i have a question about the prefix/postfix part.

Theres the following demo:

class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}

I dont understand the last line:
System.out.println(i); // "7"

shouldnt it be "5" as well? why is it "7"?

perminder_bhatia
Offline
Joined: 2009-04-12

Understanding ++ prefix & postfix operators

int i = 3;

i++; [b]// this is equivalent to i=3+1 hence i = 4[/b]

System.out.println(i); // "4" [b]due to above equation[/b]

++i; [b]// this is also equivalent to i=i+1 which makes i = 5[/b]

System.out.println(i); // "5" [b]due to above equation[/b]

System.out.println(++i); // "6"
[b]this is a bit trickey as when used in println it translates to two statements
since a prefix operator is used therefore statements will be:
i=i+1; // this makes i = 6
System.out.println(i); // this prints value 6[/b]

System.out.println(i++); // "6"
[b]in this case postfix operator is used therefor the statements become
System.out.println(i); // this prints value 6
i=i+1; // this makes i = 7[/b]

System.out.println(i); // "7" [b]due to above statement[/b]

i hope the solution is clear to your understanding