File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String parsing and Boolean Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String parsing and Boolean Constructor" Watch "String parsing and Boolean Constructor" New topic

String parsing and Boolean Constructor

Imtiaz Nizami

Joined: May 19, 2007
Posts: 12
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

Joined: Aug 22, 2006
Posts: 45
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");


Imtiaz Nizami

Joined: May 19, 2007
Posts: 12
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

Joined: Nov 18, 2006
Posts: 689

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.

I agree. Here's the link:
subject: String parsing and Boolean Constructor
It's not a secret anymore!