Reputation: 61
When I multiply long
s with L
prefix I get the result 31536000000
.
When I multiply long
s without L
prefix I get the result 1471228928
.
How the result getting varies?
I am thinking number exceeds the `int? range but not sure.
long longWithL = 1000*60*60*24*365L;
long longWithoutL = 1000*60*60*24*365;
System.out.println(longWithL);
System.out.println(longWithoutL);
Output:
31536000000
1471228928
Upvotes: 2
Views: 121
Reputation: 20931
A plain number is perceived as int
by the Java Standard always. If you wish to make the compiler know that the number which is being operated is other than integer type, the postfix letter is required, e.g. L
, F
(for floating point numbers, similar idea).
By the by, as an additional information, +
, -
, *
, /
operators' left-hand side has more precedence vis-à-vis its left-hand side's. So, for example, 10L*2*3*4*5
results in type of long
. To make sure for the mentioned example, the following image can be examined.
Upvotes: 2
Reputation: 483
it outputs different result because of overflow in Integer Result. when you write long longWithoutL = 1000*60*60*24*365;
. java read that numbers as Integers. multiplication is going out of the bounds of Integer and java tries to fit it into the Integer. To have Correct output try to use Suffix like L
, D
, F
. same it true if you write 4.676 java assumes that number is Double
this question already have an answer here and here
Upvotes: 0