Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference Boolean(boolean), Boolean(String)

 
Thiru Thangavelu
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between Boolean(boolean), Boolean(String) constructors. Where do we use the second one?
Thanks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's important to remember that the boolean literal, true, is very different from the String literal, "true". These two lines of code would use the two constructors, respectively:

I hope that helps,
Corey
 
Thiru Thangavelu
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey, I understand the constructors. But where do we use the second one? We use both true and false for boolean. But why do we need string? A tiny exmaple is appreciated.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any time you have a String that contains a boolean literal, you may want to use this approach. Perhaps you're taking some input from a user and you know that the input will be either "true" or "false". You'll want to turn that input (which is a String) into a boolean, so you'll have to use the String constructor. Here's an example:

Granted, I doubt this would be used vary often. However, if you were to create an expert system, this may be a useful technique. Of course, Java isn't usually the language of choice for such a system, but the example just popped to mind.
I hope that helps,
Corey
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
very nice example
Also, remember that the java.lang.Boolean(String) contructor gives some leeway -- it's case INsensitive.
So Boolean("tRuE") and Boolean("true") both evaluate to Boolean.TRUE
[ June 03, 2002: Message edited by: Jessica Sant ]
 
Thiru Thangavelu
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jessica Sant:
it's case INsensitive.
So Boolean("tRuE") and Boolean("true") both evaluate to Boolean.TRUE

Great point, Jess. I overlooked that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic