Helllo,I am trying for scjp6.
In this example,
String b="fAlSe"; String s1=null,s2=null; s1=new Formatter().format("%b",b).toString(); s2=new Formatter().format("%b",new Boolean(b)).toString(); System.out.println(s1+" "+s2);
in b is false value,but when format It print true and in s2 why it is false?
Here b is NOT a false value. It is a String value.
As I explained in my answer to your other question, the formatter (either by using the Formatter class or printf) has a contract that when you use %b, it expects the object to be either a "boolean" primitive, or Boolean wrapper. When such a primitive or wrapper is given, it will print the boolean value it contains. If the object was any other type, it will print "true". Additionally, if the object was null, it then prints "false".
This goes finely with this line:
s1=new Formatter().format("%b",b).toString();
Here, since 'b' is a String value ("fAlSe"), it gives "true" based on the above description.
The trickiest part is the other line:
s2=new Formatter().format("%b",new Boolean(b)).toString();
Here, the argument the formatter process is new Boolean(b). So basically, we first pass the string variable 'b' to the constructor of java.lang.Boolean. The object it creates then get passed to the printf method.
So let's take a look at the documentation of the Boolean(String) constructor. It says:
"Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false."
Now, what this means is, if the passed String value is "true" (case insensitive), it will be treated as true. In ALL OTHER cases, it will be treated as "false". I know, this is the opposite to how Formatter works.
So, as we pass the String value "fAlSe", the Boolean constructor makes a false type Boolean object, which we then pass to the formatter. The formatter takes this wrapper object and treats is as a "false" value.
This is why it first prints true and then prints false!