Er Rahul Raj
Er Rahul Raj

Reputation: 61

How output changes for a number when multiplying with long?

When I multiply longs with L prefix I get the result 31536000000.

When I multiply longs 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

Answers (2)

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.

enter image description here

Upvotes: 2

George Weekson
George Weekson

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

Related Questions