Post and Pre increment operators

2020-04-03 10:22发布

When i run the following example i get the output 0,2,1

class ZiggyTest2{

        static int f1(int i) {  
            System.out.print(i + ",");  
            return 0;  
        } 

        public static void main(String[] args) {  
            int i = 0;  
            int j = 0;  
            j = i++;   //After this statement j=0 i=1
            j = j + f1(j);  //After this statement j=0 i=1
            i = i++ + f1(i);  //i++ means i is now 2. The call f1(2) prints 2 but returns 0 so i=2 and j=0
            System.out.println(i);  //prints 2?
        } 
    } 

I don't understand why the output is 0,2,1 and not 0,2,2

标签: java scjp ocpjp
7条回答
虎瘦雄心在
2楼-- · 2020-04-03 10:55

The solution can be understood from this example

public static void main(String[] args) {
    int i = 0;
    i = i++;
    System.out.println("i is" + i);
}
/* The output is "i is 0" */

Hence from this line,

i = i++ + f1(i); 

Your i is still 1 and obviously the function is going to return 0. Which is again stored in i and hence the value 1. Instead of the updated value of i being stored in i, you are overriding it by the assignment operator.

查看更多
登录 后发表回答