code:
public class Main{
public static void main(String[] a){
long t=24*1000*3600;
System.out.println(t*25);
System.out.println(2
In the first case you are printing a long
but in the second, you are printing it as int
.
And int
has a range from: -2^31 to 2^31 - 1 which is just below what you are calculating (int max: 2147483647 you: 2160000000) so you overflow the int to the negative range.
You can force the second one to use long
as well:
System.out.println(24L*1000*3600*25);
(int)Long.valueOf("2345678901").longValue();
To explain it clearly,
System.out.println(24*1000*3600*25);
In the above statement are actually int
literals. To make treat them as a long
literal you need to suffix those with L
.
System.out.println(24L*1000L*3600L*25L);
Caveat, a small l
will suffice too, but that looks like capital I
or 1
, sometimes. Capital I
doesn't make much sense here, but reading that as 1
can really give hard time. Furthermore, Even sufficing a single value with L
will make the result long
.
You should suffix the numbers with 'l'. Check the snippet below:
public static void main(String[] a){
long t=24*1000*3600;
System.out.println(t*25);
System.out.println(24l*1000l*3600l*25l);
}
If you want to do mathematical operations with large numerical values without over flowing, try the BigDecimal class.
Let's say I want to multiply
200,000,000 * 2,000,000,000,000,000,000L * 20,000,000
int testValue = 200000000;
System.out.println("After Standard Multiplication = " +
testValue *
2000000000000000000L *
20000000);
The value of the operation will be -4176287866323730432, which is incorrect.
By using the BigDecimal class you can eliminate the dropped bits and get the correct result.
int testValue = 200000000;
System.out.println("After BigDecimal Multiplication = " +
decimalValue.multiply(
BigDecimal.valueOf(2000000000000000000L).multiply(
BigDecimal.valueOf(testValue))));
After using the BigDecimal, the multiplication returns the correct result which is
80000000000000000000000000000000000
You reached the max of the int
type which is Integer.MAX_VALUE
or 2^31-1. It wrapped because of this, thus showing you a negative number.
For an instant explanation of this, see this comic: