0

Multiplication with the maximum value of the Long type in eclipse results in the following result. I wonder what the result means.

    long long1 = 9223372036854775807L;
    long long2 = 9223372036854775807L;
    int n = 5;
    long tmp_long = long1*long2;
    
    System.out.println(long1*n);
    System.out.println(tmp_long);

enter image description here

shindang5
  • 11
  • 2
  • 1
    The result won’t fit in a long and is truncated – Thorbjørn Ravn Andersen Jan 15 '22 at 07:41
  • 1
    Java Language Specification [15.17.1](https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.17.1-200): *"If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. ..."* and [4.2.2](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.2.2-220): *"The integer operators do not indicate overflow or underflow in any way."* – user16320675 Jan 15 '22 at 09:11

2 Answers2

3

The result is too big to fit in a long, and it overflows, that's why you get those results. If you need to work with such big number correctly you should use the BigInteger class.

BigInteger int1 = BigInteger.valueOf(9223372036854775807L);
BigInteger int2 = BigInteger.valueOf(9223372036854775807L);
BigInteger n = BigInteger.valueOf(5);
System.out.println(int1.multiply(n));
System.out.println(int1.multiply(int2));

Or if you want the overflow to throw an error you could use Math.multiplyExact(long, long)

long long1 = 9223372036854775807L;
long long2 = 9223372036854775807L;
int n = 5;
System.out.println(Math.multiplyExact(long1, n));
System.out.println(Math.multiplyExact(long1, long2));
Chaosfire
  • 4,818
  • 4
  • 8
  • 23
0

Java has a BigInteger class to manage such integers.

Nicolas Peron
  • 124
  • 1
  • 8