About Question enthuware.ocajp.i.v8.2.1236 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
flex567
Posts: 202
Joined: Mon Apr 02, 2018 8:40 am
Contact:

About Question enthuware.ocajp.i.v8.2.1236 :

Post 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?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v8.2.1236 :

Post by admin »

What error message do you get when you try to compile it?

flex567
Posts: 202
Joined: Mon Apr 02, 2018 8:40 am
Contact:

Re: About Question enthuware.ocajp.i.v8.2.1236 :

Post 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.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v8.2.1236 :

Post by admin »

:thumbup:
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).

flex567
Posts: 202
Joined: Mon Apr 02, 2018 8:40 am
Contact:

Re: About Question enthuware.ocajp.i.v8.2.1236 :

Post 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?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v8.2.1236 :

Post by admin »

Boolean is unboxed into a boolean

Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests