Max Value of primitive long seems incorrect.
I wrote a little program to test the max value that can be stored in a primitive long , but got confusing results
Here's the stuff I tried so far
package test91;
publicclass TestLong{
publicstaticvoid main(String[] args){
//The following prints Long.MAX_VALUE : 9223372036854775807
System.out.println("Long.MAX_VALUE : " + Long.MAX_VALUE);
//The following gives a compile time error
//long testMaxPossible = 9223372036854775807;
//test91\TestLong.java:9: integer number too large: 9223372036854775807
//long testMaxPossible = 9223372036854775807;
//The following compiles with no compalints
long testMax = Long.MAX_VALUE;
//The max value of long is: 2^63 -1
long twoRaisedTo62 = 1;
for (int i = 1; i <= 62; i++){
twoRaisedTo62 = twoRaisedTo62 * 2;
}
//The following gives a negative number: twoRaisedTo62 -9223372036854775808
System.out.println("twoRaisedTo62 " + twoRaisedTo62);
}
}
When I assign 9223372036854775807 which seems legal to a primitive long variable, I get compile time error as shown above in the code.
So why does assigning 9223372036854775807 to a long primitive not work?
Then I read in the JavaDocs for Long that the max possible value is
2^63 -1(two raised to 63 minus 1) , so I tried to calculate 2^62 iteratively, but at the end I get a negative value.
I'm totally confused with the above output.
I would expect this assignment to work:
long testMaxPossible = 9223372036854775807; and would expect twoRaisedTo62 to hold a positive value.
Any explanation is appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
java version "1.6.0_01"
Java(TM) SE Runtime Environment (build 1.6.0_01-b06)
Java HotSpot(TM) Client VM (build 1.6.0_01-b06, mixed mode, sharing)
javac 1.6.0

