Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Long won't print properly

Tags:

java

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?

like image 910
f20k Avatar asked Mar 04 '11 14:03

f20k


3 Answers

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.

like image 199
Jon Skeet Avatar answered Oct 29 '22 09:10

Jon Skeet


How about:

long mult = 2147483647L + 2147483647 + 2;
like image 3
Konrad Garus Avatar answered Oct 29 '22 10:10

Konrad Garus


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);
like image 1
Manoj Avatar answered Oct 29 '22 09:10

Manoj