Java Long primitive type maximum limit [duplicate]
I am using the Long primitive type which increments by 1 whenever my 'generateNumber'method called. What happens if Long reaches to his maximum limit? will throw any exception or will reset to minimum value? here is my sample code:
class LongTest {
private static long increment;
public static long generateNumber(){
++increment;
return increment;
}
}
Solution 1:
Long.MAX_VALUE
is 9,223,372,036,854,775,807
.
If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.
When that happens, it'll just wrap around to Long.MIN_VALUE
, or -9,223,372,036,854,775,808
as others have said.
Solution 2:
It will overflow and wrap around to Long.MIN_VALUE
.
Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.
Solution 3:
Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
It will start from -9,223,372,036,854,775,808
Long.MIN_VALUE.
Solution 4:
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?