class Main {
public static void main (String[] args){
long value = 1024 * 1024 * 1024 * 80;
System.out.println(Long.MAX_VALUE);
System.out.
In Java, all math is done in the largest data type required to handle all of the current values. So, if you have int * int, it will always do the math as an integer, but int * long is done as a long.
In this case, the 1024*1024*1024*80 is done as an Int, which overflows int.
The "L" of course forces one of the operands to be an Int-64 (long), therefore all the math is done storing the values as a Long, thus no overflow occurs.
The integer literals are int
s. The int
s overflow. Use the L
suffix.
long value = 1024L * 1024L * 1024L * 80L;
If the data came from variables either cast or assign to longs beforehand.
long value = (long)a * (long)b;
long aL = a;
long bL = b;
long value = aL*bL
Strictly speaking you can get away with less suffices, but it's probably better to be clear.
Also not the lowercase l
as a suffix can be confused as a 1
.
I suspect it's because by default java treats literals as integers, not longs. So, without the L on 80 the multiplication overflows.
If I understood it correctly, per your requirement, you wanted to multiply these values 1024 * 1024 * 1024 * 80;
In calculator I see values coming 1024 * 1024 * 1024 * 80=85899345920.
Here you go your java code: These are monetary value calculation in java
import java.math.BigDecimal;
public class Demo {
public static void main(String[] args) {
BigDecimal bd1 = new BigDecimal("1024");
BigDecimal bd2 = new BigDecimal("1024");
BigDecimal bd3 = new BigDecimal("1024");
BigDecimal bd4 = new BigDecimal("80");
BigDecimal bd5 = bd1.multiply(bd2).multiply(bd3).multiply(bd4);
System.out.println(bd5); // output comes: 85899345920
}
}
This code:
long value = 1024 * 1024 * 1024 * 80;
multiplies some integers together, converts it to a long and then assigns the result to a variable. The actual multiplication will be done by javac rather than when it runs.
Since int is 32 bits, the value is wrapped and results in a zero.
As you say, using long values in the right hand side will give a result which only wraps if it exceeds 64 bits.