Page 1 of 1
About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Sat Feb 16, 2019 4:23 am
by flex567
Code: Select all
public class Test {
public static void main(String[] args){ //for argument '0'
Object o;
Boolean b = true;
o = b;
if(o); // wont compile
if((Boolean)o);
if(b);
}
}
I just wonder why this wont completely compile?
Re: About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Sat Feb 16, 2019 4:24 am
by admin
What error message do you get when you try to compile it?
Re: About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Sat Feb 16, 2019 6:51 am
by flex567
Code: Select all
Test.java:10: error: incompatible types: Object cannot be converted to boolean
That means that Java designers decided that only Boolean reference can go inside if.
Re: About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Sat Feb 16, 2019 6:56 am
by admin
Remember that compiler cannot run the code. It cannot know what o will point to at run time. It only has the type declaration of o to go by and since the declared type of o is Object, o can point to any object (not just Boolean) at run time (every object is an Object) and so, the compiler cannot compile if(o).
Re: About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Fri Feb 22, 2019 5:49 pm
by flex567
It is a bit strange to me that you can just past a reference variable into IF. I would thought that only boolean primitives can be passed in or expressions that evaluate to boolean?
Re: About Question enthuware.ocajp.i.v8.2.1236 :
Posted: Fri Feb 22, 2019 8:06 pm
by admin
Boolean is unboxed into a boolean