Thursday, October 31, 2019

java - Incompatible types. Required: short, Found: int





I just can't understand the difference between this:



short d = 0;

//some code
node.accessible = d + 1;



and this



short d = 0
//same code here
node.accessible = d;
node.accessible += 1;




the second thing is working, but the 1st one is't inteliji showes "incompatiable types" error.



p.s. node class:



public class Node {
int n;
short accessible;
Node(int n){
this.n = n;
this.accessible = -1;

}
}

Answer



In the first version :



node.accessible = d + 1;


d + 1 produces a int as summing an int and a short produces an int.
The JLS states indeed that (look at the last case, emphasis is mine) :





5.6.2. Binary Numeric Promotion



When an operator applies binary numeric promotion to a pair of
operands, each of which must denote a value that is convertible to a
numeric type, the following rules apply, in order:




  1. If any operand is of a reference type, it is subjected to unboxing

    conversion (§5.1.8).


  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:




    • If either operand is of type double, the other is converted to double.


    • Otherwise, if either operand is of type float, the other is converted
      to float.


    • Otherwise, if either operand is of type long, the other is converted
      to long.


    • Otherwise, both operands are converted to type int.







But you cannot assign a int to the accessible field that is a short without explicit cast as int has a broader range than short.






While in the second version, a Compound Assignment Operators is used (+=):




node.accessible += 1;


As a consequence, in your case the result of the operation is converted to short : the type of the left-hand variable as the JLS states :




15.26.2. Compound 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 Evaluations only once.




And more specifically in your case :




Otherwise, the result of the binary operation is converted to the type
of the left-hand variable, subjected to value set conversion (§5.1.13)
to the appropriate standard value set (not an extended-exponent value
set), and the result of the conversion is stored into the variable.




No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...