0

I am using Java SE Development kit 8 update 25(64 bit). I have read the "Primitive Data Types" java tutorial from The Java™ Tutorials and according to this specification the long type can hold the maximum value of (2 to the power 64)-1 which is 18446744073709551615.

But the below code throws "integer number too large" error message.

public class SampleClass
{
    public static void main (String[] args)
    {        
        Long longMaxValue= 18446744073709551615L /* UInt64.MaxValue */;
    }
}

Also the Long.Max_Value only returns 9223372036854775807 . Why? I need to store the value 18,446,744,073,709,551,615 as a constant in java. What should I do?

Any help will be appriciated.

IMK
  • 654
  • 9
  • 15
  • where is below 'code' ? – aberry Mar 09 '15 at 07:11
  • from javadoc :The signed long has a minimum value of -2 power of 63 and a maximum value of 2 power 63-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 power of 64-1 – aberry Mar 09 '15 at 07:14
  • Yes aberry, The value am using is (2 to the power of 64)-1 which is equivalent to 18446744073709551615 and I am using java SE 8. So why am I getting the error? – IMK Mar 09 '15 at 07:19

1 Answers1

8

The max positive value of long is (2 to the power of 63) - 1, since long in Java is signed, and therefore can hold negative integers. The left most bit is reserved for the sign, which leaves 63 bits for the value itself.

You can use BigInteger if Long.MAX_VALUE is not big enough for you.

Another option, if you are using Java 8 and wish to treat long as unsigned is to use the unsigned methods of Long :

For example :

long l = parseUnsignedLong("18446744073709551615");

If you print l with System.out.println(l), you'll see a negative value, but if you print Long.toUnsignedString(l) you'll see the unsigned value.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • The specification says this (2 to the power of 63) is for the previous versions of Java SE 8. Please refer the specification that points as below "The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -(2 to the power 63) and a maximum value of (2 to the power 63)-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of (2 to the power 64)-1." – IMK Mar 09 '15 at 07:16
  • 1
    @MeikandaNayanar.I I just edited my answer to account for Java 8. The primitive long is still sighed, but some method were added in Java 8 to the Long class to support unsigned Long. – Eran Mar 09 '15 at 07:20
  • 1
    See this answer which is basically a duplicate w.r.t. the rather confusing (imho) documentation on unsigned int and long http://stackoverflow.com/questions/25556017/how-to-use-the-unsigned-integer-in-java-8. – J Richard Snape Mar 09 '15 at 07:24