Why java has a lot of duplicate methods?
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 Boolean
s are immutable this is fine.
They are not really duplicate methods/constructors, if you notice difference between true
and "true"
. true
means primitive type boolean
in Java but "true" means a java.lang.String
object that has a value "true".
you missed the funniest one
Boolean.getBoolean("true")
- Sometimes you need to parse string to primitive
Boolean.parseBoolean(*String*)
- Sometimes you need to parse String to Boolean
Boolean.valueOf(*String*)
- Sometimes you need not create new object. Better avoid using
new
- Sometimes you need the Boolean object instead of primitive
Boolean.valueOf(*boolean*)
These are not same need.