Java Long primitive type maximum limit

Java

Java Problem Overview


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;
   }
}

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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: https://stackoverflow.com/questions/12348067/java-number-exceeds-long-max-value-how-to-detect

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1591156View Question on Stackoverflow
Solution 1 - JavaKreaseView Answer on Stackoverflow
Solution 2 - JavaZuttyView Answer on Stackoverflow
Solution 3 - JavaAjay SView Answer on Stackoverflow
Solution 4 - JavajsedanoView Answer on Stackoverflow