1
public class Testtt { public static void main(String [] args) { int x = 1; System.out.println(x++ + ++x + ++x); } } Result is 8 

how it prints 8 .. can any one please explain it ? o.O sorry to ask dumb question but i didnt get how the pre - post increment works

0

4 Answers 4

4

x++ returns 1, value of x is now 2
++x now returns 3, value of x is now 3
++x now returns 4, value of x is now 4
The returned values (1, 3 and 4) all add up to 8.

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

1 Comment

thank you sir :) got it now
2
System.out.println(x++ + ++x + ++x); 

1.) x++ => x = 1, increement later

2.) ++x => x =3, increement from step 1 , increement again for ++x

3.) ++x => x=4, increement again for ++x

finally - 1 + 3 + 4 

Comments

2

x++ increments after x value is used and ++x increments before x value is used I try to explain it using an example:

int x = 1; System.out.println(x++); // prints 1 but its value will be 2 after print x = 1; System.out.println(++x); // prints 2 but its value will be 2 after print System.out.println(x++ + ++x + ++x); // 1 + 3 + 4 = 8 

Comments

0

++x is called preincrement x++ is called postincrement

Example:

int x = 1, y = 1; System.out.println(++x); // outputs 2 System.out.println(x); // outputs 2 System.out.println(y++); // outputs 1 System.out.println(y); // outputs 2 

I can explain x++ + ++x + ++x by 1 + 3 + 4 = 8

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.