Tuesday, February 12, 2013

java.lang.Long.intValue() or casting long to int

Problem:

public static void main(String args[]) {
Long l = Long.MAX_VALUE;
System.out.println(l.longValue());
System.out.println(l.intValue());
System.out.println("---------------\n");
Long l2 = Long.valueOf(Integer.MAX_VALUE);
System.out.println(l2.longValue());
System.out.println(l2.intValue());
System.out.println("---------------\n");
Long l3 = Long.valueOf(Integer.MAX_VALUE) + 1;
System.out.println(l3.longValue());
System.out.println(l3.intValue());
System.out.println("---------------\n");
Long l4 = Long.valueOf(Integer.MAX_VALUE) + 2;
System.out.println(l4.longValue());
System.out.println(l4.intValue());
System.out.println("---------------\n");
Long l5 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE;
System.out.println(l5.longValue());
System.out.println(l5.intValue());
System.out.println("---------------\n");
Long l6 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE + 1;
System.out.println(l6.longValue());
System.out.println(l6.intValue());
System.out.println("---------------\n");
Long l7 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE + 2;
System.out.println(l7.longValue());
System.out.println(l7.intValue());
System.out.println("---------------\n");
}




9223372036854775807
-1
---------------

2147483647
2147483647
---------------

2147483648
-2147483648
---------------

2147483649
-2147483647
---------------

4294967294
-2
---------------

4294967295
-1
---------------

4294967296
0
---------------




Solution:

use one of the suggested methods mentioned at this thread:

http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java

No comments:

Post a Comment