Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Really confused by java data type in this specific case [duplicate]

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!

like image 279
tanvir irfan Avatar asked May 11 '16 08:05

tanvir irfan


People also ask

What are the types of data types in Java?

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.

What are the types of variables in Java?

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.

What are the different types of data types in C?

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 ...

What is a long type in Java?

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.


1 Answers

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.

like image 191
zubergu Avatar answered Oct 13 '22 01:10

zubergu