Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you increment an integer beyond its max value?

Tags:

java

math

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?

like image 721
Lyke Avatar asked Feb 27 '11 02:02

Lyke


People also ask

What happens if int exceeds max value?

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.

What would happen if I will use ++ in an 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.

Can you increment an integer?

Integer objects are immutable, so you cannot modify the value once they have been created.

What does integer max value do?

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.


1 Answers

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.

like image 172
Ted Hopp Avatar answered Oct 16 '22 19:10

Ted Hopp