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

后端 未结 7 2013
醉酒成梦
醉酒成梦 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:44

    Example:

    int n = 10;
    int a = n++; // a is 10
    int b = n; // b is 11
    int c = ++n; // c is 12
    

    The difference is that the value of ++n is n + 1 and the value of n++ is n.

    Neither is better, they do the same thing. You shouldn't really rely on the difference between the two in your programs because 1.) quite a few people don't understand the difference and 2.) the same thing can be accomplished far more simply.

    0 讨论(0)
提交回复
热议问题