Java Long will not print correctly

This should be very stupid, but I'm trying to do the following:

long mult = 2147483647 + 2147483647 + 2; System.out.println(mult); // result = 0 

Now my varaible mult will be a ten-digit number, well, in a long range. Therefore, I do not understand why it prints 0 as a result. Can someone explain why?

+4
source share
3 answers

Arithmetic is done using int instead of long , since there are three constant values โ€‹โ€‹of int s. The fact that you are assigning a variable to long does not matter. Try the following:

 long mult = 2147483647L + 2147483647L + 2L; 

You may be able to make only one of the literals a long literal if you are careful, but I personally applied it to everyone, just to make it clear that you want long arithmetic for everything.

+12
source

What about:

 long mult = 2147483647L + 2147483647 + 2; 
+3
source

thats because when you give any number directly, like num1 + num2 , they are taken as integers, and since the value is out of bounds in this case, you will get either 0 or another output depending on the input.

You can easily solve this problem by choosing

 long mult = 2147483647; mult += 2147483647; mult += 2; System.out.println(mult); 
+1
source

Source: https://habr.com/ru/post/1342295/


All Articles