141

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;
   }
}
Ahmad Hosny
  • 597
  • 1
  • 6
  • 23
user1591156
  • 1,945
  • 4
  • 18
  • 31
  • 3
    Pretty big range - `8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.` http://www.cafeaulait.org/course/week2/02.html – Caffeinated Mar 19 '13 at 16:48
  • 5
    Once you reached to max value, next it will get rollover to min value. – Smit Mar 19 '13 at 16:49

4 Answers4

424

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.

daiscog
  • 11,441
  • 6
  • 50
  • 62
Krease
  • 15,805
  • 8
  • 54
  • 86
47

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.

Zutty
  • 5,357
  • 26
  • 31
10

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.
Ajay S
  • 48,003
  • 27
  • 91
  • 111
10

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?

Community
  • 1
  • 1
jsedano
  • 4,088
  • 2
  • 20
  • 31