Best of 2008: A developer's list

JW blogger Dustin Marx names his top 10 technology events of 2008. Highlights include updates to Java SE 6, runtime support in OpenLaszlo 4.2, and the clash of the titans that occurred early in the year, when Sun acquired MySQL on the same day that Oracle announced its acquisition of BEA. No two lists are alike and it's not too late: What were your top 10 for 2008?

Also see:

Featured Whitepapers
Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

A Boolean wrapped with string

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

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

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

About the author

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).
Boolean.FALSE


  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources