Which statement (true or Boolean.TRUE) will be more efficient - java

My bean is as below
private boolean myBoolean;
public boolean isMyBoolean() {
return myBoolean;
}
public void setMyBoolean(
boolean myBoolean) {
this.myBoolean = myBoolean;
}
Now when I use setter for the above Boolean field then what should be the efficient way to do it
setMyBoolean(true);
or
setMyBoolean(Boolean.TRUE);
I know that autoboxing will take care and both will work But I don't know what is the efficient way in this example. So my question is which of both should I use to write an efficient code OR both are equally good
TIA

Use the first one. More readable. You don't need to concern about the performance issue here, although the second one will involve auto-boxing and comparatively slower (again, you don't need to think about it).
Only consider code readability in this type of cases, and remember that primitives will always be faster than objects.

imho
setMyBoolean(true);
Primitives always do favor than Wrappers.Where ever I am able to use primitives,I go for them
Because while run time, If we use Wrappers Boxing conversions and Unboxing Conversions happens at Runtime,Obviously that takes more time.
In your case
At run time, boxing conversion proceeds as follows:
If p is a value of type boolean, then boxing conversion converts p into a reference r of class and type Boolean, such that r.booleanValue() == p
If you use primitive there,Obviously you save that time.

The reason
boolean boolVar = Boolean.TRUE;
works is because of autounboxing, a Java 5 feature that allows a wrapper object to be converted to its primitive equivalent automatically when needed
as you can understand, setting is faster then autounboxing and then setting...

It does not matter. At the very end when your code is compiled the bytecode generated will end up using the boolean data type on the JVM.
What I am trying to say is, on compile time, such a simple code like this will be optimized automatically for the JVM. It does not matter which way you use, remember that the compiler will end up translating this into bytecode and JVMs nowadays do this kind of optimizations all the time.
If you are skeptical on this, you can try both ways and use a profiler on your code. You will be amazed.

Boolean.TRUE is a wrapper object for boolean.
Boolean class implementation from Sun SDK:
public final class Boolean ...
{
private final boolean value;
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
...
}
when you use setMyBoolean(Boolean.TRUE);:
VM creates Boolean object (in heap) and the saves the value to true.
Unboxes the created object and finally assigns primitive true to myboolean.
when you use setMyBoolean(true);: only step 2 will be performed from above. Thus faster!

Related

Object-Equals to force same type at runtime

I am wondering whether it is possible to add something like Objects.equals() that allows runtime checking of types.
Note: I know, that is not what you always want to do, but I think it has its use cases. At least for me.
Example problem: I have some class, let's say, an id of type Integer. And I have an entity Foo with foo.getId() returns a type Integer. For some reasons I check for equality with Objects.equals(someId, foo.getId()).
Now I refactor my entity, foo.getId() will no longer return an Integer but will return Long. Unfortunatelly, there will be no compile time hint at all that Objects.equals(someId, foo.getId()) will never return true. (Yes, stuff like sonarqube helps you a bit).
To solve that, I thought I write something like
private static <T> boolean equals(T object1, T object2) {
return Objects.equals(object1, object2);
}
which.....just does not work. It still accepts any arbitrary Object. Is there any possible solution in Java for this?
Edit: Please note, this question has nothing to do with equals and hashCode of an object or overriding equals of an object in general, I am looking for a compile-time solution.
I think there is no fast solution short of writing a bunch of equals() methods. This might be feasible if you have only a limited set of types that you want to use:
public class Equals {
public static boolean equals(Integer a, Integer b) {
return Objects.equals(a, b);
}
public static boolean equals(Long a, Long b) {
return Objects.equals(a, b);
}
public static void main(String[] args) {
// System.out.println(equals(1, 1L)); doesn't compile
System.out.println(equals(1, 1));
System.out.println(equals(1L, 1L));
}
}
Just as Thomas already mentioned, I cannot think of a fast solution either.
You have several options, some of which you may have already tried:
You may use your own equals methods, forcing you to pass two arguments of the same type (either both Integer or both Long). This is the solution Thomas proposed.
You may force a certain type by typecasts:
Objects.equals((Integer) someId, (Integer) foo.getId())
The compiler starts whining if you change the type of either of the arguments.
Apply encapsulation. Create a class Id, in which you store the actual value, either as a Long or as an Integer. Then if you return an id anywhere, use the Id class for it. The problem with directly using a Long or Integer is that you expose the internal implementation. And when you change the implementation, you change the interface.
Whether this option is feasible, depends on your use case.
If you don't want to use a class Id, then I suggest you switch to Long, and hope you don't ever need an id greater than 9,223,372,036,854,775,807.

Java boolean primitive

Can I do this in java?
private static boolean isRight(){
return new Random.nextBolean();
}
boolean test = true;
test = test && isRight()
My question is can I use a boolean to update the same boolean like I would if it were an int or double? Is this a good programming practice or there's a better way
Yes of course you can. boolean works in the same way as any other primitive type in Java.
Note however that this is an abuse of Random: you should not reinitialise the generator every time you want to draw from it. You could keep it as a static field in the class, taking care to synchronize on its monitor to help achieve thread safety.
Note also that test will remain false once it evaluates to false.

