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.
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
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
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.
(I thought I once read something about this in a book, but now I'm not sure where to find it. If this question reminds you of some material that you've read, please post a reference!)
What are the pros and the cons of primitives in interfaces?
In other words, is one of these preferable to the other and why? Perhaps one is preferable to the other in certain contexts?
public interface Foo {
int getBar();
}
or
public interface Foo {
Integer getBar();
}
Similarly:
public interface Boz {
void someOperation(int parameter);
}
or
public interface Boz {
void someOperation(Integer parameter);
}
Obviously there's the issue of having to deal with nulls in the non-primitive case, but are there deeper concerns?
Primitive types should be used for efficiency and simplicity unless there is a specific reason to use the object type (e.g., you need null). Using object types can lead to various subtle errors, such as mistakenly comparing if two references are to the same object, instead of having the same value. Observe how Java's own libraries use the primitive types except for containers, which take Objects.
I would say that for the primitives, there is usually little reason to use the primitive wrapper as a return type. One argument is simply the memory requirements. With a primitive return value you only need the X bytes for the return value vs the wrapper where you have the object overhead. The only place where you might save is the cached value for things such as Integer.valueOf(1), but for example with integer this only works for values -128 -> 127.
While lexicore does make a valid point with using null as a special case return value, there are many times where you can do the same with the primitve value (such as something in the API that says "Integer.MIN_VALUE is returned when the result can not be caluclated". Which is viable in many cases for all of the primitives except boolean.
There is also always the option of exceptions as one could argue that an interface should always be well defined for all possible inputs and that an input that would cause a return value to be undetermined is the definition of an exceptional case (and as such perhaps a good case for an IllegalArgumentException).
A final (adimittedly much less elegeant) solution is to add some sort of state checking method to the interface that can be tested after a call to the method that may not execute as desired:
boolean b = (interface).doFoo();
if((interface).wasError()){
//doFoo did not complete normally
}else{
//do something fooish
}
where wasError can clear itself automatically in the style of Thread's interrupt flag (note that this approach will be error prone in multi threaded code).
Except for the rare cases where primitives are troublesome (I've had some "nice" experience with CORBA), I'd suggest using primitives.
I'm thinking of stuff like this too:
Suppose that we have this type:
public interface Foo {
int getID();
}
Then, for whatever reason, an ID type is introduced:
public interface Foo {
FooID getID();
}
Now, suppose that some client was written before the change, and the client contains code like this:
if (A.getID() == B.getID()) {
someBehavior();
}
Where A and B are Foos.
This code would be broken after the change because the primitive equality comparison (==) between the ints, which was ok before the change, is now incorrectly comparing reference values rather than invoking equals(Object) on the identifiers.
Had getID() produced an Integer from the start, the correct client code would have been (ok, the correct client code might have been this. Boxing conversions would have been applied with == so that would have worked too):
if (A.getID().equals(B.getID())) {
someBehavior();
}
Which is still correct after the software evolved.
Had the change been "the reverse," in other words, had getID() originally produced some FooID type, then had it been changed to produce int, the compiler would have complained about calling equals(Object) on a primitive and the client code would have been corrected.
There seems to be some feeling of "future proofing" with the non-primitive type. Agree? Disagree?
Use primitives. Auto-boxing/-unboxing will cast your ints to Integers and so on. Primitives are also allocated on the stack, not the heap. By using wrapper classes you are using more memory and incurring more overhead; why would you want to do that?
Yes , The major use you can see is , when you transfer the object over network.
** The use of serialization. **