Why doesn't Integer.parseInt(“1”)++ work in Java?

后端 未结 5 536
渐次进展
渐次进展 2020-12-30 00:26

I\'ve got the following line of code:

suffix = suffix.isEmpty() ? \"1\" : Integer.toString(Integer.parseInt(suffix)+1);

in a block where su

相关标签:
5条回答
  • 2020-12-30 01:03

    The ++ operator should update the value of its argument, so the argument should have a fixed position in memory to be updated. For this reason, the argument should be a variable*. In this case, the argument is Integer.parseInt(suffix), has no fixed memory address to be updated at all.

    Intuitively, Integer.parseInt(suffix)++ is roughly equivalent to Integer.parseInt(suffix) = Integer.parseInt(suffix) + 1. But Integer.parseInt(suffix) is just an integer value, not associated to a fixed position in memory, so the code above is almost the same thing of, let us say, 32 = 32 + 1. Since you cannot assign a new value to 32 (neither to Integer.parseInt(suffix)) then there is no sense in supporting the ++ operator.

    The good news is that this does not cause any problems at all! Instead of Integer.parseInt(suffix)++, write Integer.parseInt(suffix)+1.

    * Or, as it is most commonly called, an l-value, or an address value.

    0 讨论(0)
  • 2020-12-30 01:13

    ++ expects an assignable value, i.e. a variable. Integer.parseInt returns a value that cannot be assigned. If you need a value plus one, use Integer.parseInt(suffix)+1 instead.

    0 讨论(0)
  • 2020-12-30 01:15

    The int is an rvalue. Since it isn't bound to a variable you cannot use post-incrementation.

    0 讨论(0)
  • 2020-12-30 01:18

    ++ requires an lvalue (an assignable value).

    Integer.parseInt(suffix) is not an lvalue.

    Note that i++ is not the same as i+1.

    0 讨论(0)
  • 2020-12-30 01:28

    Writing i++ is a shortcut for i=i+1; if you were to 'read it in english' you'd read it as "i becomes current value of i plus one"

    which is why 3++ doesn't make sense you can't really say 3 = 3+1 (read as 3 becomes current value of 3 plus one) :-)

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