I have the following code:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Why does my check up on the Boolean variable "bool" result in an exception?
Shouldn't it just jump right past the if statement when it "sees" that it isn't true?
When I remove the if statement or check up on if it's NOT null, the exception goes away.
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.
In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:
if(bool != null && bool) { ... }
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue():
BooleanUtils.isTrue( bool );
Checks if a Boolean value is true, handling null by returning false.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
Boolean types can be null. You need to do a null check as you have set it to null.
if (bool != null && bool)
{
//DoSomething
}
if (bool) will be compiled to if (bool.booleanValue()) aka unboxing and that would throw a NullPointerException if bool is null.
Other solutions for nullable boxed Boolean evaluation:
JDK 9+ requireNonNullElse(obj, defaultObj)
import static java.util.Objects.requireNonNullElse;
if (requireNonNullElse(bool, false)) {
// DoSomething
Google Guava 18+ firstNonNull(first, second)
import static com.google.common.base.MoreObjects.firstNonNull;
if (firstNonNull(bool, false)) {
// DoSomething
false is used as the default for the null-case here.
as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.
Objects.equals()
There is nothing wrong with the accepted answer by K-ballo. If you prefer a single simple condition and like me you don’t like Yoda conditions, since java 1.7 the answer is
if (Objects.equals(bool, true)) {
or if at the same time you prefer to be really explicit
if (Objects.equals(bool, Boolean.TRUE)) {
Or better: avoid the issue
It’s not recommended to use Boolean objects thereby allowing a Boolean reference to be null in the first place. The risk of a NullPointerException like the one you saw is too great. If you need a kind of tri-state logic, it’s better to define an enum with three values. For example
enum MyTristateBoolean { FALSE, DONT_KNOW, TRUE }
Now we don’t need null at all. The middle constant should probably be named UNKNOWN, UNDEFINED, NOT_EXISTING or something else depending on your exact situation. You may even name it NULL if appropriate. Now depending on taste your comparison becomes one of the following two.
if (myBool.equals(MyTristateBoolean.TRUE)) {
if (myBool == MyTristateBoolean.TRUE) {
The latter works since the compiler guarantees that you will only have one instance of each enum constant. As most of you know == doesn’t work for comparing objects of non-enum type for equality.
Related
I was wondring what the best way to check if we have a valid reference in java. I know that this syntax works, but its a mouth full.
if (myObj == null) {
// Do something knowing we have an object
}
I'm coming from some other languages that allow you to just check a pointer like in c++.
char* prt = null;
if (ptr) {
// We know we have a valid c-string
}
Is there any equivocate or similar syntax in java? I would be okay using compiler extensions or a preprocessor.
Follow up before. Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't.
if (myObj = null)
Will be caught by the compiler/linter.
Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool, so you have to use the somewhat more long-winded notation
if (myObj == null)
whereas in C++ we can write
if (myObj)
In this respect, Java is less terse, and arguably clearer.
There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, e.g. while (cin >> x) { ... }.
However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T>, and use its methods to hide null checks.
Here is a short example:
String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });
The above prints "Hello". If you set s to null, the code would print nothing.
Oracle's article on using Optional<T>.
if(x == null) {
doSomething();
}
... is the general idiom in Java. Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values.
Another common idiom is to use x == null in a ternary statement:
return x == null ? "not found" : x;
Or to use a standard method to throw an exception early on nulls:
Objects.requireNonNull(x);
More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility.
On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves).
In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case.
A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern).
I would like to know the difference(w.r.t code size and/or performance) of the following snippets:
if(null == someObject.getSomeProperty()){
...
}
vs
if(someObject.getSomeProperty() == null ){
...
}
In my opinion performance and generated bytecode size should be the same. The first pointed style ( null == value) comes from C/C++ where anything different from 0 was considered true while something equal to 0 was false. To avoid an issue it is approached in this way: null == value, then you made sure that this is a condition.
As java has a boolean type, it is useless to approach a condition this way, more it is considered a bad practice. It is referred to as Yoda Condition.
A sole reason where this approach should be used when verified against a literal value:
if("someValue".equals(input)) {
// do something
}
if (BigDecimal.ONE.equals(input)) {
// do something
}
writing the code in the natural way would throw a NullPointerException exception if the input is null hence the condition should be written more defensive like:
if (input != null && input.equals("someValue")) {
// do something
}
There's no difference in the performance. Furthermore in modern languages that shouldn't be any of your concern since the compiler would do the optimization for you.
The only reason for writing these so-called "yoda conditions" (having the compare statement in the 'wrong' order) is comparing specific values to values that might be null when using equals, example:
if("blue".equals(sky.getColor())){
//...
}
because if you wanted to write it the intuitive way, you'd have to perfom a manual null check:
if(sky.getColor() != null && sky.getColor().equals("blue")){
//...
}
I've come across this code in one of the projects I'm working on
(This is in Java)
if (Boolean.TRUE.equals(foo.isBar()))
Foo#isBar() is defined as boolean isBar(), so it can't return null
Is there really any reason why it should be written that way?
I myself would just write
if (foo.isBar())
, but perhaps I'm missing something subtle.
Thanks
I hope foo.isBar() returns a boolean. In that case you can always write if (foo.isBar()). If you foo.isBar() returns Boolean then it can be either Boolean.TRUE, Boolean.FALSE or NULL. In that case if (Boolean.TRUE.equals(foo.isBar())) makes sure the if block is executed in one scenario(TRUE) and omitted in remaining 2.
Over and above if (foo.isBar()) will fail, when foo.isBar() returns Boolean NULL.
Since isBar returns a primitive boolean, there is no semantic difference. Additionally, the second way is more concise, more clear, and more efficient, since the result won't have to be autboxed for the call and then have the original boolean extracted again. Given all that, there is no reason to use the first method, and several to use the second, so use the second. I give a great deal of leeway to fellow coders, but I would sit down and have a chat with anyone who added something like that to professional code.
I would suspect "old legacy code with no good reason" - and in fact, I would contend it is worse. (I wonder how ints are compared ..)
The code that uses TRUE.equals requires a boxing conversion, an additional method call (and everything inside) and, in the end, it just looks sloppy.
The only reason I am aware of is if foo.isBar was typed as returning Boolean (not boolean) and where it may return null:
Boolean b = null;
// throws an exception when it tries to unbox b because it is null
boolean isTrue1 = (boolean)b;
// evaluates to false
boolean isTrue2 = Boolean.TRUE.equals(b);
// evaluates to false as well
boolean isTrue3 = b != null ? (boolean)b : false;
Did I find this practical example, can be useful to someone:
When boxed type java.lang.Boolean is used as an expression it will throw NullPointerException if the value is null as defined in Java Language Specification §5.1.8 Unboxing Conversion.
It is safer to avoid such conversion altogether and handle the null value explicitly.
Noncompliant Code Example
Boolean b = getBoolean();
if (b) { // Noncompliant, it will throw NPE when b == null
foo();
} else {
bar();
}
Compliant Solution
Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
foo();
} else {
bar(); // will be invoked for both b == false and b == null
}
in the first condition you are checking for the equality of Boolean object corresponding to true.
and you are using the first condition in your code because your java version doesn't support autounboxing hence you need to use the boolean object.
What is the difference between Boolean.TRUE and true in Java?
In a project I've been trying to familiarise myself with, I ran across a method that looks like this:
public boolean testString(String string){
return string != null && !"".equals(string);
}
What is the value of testing the string for emptiness this way instead of with the variable first? I understand why we see constant-first (Yoda syntax) in C, but is there any reason to do so with method calls in Java?
note: I do understand about NullPointerException, which is not possible in this instance. I'm looking for a value to doing it this way in this case particularly.
In this context it makes little difference, as it already tested for null. Usually you do it this way to make sure you don't call a member on a null-reference (resulting in a NullPointerException), i.e.
"test".equals(myString)
will never throw a null pointer exception whereas
myString.equals("test")
will if myString is null. So basically, the first test makes sure it's a string (not null) AND it's equal to "test".
For two strings it doesn't matter much, but when there is a non-final type involved it can be a micro-optimization.
If the left hand side is a non-overridden concrete type, then the dispatch becomes static.
Consider what the JIT has to do for
Object o;
String s;
o.equals(s)
vs
s.equals(o)
In the first, the JIT has to find the actual equals method used, whereas in the second, it knows that it can only by String.equals.
I adopted the habit of doing
"constant value" == variableName
in other languages, since it means that the code will fail to parse if I mis-type = instead of ==.
And when I learned Java, I kept that order preference.
The usual reason for using "constant string".equals(variable) is that this works properly even if variable is null (unlike variable.equals("constant string")). In your case, however, since you are testing that string != null in a short-circuit boolean test, it's entirely a matter of style (or habit).
If they just did this:
!"".equals(string);
then they're avoiding the possibility of a NullPointerException, which is pretty smart. However, they're checking for null right before this condition, which is technically not necessary.
Is it running any tools like checkstyle? if it is, putting the variable first will result in checkstyle failing. Another reason is that if you put the empty string first it will take away the possibility of getting a null exception if the variable is null because the expression will always evaluate to false. If you had the variable first and the variable was null it will throw an exception.
It is more than a coder preference. If the purpose of the method was only to check that string is not an empty String (without caring whether its a null) then it makes sense to have the constant first to avoid a NullPointerException.
e.g. This method will return the boolean outcome. false in case string is null.
public boolean testString(String string){
return !"".equals(string);
}
while this one may throw a runtime exception if string is null
public boolean testString(String string){
return !string.equals("");
}
No, it is unnatural, and harder to read. It triggers a pause for most readers, and may wastefully consume lots of resources on stackoverlow.com.
(Better use string.isEmtpy() anyway)
There are no fixed rules tho, sometime this is easier to read
if( null != foobar(blahblahblah, blahblahblah, blahblahblah) )
than
if( foobar(blahblahblah, blahblahblah, blahblahblah) != null )
This question can be answered on a number of levels:
What does the example mean?
As other answers have explained, !"".equals(str) tests if str is an non-empty string. In general, the <stringLiteral>.equals(str) idiom is a neat way of testing a string that deals with the null case without an explicit test. (If str is null then the expression evaluates to false.
Is this particular example best practice?
In general no. The !"".equals(str) part deals with the case where str is null, so the preceding null test is redundant.
However, if str was null in the vast majority of cases, this usage would possibly be faster.
What is a better way to do this from a code-style perspective?
return "".equals(str);
or
return str != null && !str.isEmpty();
However, the second approach doesn't work with Java versions prior to 1.6 ... because isEmpty() is a recent API extension.
What is the optimal way to do this?
My gut feeling is that return str != null && !str.isEmpty(); will be fastest. The String.isEmpty() method is implemented as a one-line test, and is small enough that the JIT compiler will inline it. The String.equals(Object) method is a lot more complicated, and too big to be inlined.
Miško Hevery (see his videos on youtube) calls this type of overkill "paranoid programming" :-)
Probably in this video:
http://www.youtube.com/watch?v=wEhu57pih5w
See also here: http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/
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.