开发者

Java Long won't print properly

This must be very silly but, I am trying to do the following:

long mult  = 2147483647 + 2147483647 + 2;
System.out.println(mult);  // result = 0

Now, my varaible开发者_如何转开发 mult would be a 10 digit number, well in the range of long. So I do not understand why it is printing out 0 as a result. Can anyone explain why?


The arithmetic is being done with int instead of long, because the three constant values are ints. The fact that you're assigning to a long variable is irrelevant. Try this:

long mult  = 2147483647L + 2147483647L + 2L;

You could probably get away with making just one of the literals a long literal if you're careful - but I'd personally apply it to all of them, just to make it clear that you want long arithmetic for everything.


How about:

long mult = 2147483647L + 2147483647 + 2;


thats because when you give any number directly like num1 + num2 they are taken as integers and since the value is out of bounds in this case you will get either 0 or other output depending on the input.

You can easily resolve this by changing to

long mult  = 2147483647;
mult += 2147483647;
mult += 2;
System.out.println(mult);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