preincrement / postincrement in java

后端 未结 5 544
粉色の甜心
粉色の甜心 2020-12-01 17:35

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


        
5条回答
  •  失恋的感觉
    2020-12-01 18:19

    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
    }
    

提交回复
热议问题