Why does incrementing a Java int eventually result in a negative number?

后端 未结 4 541
醉梦人生
醉梦人生 2020-11-30 15:30

I was trying to check different inputs and creating infinite loops in java and I found that once the int is getting incremented over the maximum limit it turns

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 15:46

    According to the documentation:

    The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 (0x80000000) and a maximum value of 2,147,483,647 (0x7FFFFFFF) (inclusive)

    So when you add one to an integer's max value:

    0x7FFFFFFF + 0x00000001 = 0x80000000 (-2,147,483,648)

提交回复
热议问题