What is the difference between false and Boolean.FALSE?

In C++ windows.h FALSE is defined as integer which makes sense for some special logic cases, but in Java java.lang.Boolean.FALSE is defined as boolean and assigned to false
public static final Boolean FALSE and I've seen some people use it.
My question: is there a performance difference between false and Boolean.FALSE? in general why do people go and Boolean.FALSE?
See http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html.
Boolean.TRUE and Boolean.FALSE are not boolean, they are Boolean. They are static instances of the two Boolean wrapper objects that correspond to the boolean values true and false.
Boolean is similar to an enum. The TRUE and FALSE instances are the instances returned by Boolean.valueOf().
As for performance of primitive vs. wrapper; there is no difference that you would ever need to be concerned about. The TRUE and FALSE static instances help performance a bit, and the javadocs recommend using Boolean.valueOf() as opposed to new Boolean(...) for that reason. The true and false boolean values are a little "lower level", but if you are storing them in a Boolean (as opposed to boolean) anyways it's irrelevant.
You should use whichever makes the most sense for your code and leads to the best readability (and definitely don't start going down the path of thinking of microoptimizations like primitive vs. wrapper types). If you are using a Boolean, use the object values. If you are using a boolean, use the primitive values. If you are deciding between Boolean vs boolean, use whatever is more appropriate (e.g. a Boolean can be null, which may be useful, and also you can't use primitive types for generic type parameters; on the other hand, a boolean can never be null which could be equally useful).
Also note that auto boxing converts the primitive types to one of those two static Boolean instances, e.g.:
Boolean a = true;
assert(a == Boolean.TRUE);
As an aside, since you mentioned it: FALSE is defined in windows.h for two reasons: 1) Because windows.h has been in use since C-only days, and C does not have a native bool type, and 2) it is traditional Microsoft practice to define data types and values with known, explicit sizes and values, esp. for passing data to Windows API functions across DLL boundaries (beyond the scope of this question) and for integrating with other languages that have different representations of "true" and "false". It is entirely unrelated to the reasons for Boolean.FALSE in Java.
false is a primitive and Boolean.FALSE is an object, so they're not really comparable.
If you assign false to a Boolean variable, like this:
Boolean b = false;
Java's auto boxing occurs to convert the primitive into an object, so the false value is lost and you end up with Boolean.FALSE anyway.
In terms of performance, using a primitive variable would slightly out-perform using a wrapper Boolean object, but your choice should be based on readability and basic design decisions rather than on "performance".
Boolean comes in handy when you need a tri-state variable.
Also, you might want to check out this autoboxing and unboxing tutorial, as well as the rules for how it works.
It is a very strange question, because false is the value of primitive type boolean, while Boolean.FALSE is a variable of reference type Boolean. Its value is reference to the object of type Boolean which internal boolean state is false.
In regards to performance, Boolean.FALSE will return a Boolean object, which might give you more flexibility to work with.
The primitive alternative takes up less memory
First of all, if you are unclear with this, you need to know that in Java numericals cannot be implicitly cast to booleans, e.g. you cannot compile something like:
int a = 1;
if(a){
//something, something
}
Second, some considerations about performance.
There's always a tradeoff.
When using primitive type boolean, performance should be better because you're using a value directly, which is either true or false (obviously, byte-encoded).
When using object type Boolean, a variable/field will hold a value, but that value cannot be immediately used, as that value is in fact the reference to an object, so you might have a performance penalty. Of course, this penalty is not significant in most cases. And, if you develop a time-critical application, most likely you are not using Java :). Nevertheless, using object types might bring some benefits in development process and safety in use cases implementation (e.g. it allows nulls, which is critical when you map JPA entities to relational tables and there are bit-typed columns that allow nulls; and this is only one scenario where object type is better).
In the end, be aware of boxing/un-boxing, which allows developers to use boolean-typed variables almost everywhere a Boolean-typed variable is expected (and the other way around).
Boolean is wrapper class for boolean primitive type, same as we have Integer for int.
Boolean has many methods to play around primitive type boolean
http://docs.oracle.com/javase/6/docs/api/java/lang/Boolean.html
Boolean a = null;
if (a) {
// NullPointerException
}
if (a != false) {
// NullPointerException
}
// Caution, comparing by reference, meaning 2 Booleans with same value could be different
if (a != Boolean.FALSE) {
System.out.println("But this one works");
}

Why change boolean primitive value into a boolean object reference?

