问题
code:
public class Main{
public static void main(String[] a){
long t=24*1000*3600;
System.out.println(t*25);
System.out.println(24*1000*3600*25);
}
}
This prints :
2160000000
-2134967296
Why?
Thanks for all the replies.
Is the only way to use L after the number?
I have tried the (long)24*1000*3600*25
but this is also negative.
回答1:
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
.
回答2:
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:

回答3:
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);
回答4:
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);
}
回答5:
Integral literals are treated as type int
by default. 24*1000*3600*25
is greater than Integer.MAX_VALUE
so overflows and evaluates to -2134967296. You need to explicitly make one of them a long
using the L suffix to get the right result:
System.out.println(24L*1000*3600*25);
回答6:
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
回答7:
(int)Long.valueOf("2345678901").longValue();
来源:https://stackoverflow.com/questions/3957937/parse-long-to-negative-number