I have an exercise which relates to "instanceof
" and I am not quite sure how to use it. This is what I came up with:
for(int i = 4; i < 6; i++){
int availSupply = part[i].stockLevel+part[i].getAvailForAssembly();
if(availSupply instanceof Integer){
System.out.println("Total number of items that can be supplied for "+ part[i].getID()+"(" + part[i].getName() + ": "+ availSupply);
}
}
The code looks fine to me, however it came up with an error:
Multiple markers at this line
Incompatible conditional operand types int and Integer at: if(availSupply instanceof Integer){
I do not know what I did wrong, it is the only error that showed up.
You can't use instanceof
with an expression of a primitive type, as you're doing here with availSupply
. An int
can't be anything else, after all.
If getAvailForAssembly()
is already declared to return int
, then you don't need your if
statement at all - just unconditionally execute the body. If it returns Integer
, you should probably use:
Integer availSupply = ...;
if (availSupply != null) {
...
}
See more on this question at Stackoverflow