Why java has a lot of duplicate methods?

Shibang picture Shibang · Apr 18, 2011 · Viewed 8.4k times · Source

I was playing with Java as I am planning to switch from C# to it for cross platform purposes. I have just noticed that it has a lot of methods that just do the same thing. And I just want to know why did they do that ?

An example, the Boolean class has two methods doing the same thing in addition to the constructor which does the same thing too.

Boolean b = new Boolean(true);
Boolean b = new Boolean("true");
Boolean b = Boolean.parseBoolean(true);
Boolean b = Boolean.parseBoolean("true");
Boolean b = Boolean.valueOf(true);
Boolean b = Boolean.valueOf("true");

And I can get the boolean value either by just calling the variable itself (b) or the method b.booleanValue(). Would anyone want to call a method getting the boolean value of a boolean although he can just call the variable itself ?

What is the point ?

Answer

MeBigFatGuy picture MeBigFatGuy · Apr 18, 2011

new Boolean(true) and Boolean.valueOf(true) return Boxed primitives. Real objects that can be used in collections etc. from primitive boolean values.

Boolean.parseBoolean("true") returns the primitive boolean value.

btw,

Boolean b = Boolean.parseBoolean(true);
Boolean b = Boolean.parseBoolean("true");

are really mistakes. you are creating a primitive boolean and then auto boxing to Boolean.

You should use valueOf(true) or valueOf("true") instead.

So the real use of these methods would be

Boolean b = new Boolean(true);   //really this should never be used **
Boolean b = new Boolean("true"); //really this should never be used **
boolean b = Boolean.parseBoolean(true);
boolean b = Boolean.parseBoolean("true");
Boolean b = Boolean.valueOf(true);
Boolean b = Boolean.valueOf("true");

** don't use this as you are just creating objects needlessly. Using valueOf allows for reusing existing Boolean objects. Since Booleans are immutable this is fine.