Shibang Shibang - 8 days ago 7
Java Question

Why java has a lot of duplicate methods?

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

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.