Shorthand operator in JAVA gives two different results
I tried the following code:
class Converter{
public static void main(String args[]) {
byte num = 1;
num = num * 2.5; // line 1
System.out.println("Result is : "+num);
}
}
So the compiler throws an error like:
error: incompatible types: possible lossy conversion from double to the byte at line 1
I later changed line 1 to the shorthand operator = *:
class Converter{
public static void main(String args[]) {
byte num = 1;
num *= 2.5;
System.out.println("Result is : "+num);
}
}
Compiled and executed successfully with output:
Result is:2
May I know that the abbreviation operator cuts work in JAVA. Why is this happening?
source to share
In the JLS documentation of the compound assignment operator, you can see the following example:
For example, the following code is correct:
short x = 3; x += 4.6;
and results in x being 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
It just automatically passes the default result.
PS: In this other answer, I tried to explain the reason why you need to perform an operation like the following: JLS
short x = 3;
x = x + 1; //Won't compile
This is really new, so I'm open to suggestions there.
source to share
As AxelH said, this is a compound binding , but I would like to do this:
A cumulative form assignment expression is
E1 op= E2
equivalent to toE1 = (T) ((E1) op (E2))
, whereT
is the typeE1
, except that itE1
is evaluated only once.
This means that by definition it distinguishes the result. For example:
byte b = 1;
b *= 2.3;
System.out.println(b); // prints 2
From your comment:
May I say that the shorthand operator suppresses the lossy conversion error and just does what it has?
No, you cannot. It does not suppress any errors because there is no error in casting (in this context).
source to share
According to java language specification 15.26.2. Connection assignment operators .
A compound assignment expression of the form E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
And you can see the bytecode of your example after compilation (check instruction 3-10).
3: i2d //convert an int into a double
4: ldc2_w #2 // double 2.5d
7: dmul //multiply two doubles
8: d2i // convert a double to an int
9: i2b //convert an int into a byte
10: istore_1 //store int value into variable 1
source to share