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.
Related
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
I need to check if the object entity satisfies certain rules. My object is a phone call, I need to check if it satisfies certain criteria or not to proceed with later logic. Please, find my solution below.
private static boolean isGPRS(CallXCD callXCD){
String serviceName = callXCD.getServiceName();
boolean isGPRS = false;
if(serviceName.compareTo("GPRSB")==0)
isGPRS = true;
return isGPRS;
}
private static boolean isVoice(CallXCD callXCD){
String serviceName = callXCD.getServiceName();
boolean isVoice = false;
if(serviceName.compareTo("TEL")==0)
isVoice = true;
return isVoice;
}
Then I will check if isGPRS returns true, I will do X. If isVoice returns true, I will do Y. I am not sure if what I did was the best practice because I pass the same object several times.
Is it better to build an array of booleans and pass the object one time in one method, do all calculations then pass the values to the boolean array. Or wouldn't it make any difference on performance?
None of this will make any measurable difference. Such trivial things won't affect performance in a way that you'll be able to tell.
I'd wonder why you have to do this at all. Why static methods? Why not make those members of the CallXCD class and let it simply tell you what kind of thing it is? Keep all the state and logic encapsulated in one place.
Why are you testing types this way? Could this be polymorphic? Object-oriented programming was born to eliminate this kind of "what am I?" if/then/else code.
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!
In some of our companys projects code I often read something like this:
boolean foo = Boolean.FALSE;
Besides the fact that AFAIK I only have to initialize local variables in Java at all (no random values like in Pascal) and besides the fact that especially for booleans I often WANT to have an initialization, what do I miss here? Why not:
boolean foo = false;
I don't get it. And code analyzation tools like PMD and Findbugs mark it, too. But why?
Edit:
Without really knowing much about the bytecode except that it is there I created an example class and decompiled it. The Boolean.FALSE went to:
0: getstatic #15 // Field java/lang/Boolean.FALSE:Ljava/lang/Boolean;
3: invokevirtual #21 // Method java/lang/Boolean.booleanValue:()Z
6: istore_1
The 'false' variant went to:
0: iconst_1
1: istore_1
So without knowing too much about this, I'd guess that more statements means more time to execute so it's not only wrong but also slower in the long run.
boolean foo = Boolean.FALSE;
This is strange and unnecessarily complicated code, written by someone who likely didn't know Java very well. You shouldn't write code like this, and PMD and FindBugs are right to mark this.
Boolean.FALSE is a java.lang.Boolean object that gets auto-unboxed; the compiler essentially translates this to:
boolean foo = Boolean.FALSE.booleanValue();
I don't have to initialize variables in Java at all...
Member variables do not need to be initialized explicitly; if you don't, they'll be initialized with a default value (which is false in the case of boolean). Local variables do need to be explicitly initialized; if you try to use a local variable without initializing it, the compiler will give you an error.
Both are same. but boolean foo = false; is enough.
There is no good reason to do this, it was probably just a novice Java programmer. I wouldn't worry too much, just replace it with false.
At the same time, you can usually if not always arrange your code such that you never declare a variable you don't have the final value for, i.e., making your objects immutable, which makes them easier to think about. What's the value of x? compared to What's the value of x between the calls to foo() and bar()? The first is generally easier to answer. This requires you to split up your classes along lines you might not be used to doing but I recommend at least trying it out.
The style to use an auto-unboxed Boolean constant in fact meshes well with the overall oververbosity endemic to many Java projects. For example:
public boolean isItOrIsItNotTheValueWeExpect(String aStringParameterThatCouldBeNull) {
boolean booleanReturnValue = Boolean.FALSE;
if (aStringParameterThatCouldBeNull != null) {
if (aStringParameterThatCouldBeNull.length() > 3) {
booleanReturnValue = Boolean.TRUE;
}
else {
booleanReturnValue = Boolean.FALSE;
}
}
else if (aStringParameterThatCouldBeNull == null) {
booleanReturnValue = Boolean.TRUE.booleanValue();
}
return booleanReturnValue;
}
Obviously, the code above would be much preferred to this unreadable mess:
public boolean validate(String s) {
return s == null? true : s.length() > 3;
}
The very occurrence of a ternary operator is considered a transgression and some projects even have it flagged by CheckStyle.
If your projects conform to such stylistic guidelines as these, that could justify your suspicious line of code.
There is no difference really although the 1st method won't work on a 1.4 or earlier JVM. The first is more convoluted since it is fetching the static value from the Boolean object and then relying on autoboxing (introduced in 1.5) to change it from a Boolean object to a boolean primitive) although I can't imagine it would ever make any speed difference.
Generally though if you are assuming a particular initial value for a variable then I would recommend initialising it rather than just declaring it as it makes the code more readable.
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.)