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 ?
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.
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.
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")
What is the point ?
Well, the point is that some of those alternatives are useful, and some are old methods left over from the first version of Java.
(The original version of Java was released in a rush, and there were a few design mistakes / inconsistencies in the APIs. However, the overarching requirement to maintain backwards compatibility meant that it was impossible to correct them. In cases where the mistakes were positively harmful, the relevant methods have been marked as "deprecated" to warn programmers not to use them. In harmless cases like this where methods are simply redundant, things have been left unchanged.)
Note that they are not the same; one of your lines:
Boolean b = Boolean.parseBoolean(true);
would give a syntax error (at least according to the Java 6 api).
Boolean.valueOf(true) and new Boolean(true) are different functions in that new Boolean(true) would create a new object and Boolean.valueOf(true) returns a stored Boolean object.
The signature of Boolean.parseBoolean returns a primitive boolean. Before Java 5 you needed Boolean.valueOf to convert it to an object form. After Java 5 the system will do that automatically, but (a) Java decided it wanted explicit forms of the autoboxing (and thus added Integer.valueOf and such) and (b) methods of Java are never deleted even when they become obsolete. In many cases that is a source of duplication itself (such as when they reorganized collections way back in Java 2 but old collection classes had methods added to match the new system leading to duplication).
Boolean is a type that herits from Object, in opposit to b.booleanValue() it returns a primitive type boolean.
so the difference is that the first is an object and the second is a primitive type.
You listed one that doesn't exist, and you incorrectly specified the return type of parseBoolean. The list is actually:
Boolean b = new Boolean(true);
Boolean b = new Boolean("true");
boolean b = Boolean.parseBoolean("true");
Boolean b = Boolean.valueOf(true);
Boolean b = Boolean.valueOf("true");
(4) is redundant with (1) and (5) is redundant with (2). Except two are constructors and two are methods. I suspect having that functionality from methods rather than from a constructor might be useful to something (factories?).
java.lang.Boolean
Related
This question already has answers here:
What is the difference between Boolean.TRUE and true in Java?
(7 answers)
Closed 9 days ago.
I had written a code of which a rough snippet is as follows:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
My team lead said to always use existing classes and insisted to use Boolean class like below:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> Boolean.TRUE)
.orElse(Boolean.FALSE);
My question is I see Boolean.TRUE will make unnecessary a Boolean type object. When to use true and when to use Boolean.TRUE? Why in first place, Boolean.java class contains a wrapper object for true and false? I mean, they have auto-boxing so they can directly do like Boolean x = true; instead of Boolean x = Boolean.TRUE.
I have read answers on existing questions on SO related to performance but here I am interested in their usage scenarios.
At first something general
The main difference between boolean and Boolean is that a Boolean can be null, while a boolean cannot. So when you have a check if(a) {...}, with a being a Boolean, this might lead to a nullpointer exception. In this case, you would prefer to have if(Boolean.TRUE.equals(a)) {...}, because the equals method of Boolean would return false in case a is null.
Your specific case
What you suggested there is equivalent to
isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION)).isPresent();
Not that isPresent actually returns a boolean and not a Boolean, as do most of the JDK internal methods that I've come across. Apart of that, I would say using true or false vs. Boolean.TRUE or Boolean.FALSE shouldn't make a real difference in most of the cases and might even be considered a matter of taste. In a large project, though, you would want to use one or the other consistently to not end up with a mess.
Constant, just one immutable object
You asked:
My question is I see Boolean.TRUE will make unnecessary a Boolean type object.
No, multiple objects are not created.
As commented by Culloca, Boolean.TRUE is a constant, referring to a singe object instantiated once when the class loads. As an immutable object, there is no need to have more than one.
Let’s look at the implementation found in the open source code at the OpenJDK project.
public static final Boolean FALSE = new Boolean(false);
The static means an instance is created when the class loads. The final means the reference named FALSE will never be re-assigned to another object. So one, and only one, object.
Avoid excessive auto-boxing
You are right to be concerned about unnecessary auto-boxing. Boxing is not magic; it takes CPU cycles to execute.
Going out of your way to use Boolean.FALSE where you know the primitive false is needed is pointless and a bit silly.
Such a practice is often harmless. If the code is infrequently executed, then you’ll see no significant impact on performance. And in some situations I would guess that the compiler might optimize away the boxing, though that is just a guess on my part.
FYI… Work is underway by the Java team to blur the sharp distinction between primitives and objects created by Java’s two parallel type systems. So the nature and impact of boxing may change in future versions of Java.
No need for Optional
Your code is overly elaborate.
You commented:
The type returned by requestParams.get(IS_CALLED_FROM_ACTION) is a string. If it is not null, I want to set isCalledFromAction to true.
Change this:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
… to use Objects.nonNull:
boolean isCalledFromAction =
Objects
.nonNull (
requestParams.get( IS_CALLED_FROM_ACTION )
) ;
There are discussions around Integer vs int in Java. The default value of the former is null while in the latter it's 0. How about Boolean vs boolean?
A variable in my application can have 0/1 values. I would like to use boolean/Boolean and prefer not to use int. Can I use Boolean/boolean instead?
Yes you can use Boolean/boolean instead.
First one is Object and second one is primitive type.
On first one, you will get more methods which will be useful.
Second one is cheap considering memory expense The second will save you a lot more memory, so go for it
Now choose your way.
Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this
boolean result = Boolean.TRUE;
or
Boolean result = true;
Which essentially the compiler does,
Boolean result = Boolean.valueOf(true);
So, for your answer, it's YES.
I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):
int is not boolean
Consider
boolean bar = true;
System.out.printf("Bar is %b\n", bar);
System.out.printf("Bar is %d\n", (bar)?1:0);
int baz = 1;
System.out.printf("Baz is %d\n", baz);
System.out.printf("Baz is %b\n", baz);
with output
Bar is true
Bar is 1
Baz is 1
Baz is true
Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of
if value \in {0,1} then cast to boolean type, otherwise throw an exception.
All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).
Bytes are not types or bits
Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).
By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).
keyword vs. type
Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class)
or in other words
boolean foo = true;
vs.
Boolean foo = true;
The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).
Optimization is achieved due to trivial:
"Less runtime casting operations => more speed."
That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).
So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).
Finally, autoboxing is slower than primitives
Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.
You can use the Boolean constants - Boolean.TRUE and Boolean.FALSE instead of 0 and 1. You can create your variable as of type boolean if primitive is what you are after. This way you won't have to create new Boolean objects.
One observation: (though this can be thought of side effect)
boolean being a primitive can either say yes or no.
Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)
Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.
boolean b1;
Boolean b2;
b1 and b2 are not same.
You can use Boolean / boolean. Simplicity is the way to go.
If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).
With primitives you guarantee that you will not pass null values. You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Use Boolean when you need an object, eg:
Stream of Booleans,
Optional
Collections of Booleans
Boolean is threadsafe, so you can consider this factor as well along with all other listed in answers
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why there is no way to pass by reference in java
Can anybody tell me why exactly Java does not provide C# "out" type feature when dealing with method parameters to pass by reference ?
I mean why would not it allow us to pass primitive data types like boolean for example, pass by reference. I have tried also with wrapper class java.lang.Boolean but still to no avail. It still wont allow me to pass variable by reference.
Is there any specific reason why Java still has not provided us with this even in version 7 ?
Java only has pass by value. This was a decision made when the language was designed.
Why doesn't java support pass by reference like C++
There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
-- James Gosling, et al., The Java Programming Language, 4th Edition
If you want you can put your boolean as a member inside a mutable class (you can't use Boolean because it is immutable), and pass a reference to that class. Apache Commons even has a class called MutableBoolean that you can use.
Only the language design team could tell you why, but I believe the reason for not allowing "out" parameters might be something like: If you want a method that calculates two things, what you really want is either two methods, or one method that returns an object. This supposedly leads to better design and more maintainable code.
Note that you if you really want "out parameters" you can easily use arrays of one element. For example:
void div(int a, int b, int[] q, int[] r) {
if (q != null) q[0] = a/b;
if (r != null) r[0] = a%b;
}
// elsewhere:
int[] quotient = new int[1];
int[] remainder = new int[1];
div(4, 3, quotient, remainder);
This is just my opinion but I feel that the designers of Java believed they could simplify programming by eliminating features rather than making them more intuitive and easier to handle.
Short answer is that it's a design decision and there's nothing you can do with passing by reference that you couldn't do with passing object references by value.
As for your particular problem, there are two solutions:
A mutable wrapper class:
final class BooleanRef {
public boolean value;
}
And use it as:
// Function
void changeTheBoolean( BooleanRef b ){
b.value = true;
}
// Call:
BooleanRef b = new BooleanRef();
changeTheBoolean( b );
OR, (more hackish but more lightweight) wrap in an array:
// Function
void changeTheBoolean( boolean[] b ){
b[0] = true;
}
// Call:
boolean[] b = new boolean[1];
changeTheBoolean( b );
i'm having issues trying to get the result I wish. Basically what I want to do is have a Boolean object which will allow me to have 3 choices, if a mailer is old i want it to be set to false (meaning does not contain "mapQ.cmd" and "add-coid.cmd" file)
if a mailer is new I want it to set to true (if it is new it will contain "mapQ.cmd" and "add-coid.cmd" file in the directory), and if it is neither an old or new mailer (meaning not a mailer) then I wish for it to be null.
This is what I have, I want to place an elseif instead of the else, and do an else inside that to set the null value, meaning non of the above, then i wish to return the boolean.
local-build-deploy.cmd is used in the example but i wish to use the above file names
private boolean isOldMailer(File mailerFolder) {
File localBuildAndDeploy = new File(mailerFolder,"test/local-build-deploy.cmd");
if (localBuildAndDeploy.exists()) {
return true;
} else {
return false;
}
}
There are 2 ways that you can do this.
If you insist on using Boolean, use the capital B version instead of lower case b. Capital B Boolean is an object and can be set to null and do what you describe. Lower case b boolean is a primitive and can not be set to null.
However, there is a better way that does not rely on using a boolean for 3 values when it is designed for 2.
Using an enum, you can define your types just how you want them and have exactly as many as you need. Here is an example and how you would use it.
public enum Status { NEW, OLD, NEITHER }
private Status isOldMailer(File mailerFolder) {
File localBuildAndDeploy = new File(mailerFolder,"test/local-build-deploy.cmd");
if (localBuildAndDeploy.exists())
return Status.NEW;
else if (/*Something else*/)
return Status.OLD
else
return Status.NEITHER;
}
This is ternary logic, not binary logic. It's typically used in relational databases.
Boolean is binary, of course - just true or false.
If you want ternary logic, wrap it in your own type.
(I'll go over three common options and then suggest the third).
The first option is to use a Boolean and set it to true, false or null. This has a few benefits:
Assuming you first check to ensure the value is not null, you can use it directly in boolean expressions.
It's a somewhat controversial point, but null really isn't too far off from "none of the possible values" (i.e. neither true nor false), so it's a reasonable model. Many disagree.
Concise.
However, some people, reasonably or not, expect a Boolean to be either true or false, and do not consider the null possibility, which can easily lead to bugs.
The second option is to use an enum:
No real risk of misuse, since null is not an option, but...
You lose the boolean semantics.
Depending on what you're modelling, it may or may not be aesthetic to introduce a custom enum.
The third--and recommended--option is to use an Optional< Boolean > from Google's excellent Guava library:
It's a very common library.
It's self-documenting.
It has well-defined semantics.
Null is not an issue.
Boolean semantics are just a get away.
Converting to/from the null-based model in the first option, above, is very concise and easy-to-read.
Use Boolean - the wrapper object on primitive boolean. In that way, you can set the reference to null or true or false.
This question already has answers here:
Boolean vs boolean in Java
(8 answers)
Closed 4 years ago.
I would like to understand the difference between the Boolean and boolean types in Java, specifically as they relate to GWT.
I know that methods are not supported but I want more info if it is available.
It's fairly Simple and the same for GWT and Java:
boolean can be yes or no
Boolean can be yes, no or NULL.
So unless you need the NULL (like for example your loading the field from the database, and you want NULL to be different to false) then stick to boolean.
I'm not sure if the GWT factor makes a difference but in general:
boolean is a java primitive type whereas Boolean is an object/reference type that wraps a boolean
Converting between primitives and objects like this is known as boxing/unboxing.
Here is more info:
http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/
Why box you ask?
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
http://www.javapractices.com/topic/TopicAction.do?Id=197
In Java, a boolean is a literal true or false, while Boolean is an object wrapper for a boolean.
There is seldom a reason to use a Boolean over a boolean except in cases when an object reference is required, such as in a List.
Boolean also contains the static method parseBoolean(String s), which you may be aware of already.
Because Boolean can be null, it can be used for lazy loading.
if(hasRoots == null){
calculateRoots();
}
Java has primitive types (int, boolean, float, etc) and anytime you wish to use them as an instance of an object they are wrapped in an associated Class type. For example, booleans get wrapped by Booleans, int as Integer etc.
It has its benefits too. boolean has no helper methods (since it's not a class), but Boolean does. So, if you wanted to convert a string to a boolean you could try Boolean.valueOf("true").
Hope that helps.
As far as GWT, they are the same in GWT as there are in java.
boolean is a primative and Boolean in an object wrapper.
According to the GWT JRE emulation docs (http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html) these methods are supported on the Boolean type:
Boolean(boolean), Boolean(String), parseBoolean(String), toString(boolean), valueOf(boolean), valueOf(String), booleanValue(), compareTo(Boolean), equals(Object), hashCode(), toString()
as to the difference between boolean and Boolean object types. Boolean objects can be in 3 states, so it is not exactly the same. But if that makes a difference in GWT (performance wise) I don't have a clue, my guess is that it does not matter much since the GWT compiler will optimize the code and most operations could simply map to native javascript boolean operations.
But as usual: to be certain you must measure (and take into account that this might differ based on what browser/version you are measuring).
The Boolean object type is normally not used very often since the boolean native type is more natural (you don't need to check for null all the time).
boolean is a primitive type whereas Boolean is wrapper class.Same applies for (int,Integer),(long,Long) etc.
Wrapper classes "wrap" the respective primitive data type into an object of that class.
They are used with collections, as primitive types are not allowed with collections.Also using wrapper classes give you access to many methods that you can call on that object.For eg. Character wrapper class have methods like:
isDigit() – to determine whether the character is digit.
isLower() – to determine whether the character is lower case alphabet.
is Letter() – to determine whether the character is an alphabet.
we cannot use the above methods if we use a primitive type as compared to a wrapper class.