Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

preincrement / postincrement in java

Can someome help me to understand why:

int i=1;
int j=1;
int k=1;
int l=1;

System.out.println(i++ + i++);  
System.out.println(++j + ++j);  
System.out.println(k++ + ++k);  
System.out.println(++l + l++);

give:

3
5
4
4

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Variable++ means: Increment variable AFTER evaluating the expression.

++Variable means: Increment variable BEFORE evaluating the expression.

That means, to translate your example to numbers:

System.out.println(i++ + i++);  //1 + 2
System.out.println(++j + ++j);  //2 + 3
System.out.println(k++ + ++k);  //1 + 3
System.out.println(++l + l++);  //2 + 2

Does this clear things up, or do you need further explanations?

To be noted: The value of all those variables after the 'println' equal '3'.

Since the OP asked, here's a little 'use-case', on where this behaviour is actually useful.

int i = 0;
while(++i < 5) {           //Checks 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Four runs
    System.out.println(i); //Outputs 1, 2, 3, 4 (not 5) 
}

Compared to:

int i = 0;
while(i++ < 5) {           //Checks 0 < 5, 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Five runs
    System.out.println(i); //Outputs 1, 2, 3, 4, 5
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...