A Boolean wrapped with string

What's the best way to convert a Boolean primitive to a string?

November 9, 2001

Q: 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");

A: 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
Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in the bridging of disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Learn more about this topic