3

I wondering to know why this snippet of code give output 112
How this last digit 2 was creating?

public static void main(String[] args) { int i = 0; System.out.print(++i); System.out.print(i++); System.out.print(i); 

Why does this happen?

3
  • 1
    This doesn't have anything to do with iteration. Commented May 12, 2013 at 9:58
  • ++i means increment and read i, i++ means read and increment i, and i means read i. Commented May 12, 2013 at 10:02
  • 1
    As a general rule; never do this, it leads to unreadable code, increment and use a value seperately Commented May 12, 2013 at 10:35

7 Answers 7

6

Your snippet it's translated as

int i = 0; i = i + 1; // 1 System.out.print(i); // 1 System.out.print(i); // 1 i = i + 1; // 2 System.out.print(i); // 2 

That's why the final result it's a 2.

++i it's incrementing the variable before being called by the print method and i++ it's incrementing the variable after the method execution.

Sign up to request clarification or add additional context in comments.

Comments

3

i++ is the post-increment operator, which has expression value the old value of i, but a side-effect of incrementing i. The value is 1, but it leaves i changed to 2.

Comments

2

When we use post or pre increment operator it increases the value.

Post increment operator (i++) assigns the value first, then increments it. Pre increment operator (++i) increments first then assigns the value. They both behave like this :

int i=0; i=i++; System.out.println(i); //1 i=++i; System.ou.println(i); //1 

Comments

2

When this code runs:

public static void main(String[] args) { int i = 0; //i=0; System.out.print(++i); // increments i to i=1, and prints i System.out.print(i++); // prints i and then increments it to i=2 System.out.print(i); // prints i, i.e. 2 } 

Comments

1

i is initially 0, then it is pre-incremented and printed so you have the first 1, then it is printed again and you have the second 1, then post-incremented, then printed for the last time and you have the 2

Comments

1

Simply;

In post increment, the increment is done after the variable is read.

In pre increment, the variable value is incremented first, then used in the expression.

Comments

1

You are applying two increments on i. The initial value was 0 so after two increments (++i and i++ )it will become 2.

Both i++ and ++i are incrementing the value of i by one.

They are similar to

i = i+1; 

but the ++i one increments the value of i then uses it, so 0 becomes 1 and printed out, while the i++ first uses the value and then increments the value of i, so the printed value is 1 and then it becomes 2 hence the last digit(the final value of i) is 2.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.