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 int
s. 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With