Home > database >  why java long type calculate different?
why java long type calculate different?

Time:06-23

final long b = 123123;
final long c = 123123*123123*123123;
long d = b*b*b;
System.out.println(c);
System.out.println(d);

output : -162426261 1866455185461867

In the case of the first printout, it seems that overflow occurs because Java treats it as an integer rather than a long one, but why is it not calculated as an integer in the second case? I thought that if I put final in front of long and make it a constant, it would be calculated in compile time, so I thought that the second and first output sentences should have the same result, but I want to know why I was wrong.

CodePudding user response:

Since your value of c won't contain decimal points, it will be treated as an int. To solve this just add "L"(L stands for long)

final long c = 123123L*123123L*123123L;
public class MyClass {
    public static void main(String args[]) {
      final long b = 123123;
      final long c = 123123L*123123L*123123L;
      long d = b*b*b;
      System.out.println(c);
      System.out.println(d);
    }
}

Output

1866455185461867
1866455185461867

CodePudding user response:

Because numeric literals without a decimal point in Java, treated as int, variable c gets an overflown result of int multiplication.

Conversely, variable d is assigned to a result of multiplication that is done on long values (because b is of type long).

Basically you have:

long c = int * int * int;     // multiply `int` numbers and then promote an overflown result into `long`
long d = long * long * long;

I thought that if I put final in front of long and make it a constant, it would be calculated in compile time

Variables b and c are compile-time constants, because they are primitive, marked as final, assigned at the moment of declaration and initialized with constant expressions. All accuracies of these variables in the code would be replaced with their values. But it doesn't change how the value of c is calculated.

Variable d isn't a compile-time constant because it has no final modifier. But this fact also has no effect on the way how its value is calculated.

  • Related