About Question com.enthuware.ets.scjp.v6.1.825 :

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

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.1.825 :

Post by ETS User »

K&B book states that "if you have a mismatch between the type specified in your conversion character and your argument, you will get a runtime exception"

I do not understand

%b implies you are trying to print a value as a boolean. The rule for conversion to a boolean is as follows:If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".

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

Re: About Question com.enthuware.ets.scjp.v6.1.825 :

Post by admin »

The given explanation is correct as per the API JavaDoc at: http://download.oracle.com/javase/6/doc ... tml#syntax

Guest

Re: About Question com.enthuware.ets.scjp.v6.1.825 :

Post by Guest »

ETS User wrote:K&B book states that "if you have a mismatch between the type specified in your conversion character and your argument, you will get a runtime exception"

I do not understand

%b implies you are trying to print a value as a boolean. The rule for conversion to a boolean is as follows:If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".
I remembered the same thing in K&B, but he is right. I just tested it.

%b and %s have some slightly different rules.

I think the others follow what K&B said and I think the K&B example was using one of the ones that would cause an exception, but they made it sound like it applied to all format codes.

piotrkmiotczyk
Posts: 27
Joined: Mon Sep 22, 2014 1:30 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.1.825 :

Post by piotrkmiotczyk »

Any logical reason why the compiler does not see that boolean is not convertible to decimal, when using Format String Syntax?

It does see it in this case:

boolean flag = false;
float f = (float) flag; //obviously does not compile
System.out.print(f);

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

Re: About Question com.enthuware.ets.scjp.v6.1.825 :

Post by admin »

Because the compiler does not know that you are trying to convert a boolean to float.You are basically passing a boolean to a method that accepts a boolean. What that method does at run time to that boolean is not really known to the compiler.


Post Reply

Who is online

Users browsing this forum: No registered users and 7 guests