I am reading Effective Java and in the first chapter the first example changes a boolean primitive value into a boolean object reference:
public static Boolean valueOf(boolean b)
{
return b ? Boolean.TRUE : Boolean.FALSE;
}
My questions are:
What is the different between boolean primitive value and boolean object reference?
What is the reason to do this?
You cannot use primitives in generics. You cannot do this:
List<boolean> x;
but you can do this:
List<Boolean> x;
Remember that the primitive boolean has two possible values: true or false. The object Boolean has three: true, false, and null. That is sometimes very useful.
A primitive cannot be used in all contexts. For instance, when used in any of the collection classes, an object type is required. This is mostly done for you, anyway, by auto-boxing. But you should still know about it, or you will get bitten at one point.
Another thing is that an object type can contain null. In cases where you need to differentiate between true, false and unknown, using Boolean can be an easy solution.
1> Boolean is wrapper class for boolean
Wrapper classes are used to represent primitive values when an Object
is required. Wikipedia
wrapper class is used to apply some methods and calculation, which is not possible using primitive data types.
2> it depends upon situations.
I believe the most common uses for Boolean are for use in generic function object and, unfortunately, reflection.
For instance:
boolean exists = java.security.AccessController.doPrivileged(
new PrivilegedAction<>() {
public Boolean run() {
return file.exists();
}
}
);
(Probably less boilerplate in Java SE 8.)

How do I pass a primitive data type by reference?

How can I pass a primitive type by reference in java? For instance, how do I make an int passed to a method modifiable?
There isn't a way to pass a primitive directly by reference in Java.
A workaround is to instead pass a reference to an instance of a wrapper class, which then contains the primitive as a member field. Such a wrapper class could be extremely simple to write for yourself:
public class IntRef { public int value; }
But how about some pre-built wrapper classes, so we don't have to write our own? OK:
The Apache commons-lang Mutable* classes:
Advantages: Good performance for single threaded use. Completeness.
Disadvantages: Introduces a third-party library dependency. No built-in concurrency controls.
Representative classes: MutableBoolean, MutableByte, MutableDouble, MutableFloat, MutableInt, MutableLong, MutableObject, MutableShort.
The java.util.concurrent.atomic Atomic* classes:
Advantages: Part of the standard Java (1.5+) API. Built-in concurrency controls.
Disadvantages: Small performance hit when used in a single-threaded setting. Missing direct support for some datatypes, e.g. there is no AtomicShort.
Representative classes: AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference.
Note: As user ColinD shows in his answer, AtomicReference can be used to approximate some of the missing classes, e.g. AtomicShort.
Length 1 primitive array
OscarRyz's answer demonstrates using a length 1 array to "wrap" a primitive value.
Advantages: Quick to write. Performant. No 3rd party library necessary.
Disadvantages: A little dirty. No built-in concurrency controls. Results in code that does not (clearly) self-document: is the array in the method signature there so I can pass multiple values? Or is it here as scaffolding for pass-by-reference emulation?
Also see
The answers to StackOverflow question "Mutable boolean field in Java".
My Opinion
In Java, you should strive to use the above approaches sparingly or not at all. In C it is common to use a function's return value to relay a status code (SUCCESS/FAILURE), while a function's actual output is relayed via one or more out-parameters. In Java, it is best to use Exceptions instead of return codes. This frees up method return values to be used for carrying the actual method output -- a design pattern which most Java programmers find to be more natural than out-parameters.
Nothing in java is passed by reference. It's all passed by value.
Edit: Both primitives and object types are passed by value. You can never alter the passed value/reference and expect the originating value/reference to change. Example:
String a;
int b;
doSomething(a, b);
...
public void doSomething(String myA, int myB) {
// whatever I do to "myA" and "myB" here will never ever ever change
// the "a" and "b"
}
The only way to get around this hurdle, regardless of it being a primitive or reference, is to pass a container object, or use the return value.
With a holder:
private class MyStringHolder {
String a;
MyStringHolder(String a) {
this.a = a;
}
}
MyStringHolder holdA = new MyStringHolder("something");
public void doSomething(MyStringHolder holder) {
// alter holder.a here and it changes.
}
With return value
int b = 42;
b = doSomething(b);
public int doSomething(int b) {
return b + 1;
}
Pass an AtomicInteger, AtomicBoolean, etc. instead. There isn't one for every primitive type, but you can use, say, an AtomicReference<Short> if necessary too.
Do note: there should very rarely be a need to do something like this in Java. When you want to do it, I'd recommend rethinking what you're trying to do and seeing if you can't do it some other way (using a method that returns an int, say... what exactly the best thing to do is will vary from situation to situation).
That's not possible in Java, as an alternative you can wrap it in a single element array.
void demo() {
int [] a = { 0 };
increment ( a )
}
void increment( int [] v ) {
v[0]++;
}
But there are always better options.
You can't. But you can return an integer which is a modified value
int i = 0;
i = doSomething(i);
If you are passing in more than one you may wish to create a Data Transfer Object (a class specifically to contain a set of variables which can be passed to classes).
Pass an object that has that value as a field.
That's not possible in Java
One option is to use classes like java.lang.Integer, then you're not passing a primitive at all.
On the other hand, you can just use code like:
int a = 5;
a = func(a);
and have func return the modified value.

Categories

Resources