The difference between n++ VS ++n in Java

后端 未结 7 2065
醉酒成梦
醉酒成梦 2021-01-01 03:56

My Java teacher said it was better to use ++n instead of n++, I am not seeing the logic behind this. Does anyone know?

7条回答
  •  无人及你
    2021-01-01 04:41

    Interesting example that illustrates the difference:

    public class Main {
        public static void main(String[] args) {
            for (int i=0; i<5; /*not incrementing here*/ ) 
                System.out.println(i++);
        }
    }
    

    output: 0 1 2 3 4

    public class Main {
        public static void main(String[] args) {
            for (int i=0; i<5; /*not incrementing here*/ ) 
                System.out.println(++i);
        }
    }
    

    output: 1 2 3 4 5

    Notice that neither for-loop performs the incrementation since it does not matter there.

提交回复
热议问题