preincrement / postincrement in java

后端 未结 5 553
粉色の甜心
粉色の甜心 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:24

    Things to know:
    1. Java evaluates expressions from left to right
    2. ++i-pre-increment i.e increment before assignment
    3. i++ - post increment i.e. increment after assignment

    System.out.println(i++ + i++);
    

    op1=i++
    op2=1++
    sum=op1+op2
    i++ - post increment the value of i

    1. Assign i to op1 and then increment the value of i.op1=1,i=2
    2. Assign i to op2 and then increment the value of i.op2=2,i=3
    3. Sum=3

      System.out.println(++j + ++j);

    op1=++j
    op2=++j
    sum=op1+op2
    ++i - Pre increment the value of i

    1. now at first j will be incremented to 2 and then assigned to op1.
    2. Then, j will again be incremented to 3 and assigned to op2
    3. Then, op1 and op2 will be added to print the sum as 5 and the value of j will be

      System.out.println(k++ + ++k);

    op1=k++
    op2=++k
    sum=op1+op2

    1. Assign the value of k to op1 and then increment k. op1=1,k=2

    2. Increment the value of k and then assign to op2. op2=3,k=3

    3. Sum = 4

      System.out.println(++l + l++);

    Apply the above logic here also.

提交回复
热议问题