When to use true and when to use Boolean.TRUE? [duplicate] - java

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 )
) ;

Related

For boolean fields in Java Model class is it better to use Boolean object or primitive boolean field [duplicate]

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

Default Boolean value in Java [duplicate]

This question already has answers here:
Default value of 'boolean' and 'Boolean' in Java
(8 answers)
Closed 8 years ago.
I just want to know if there is a difference in Java between:
private boolean someValue;
private boolean someValue = false;
The second line maybe is just a time wasting?
EDIT (SUMMARY):
From the answers I found that there is almost no difference, but:
"Relying on such default values, however, is generally considered bad programming style."
But there are some strong arguments not to do so - see accepted answer below.
EDIT 2
I found that in some cases boolean value must be initialized, otherwise the code will not compile:
boolean someValue;
if (someValue) { // Error here
// Do something
}
In my NetBeans IDE I got the error - "variable someValue might not have been initialized".
It's getting interesting.. :)
All instance and class variables in Java are initialised with a default value:
For type boolean, the default value is false.
So your two statements are functionally equivalent in a single-threaded application.
Note however that boolean b = false; will lead to two write operations: b will first be assigned its default value false then it will be assigned its initial value (which happens to be false as well). This may have an importance in a multi-threaded context. See this example of how explicitly setting the default value can introduce a data race.
Relying on such default values, however, is generally considered bad programming style.
I would argue the opposite: explicitly setting default values is bad practice:
it introduces unnecessary clutter
it may introduce subtle concurrency issues
If you didn't initialize it, it will be false. So there is no difference between them.
The default value of boolean data type is false so we can say that there is no difference.
There is no difference, from:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable).
If it's an instance variable Boolean it will be null.
If it's declared within a method you will have to initialize it, or there will be a compiler error.

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 ?
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

using Boolean Object

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.

Why would one want to use the public constructors on Boolean and similar immutable classes?

(For the purposes of this question, let us assume that one is intentionally not using auto(un)boxing, either because one is writing pre-Java 1.5 code, or because one feels that autounboxing makes it too easy to create NullPointerExceptions.)
Take Boolean, for example. The documentation for the Boolean(boolean) constructor says:
Note: It is rarely appropriate to use this constructor. Unless a new
instance is required, the static factory valueOf(boolean) is generally
a better choice. It is likely to yield significantly better space and time
performance.
My question is, why would you ever want to get a new instance in the first place? It seems like things would be simpler if constructors like that were private. For example, if they were, you could write this with no danger (even if myBoolean were null):
if (myBoolean == Boolean.TRUE)
It'd be safe because all true Booleans would be references to Boolean.TRUE and all false Booleans would be references to Boolean.FALSE. But because the constructors are public, someone may have used them, which means that you have to write this instead:
if (Boolean.TRUE.equals(myBoolean))
But where it really gets bad is when you want to check two Booleans for equality. Something like this:
if (myBooleanA == myBooleanB)
...becomes this:
if (
myBooleanA == myBooleanB ||
(myBooleanA != null && myBooleanA.equals(myBooleanB))
)
UPDATE: With the release of Java 7, java.util.Objects makes this simpler construct possible:
if (Objects.equals(myBooleanA, myBooleanB))
I can't think of any reason to have separate instances of these objects which is more compelling than not having to do the nonsense above. What say you?
The cached values are never garbage collected, so use the constructors whenever you'd like to use them as soft/weak references, so that it can be garbage collected anyway whenever needed. The same applies on Long#valueOf(), Integer#valueOf() and consorts with values within cacheable ranges.
Doing a reference search in Eclipse learns me that under each java.lang.Thread uses new Boolean() as a soft-reference based cache, it's even explicitly commented (in isCCLOverridden() method):
/*
* Note: only new Boolean instances (i.e., not Boolean.TRUE or
* Boolean.FALSE) must be used as cache values, otherwise cache
* entry will pin associated class.
*/
The constructors are public because of backwards compatibility... .valueOf() only got added in java 1.4...
Also using a Boolean as a tri-state variable in your example (null/TRUE/FALSE) is probably a bad idea -- better to use an enum (UNKNOWN,TRUE,FALSE), or if null is not a valid value, check for it, and manually unbox for testing equality.
These object types were needed because the Collection class only accepted objects, hence you couldn't use the native types.
This introduced the design flaw you are talking about and hence autoboxing was introduced.
EDIT
And the constructors are public because they were always public. Before the world of autoboxing in some very poor code you wanted new Integer(0) != new Integer(0) to be true. It was a flaw more than anything of the original design, however since its a part of the public interface now they don't want to break old code.
I bet they could deprecate it now and most people would be ok with it since autoboxing just works.

Categories