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 am really confused to see the output from the above code segment. I expected to get the same (correct) answer but here x^2 is actually wrong!
Data Types in Java. Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
As explained in the previous chapter, a variable in Java must be a specified data type: Primitive data types - includes byte, short, int, long, float, double, boolean and char A primitive data type specifies the size and type of variable values, and it has no additional methods. Stores fractional numbers.
Data types are divided into two groups: 1 Primitive data types - includes byte, short, int, long, float, double, boolean and char 2 Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter) More ...
5. long: The long data type is a 64-bit two’s complement integer. Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64 -1.
99999 * 99999
= 1001010100000010001101011011000001
in binary (if you count these you will find out that you need 34 bits to represent this number in memory).
int is 32-bit long so two MSBs are cut out.
That gives you 01010100000010001101011011000001b
= 1409865409
decimal as a result.
Assigning this value to 64-bit long doesn't change the result, multiplication of two integers gives you integer as a result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With