November 9, 2001
What's the best way to convert a Boolean primitive to a string? Would the following work?
boolean bool = true;
String s = new Boolean(bool).toString();
s.equals("true");
Yes, your proposed code will work. However, I'm not sure I would characterize it as "the best way to convert a Boolean into
a string" as your solution creates an unnecessary extra object. You should avoid extraneous object creation because it can
slow your program down and waste memory.
Instead, take a look at the String class. In particular, consider valueOf(boolean b) -- a static method that takes a Boolean as argument and returns a string representation. So, to convert your bool variable, you can simply do the following:
String s = String.valueOf( bool );
If you're new to Java (or whenever there is a new release), take a careful look at the JDK -- you'll find it offers many hidden treasures.
For example, you will rarely need to actually instantiate Booleans yourself since the Boolean class declares two static Boolean constants: TRUE and FALSE. So whenever you need a Boolean instance, you can just do the following:
Boolean.TRUE
or
Boolean.FALSE
String class JavadocBoolean