• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String parsing and Boolean Constructor

 
Imtiaz Nizami
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Page 292 of Head First Java discuss static utility methods that are present in Wrapper classes. For example
int x = Integer.parseInt("2");

No problems with this example. It also gives the following example in case of Boolean:
boolean b = new Boolean("true").booleanValue();

Here, book mentions, the Boolean constructor takes and parses the String and primitive variable 'b' gets the primitive value by unwrapping it. I cannot make sense out of this code. To me, the code should be:
boolean b = (new Boolean("true")).booleanValue();

The above two pieces give similar results, but I can understand the second implementation which tells me that we are calling the unwrap method on an object. Whereas the code mentioned in the book makes little sense to me.

Any help will be appreciated. Thanks.
 
Majid Al-Fifi
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and (((new Boolean("true")))).booleanValue(); will also work...

new Boolean("true") returns an object and then you are calling booleanValue() on that object. the two parenthesis are redundant.

you can think of it this way:

you have:

new Boolean("true").booleanValue();

now replace [new Boolean("true")] with b you get b.booleanValue();

now define Boolean b = new Boolean("true");

Regards,
Majid
 
Imtiaz Nizami
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I got your point of new Boolean("true") being a single entity whether within parenthesis or not. I was not sure if the method is being called after the object creation.

Although, I still feel that the other syntax with extra parenthesis is more readable. It might be a preference based on working with C.
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I think that the above code with parentheses is more readable too. In other words "me too".

I disagree with the book using "true" as a String. This doesn't work for languages other than English. Using the string constructor for numbers is OK because they are the same in other languages, but using the String "true" instead of the boolean literal true is bad practice in general.

Kaydell
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic