Mahesh Nadar
Mahesh Nadar

Reputation: 487

unexpected behavior in types

I have just created a simple java program by using datatype short.
The program looks like this:

class test
{
    public static void main(String arg[])
    {
        short x=1;
        short x_square=x*x;
    }
}

This program throws an error:

java:6: possible loss of precision
found   : int
required: short

How compiler founds int? There is no int variable in this program all variable are declared as short.

Upvotes: 5

Views: 158

Answers (4)

AllTooSir
AllTooSir

Reputation: 49432

During arithmetic operation the integer types are always treated as int primitive in Java if none of them is of type long. Small integer types are promoted to int and the result of the operation is int. Hence x*x is type casted as int and you are trying to assign it to short. You need an explicit cast to short for this narrowing conversion .

short x_square=(short)(x*x);

Follow the JLS 4.2.2

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

Upvotes: 11

Vishal K
Vishal K

Reputation: 13066

Because the multiplication of two shorts returns an int in java. To get rid of this error you need to have explicit type casting :

short x_square=(short)x*x;

Or, You can also do the following:

short x_square = x; 
x_square *= x_square;

Upvotes: 4

Try casting it: short x_square=(short)(x*x)

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382464

From the specification :

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

Adding a short and a short makes an int. If you want to store the result in a variable of type int, you must cast it.

Upvotes: 4

Related Questions