In fact, in this particular case, the really confusing java data type

public class Test { public static void main(String [] s) { int x = 99999; long y = 99999; long res = x * x; System.out.println("x^2 = " + res); res = y * y; System.out.println("y^2 = " + res); } } Output: x^2 = 1409865409 y^2 = 9999800001 

I'm really confused to see the result from the above code segment. I expected to get the same (correct) answer, but here x ^ 2 is actually not so!

+5
source share
3 answers

99999 * 99999 = 1001010100000010001101011011000001 in binary format (if you count this, you will find that you need 34 bits to represent this number in memory).

int is longer than 32-bit , so two MSBs are cut.

As a result, you will get 01010100000010001101011011000001b = 1409865409 decimal value.

Assigning this value to 64-bit length does not change the result; multiplying two integers gives you an integer.

+8
source

This is because you multiply integers x * x , and the result of this will be integer (temporary variable, we are talking here about the result of the operation x * x , not res = ). Since the result will be larger than Integer.MAX_VALUE , you will get some "weird" number. Then you put this number in a variable of type long .

Here is how you fix this problem:

 long res = 1l * x * x; 

Now it will calculate 1l * x , and since the first number is long , it will calculate it as long , then multiply by x and again, since the first number is long , the result will be long , then this result will be placed in the res variable.

Similarly, you fix the decimal point problem, for example:

 int a = 10; int b = 3; double d = a / b; 

The result for this will be 3.0 . But if you do this:

 double d = (1d *a) / b; d = a / (b * 1d); d = (double) a / d; 

Both will be 3.3333333333333335 (this is 5 , well, this is another problem ...). Also, using casting for double for one of the variables also works (thanks @Aconcagua).

+3
source

Because at first x * x is executed in int space, and only then the result is placed in long . Therefore, although the long variable is large enough to hold the result, before putting the result in long , it is first evaluated as an int product, and the result is truncated because it does not fit in int

+3
source

All Articles