Why do I need to add an “L” letter to get the correct long value? And what is the other value?
long oneYearWithL = 1000*60*60*24*365L;
long oneYearWithoutL = 1000*60*60*24*365;
System.out.println(oneYearWithL);//gives correct calculation result : 31536000000
System.out.println(oneYearWithoutL)//gives incorrect calculation result: 1471228928
Your first value is actually a long (Since
365Lis along, and1000*60*60*24is aninteger, so the result ofmultiplyingalongvalue with anintegervalue is alongvalue.But 2nd value is an integer (Since you are mulitplying an
integervalue with anintegervalue only. So the result will be a32-bitinteger. Now the result obtained for thatmultiplicationis outside the actual range of integer. So, before getting assigned to the variable, it is truncated to fit into valid integer range.Take a look at the following print statement: –
When you run the above code: –
Output: –
So, you can see the difference..
So, if you don’t add that
Lat the end of your number, the 4 most significant bit is removed from the first binary string..So, the string becomes..
(which you get as output)
UPDATE: –
From the above explanation, you can also understand that, even in the first assignment, if the result of your
multiplicationofintegersbefore multiplying it with365Lgoes out of range, then again it will be truncated to fit in integer range, or converted to2's complement representationif required, and then only it will be multiplied with thelong value - 365L.For e.g: –
In the above example, consider the first part –
1000*60*60*24*30. The result of this multiplication is: –2592000000. Now lets’ see how it is represented inbinary equivalent: –Decimal representation of the
2's complementrepresentation is1702967297. So,2592000000is converted to-1702967297, before getting multiplied to365L. Now since, this value fits in theinteger rangewhich is : –[-2147483648 to 2147483647], so it will not be truncated further.So, the actual result will be: –
So, all these stuffs just considers the actual
typeof final result on applying the arithmetic operation. And this check is performed on each temporary result of operations moving fromleft to right(considering operators withleft-to-rightassociativity). If any temporary result is found to be out of range, then that is converted accordingly to fit in the required range, before moving forward with next operation.UPDATE 2: –
So, instead of: –
if you move your
365Lat the start, then you will get the correct result: –Because, now your
temporaryresult will be of typelong, and is capable of holding that value.