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
.
An unexpected behavior is a behavior that other people might find stressful or could make someone feel uncomfortable in the situation. Unexpected behaviors could be a child talking loudly during circle time, running around during snack, or having a tantrum in line with the class.
Expected behavior is simply behavior that is normal, reasonable and anticipated. Unexpected behavior is behavior that is out of the norm, and is unusual.
Emergence is defined as an unexpected behavior or outcome due to interacting parts and elements of a systems.
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.
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.
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