In Java, what happens when you increment an int (or byte/short/long) beyond it's max value? Does it wrap around to the max negative value?
Does AtomicInteger.getAndIncrement()
also behave in the same manner?
Overflow in int As int data type is 32 bit in Java, any value that surpasses 32 bits gets rolled over. In numerical terms, it means that after incrementing 1 on Integer. MAX_VALUE (2147483647), the returned value will be -2147483648. In fact you don't need to remember these values and the constants Integer.
By a++ , a new instance of Integer is created, and the value of it comes from adding a 1 to the original Integer object which both a and b are pointing to, and then a is re-assigned to this new object.
Integer objects are immutable, so you cannot modify the value once they have been created.
Integer. MAX_VALUE represents the maximum positive integer value that can be represented in 32 bits (i.e., 2147483647 ). This means that no number of type Integer that is greater than 2147483647 can exist in Java.
From the Java Language Specification section on integer operations:
The built-in integer operators do not indicate overflow or underflow in any way.
The results are specified by the language and independent of the JVM version: Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
and Integer.MIN_VALUE - 1 == Integer.MAX_VALUE
. The same goes for the other integer types.
The atomic integer objects (AtomicInteger
, AtomicLong
, etc.) use the normal integer operators internally, so getAndDecrement()
, etc. behave this way as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With