Declaring boolean variable - java

I just saw a code from another developer.
private static boolean _menuNeedsUpdate = false;
private static Boolean _userIsLoggingIn = Boolean.valueOf(false);
I want to know the differences between these two declarations. Can any one please clarify this?

The first one is a primitive boolean with default value false.
The second one is a Wrapper class of Boolean with default value false.
Apart, I can't see any more difference.
Edit : (Thankyou #carsten #sasha)
Apart from the declaration, another point worth mentioning is with the second declaration the value of _userIsLoggingIn may become null later on where as the primitive cannot.

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.
Now choose your way

Frist one is java primitive and second one is an object/refrence types that wraps a boolean.
Converting between primitives and objects like this is known as boxing/unboxing.
boolean can be yes or no.
Boolean can be yes, no or NULL.

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.
More info :
What's the difference between boolean and Boolean in Java?

As others said, the first declaration is a primitive while the second is wrapper class.
I would like to add that the second declaration creates a warning when using Java 5 or newer.
Declaring _userIsLoggingIn like
private static Boolean _userIsLoggingIn = false;
instead of
private static Boolean _userIsLoggingIn = Boolean.valueOf(false);
will use Boolean.FALSE, avoiding the creation of a new Boolean instance

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

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

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!

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

Categories

Resources