Java: Trap in Arithmetic
By admin on Aug 28, 2008 in Java, open source
Have a look at the following code snippet
1: public static void main(String[] args) {
2: long result = 10 * 100 * 1000 * 10000 * 10000;
3: System.out.println(result);
4:
5: }
What would you expect?
Instead of printing “100000000000000″ , it prints “276447232″ on my machine.
This is because the arithmetic is performed as integer before assigning the value to result variable.
To get the correct result, just make one of the operands as long
1: public static void main(String[] args) {
2: long result = 10l * 100 * 1000 * 10000 * 10000;
3: System.out.println(result);
4: }
The above is a simple example. But this could possibly happen in real life. Some time we just perform arithmetic on integer variables and unknowingly hits the overflow error.
Post a Comment