2

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
  • 3
    Yes, an int overflow: positive int goes upto 2^31 ≈ 2*10^9, so 9 digits. Your product 3+3+3+3+3 = 12 digits. Mind that more safe would have been 1000L, as 1000*60*60*24 already reaches 9 digits. – Joop Eggen Oct 24 '19 at 07:40
  • 1
    `int * long = long` in first case. And in second case it multiplies some integers together, converts it to a long and then assigns the result to a `longWithoutL` variable. – Sudhir Ojha Oct 24 '19 at 07:42

2 Answers2

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

0

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

George Weekson
  • 483
  • 3
  • 13