Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 691
Shibang Avatar asked Apr 18 '11 01:04

Shibang


2 Answers

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.

like image 190
MeBigFatGuy Avatar answered Oct 22 '22 08:10

MeBigFatGuy


  1. Sometimes you need to parse string to primitive Boolean.parseBoolean(*String*)
  2. Sometimes you need to parse String to Boolean Boolean.valueOf(*String*)
  3. Sometimes you need not create new object. Better avoid using new
  4. Sometimes you need the Boolean object instead of primitive Boolean.valueOf(*boolean*)

These are not same need.

like image 25
Yeameen Avatar answered Oct 22 '22 08:10

Yeameen