You got negative value because you exceeded the maximum value a long
can hold. When you exceed the maximum value, it starts again from its minimum value up to the number exceeding the maximum value. The same is also true when you try to assign a number smaller than the minimum value to a long
variable. To understand this, you can look at the output of the following program:
public class Main {
public static void main(String[] args) {
System.out.println("Long.MAX_VALUE: "+Long.MAX_VALUE);
System.out.println("Long.MIN_VALUE: "+Long.MIN_VALUE);
long x = Long.MAX_VALUE + 1;
long y = Long.MIN_VALUE - 1;
System.out.println("Long.MAX_VALUE + 1: "+x);//will be assigned the value of Long.MIN_VALUE
System.out.println("Long.MIN_VALUE - 1: "+y);//will be assigned the value of Long.MAX_VALUE
x = Long.MAX_VALUE + 2;
y = Long.MIN_VALUE - 2;
System.out.println("Long.MAX_VALUE + 2: "+x);//will be assigned the value of Long.MIN_VALUE + 1
System.out.println("Long.MIN_VALUE - 2: "+y);//will be assigned the value of Long.MAX_VALUE - 1
}
}
Output:
Long.MAX_VALUE: 9223372036854775807
Long.MIN_VALUE: -9223372036854775808
Long.MAX_VALUE + 1: -9223372036854775808
Long.MIN_VALUE - 1: 9223372036854775807
Long.MAX_VALUE + 2: -9223372036854775807
Long.MIN_VALUE - 2: 9223372036854775806
For your requirement, you need BigInteger
e.g.
BigInteger bi = new BigInteger("18000000000000000000");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…