java : Handling Null check through a Combination - java

I am able to handle null check on a String with this below piece of code
if (acct != null && !acct.isEmpty()|| !acct.equals(""))
what i mean from the above code is , if
Accountid is not equal to null And
Accountid length is greater than 0
(These two is a combination of checks )
Or
Accountid is not equal to ""
Does my code satisfy these combination i mentioned above , or do i need to add any brackets ?? to satisfy the combination ( first 1 and 2 ) i mentioned above ??
Thanks

Yes it does, and is always evaluated before or, i.e. your code is the same as
if ((acct != null && !acct.isEmpty()) || !acct.equals(""))
However, logically it does not make sense to me. Do you really need the last part? Isn't "acct.isEmpty()" the same as "acct.equals(""))" in this specific instance?

isEmpty() and .equals("") are exactly the same condition. And your test will throw a NullPointerException if acct is null.
I don't understand exactly which test you want to make, but this one is wrong. Think about it once again, and implement a unit test to test all the cases:
null string,
empty string,
not empty string.

As per your question framed by you, it should have brackets as below
if ((acct != null && !acct.isEmpty()) || !("".equals(acct) ))
After the || operator, the code is changed which will avoid facing NullPointerException when acct is NULL.
This SO answer explains more about using "".equals().
https://stackoverflow.com/a/3321548/713414

Related

Java Stream.builder() in Collector null problem

The aim is to use a Stream to iterate over an array, filtering/extending values as required and collecting the result in a new Stream.
Trying to use Stream.builder(), as in the following three examples, I'll always get a Stream with the expected Strings, but lots of trailing nulls. In addition, I can't process null elements this way.
I suspect, the internal fixed buffer in Stream.builder() is the problem.
Is there a way, to prevent 'trailing' nulls with this approach, without loosing the ability to use null values as Stream elements?
String[] whitespaces = new String[] { " ", "\n", "\r", "\t" };
int len = whitespaces.length;
boolean addNulls = false;
int flexBoundary = addNulls ? len : len - 1;
Stream<String> whitespaceNullStringStream = IntStream.rangeClosed(0, flexBoundary)
.mapToObj(idx ->
addNulls && idx == flexBoundary
? null
: whitespaces[idx])
// #1
.collect(Stream::<String>builder, Builder::add, (b1, b2) -> Stream.concat(b1.build(), b2.build())).build();
// #2
// .collect(Stream::<String>builder, Builder::add, (b1, b2) -> Stream.builder().add(b1).add(b2)).build();
// #3
// .collect(
// Collector.of(
// Stream::<String>builder,
// Builder::add,
// (b1, b2) -> b1.add(b2.build().reduce(String::concat).get()),
// Builder::build
// )
// );
If I instead use the following, it'll work as expected, except null values are converted to Strings, of course, which is not desirable here:
.collect(
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
(sb) -> Stream.of(sb.toString())
)
)
To overcome this, I've used the following approach:
Stream<String> stream = IntStream.rangeClosed(0, flexBoundary)
.mapToObj(idx -> addNulls && idx == flexBoundary ? null : whitespaces[idx])
.collect(Collector.of(
ArrayList<String>::new,
List::add,
(l1, l2) -> { l1.addAll(l2); return l1; },
(list) -> list.stream()
)
);
But, as described above, I'd like to use the Stream.builder() approach inside a Collector, which works the same.
Most of the stream API will fast-crash when null is involved. The things just aren't designed for it.
There are different ideas about what null actually means. Reductively, null in java means one of 3 things:
The field was not initialized (private String hello; starts out as null)
The array slot was never written to (new String[10] starts with 10 null values)
Somebody explicitly used null, the keyword.
But that's not too useful. Let's talk semantics. What does it mean when an API returns null for something, or when you use null in some code?
There are different semantic takes on it too:
It means: Not initialized, not applicable, unexpected, no result.
In this case, exceptions are good and anything you could possibly want here would be wrong. You can't ask "concatenate this unknown thing to this string". The correct answer is not to silently just skip it. The correct answer is to crash: You can't concatenate an unknown. This is what SQL does with null quite consistently, and is a usage of null in java that I strongly recommend. It turns nulls downsides into upside: You use null when you want that exception to occur if any code attempts to interact with the thing the pointer is pointing at (because the idea is: There is no value and the code flow should therefore not even check. If it does, there is a bug, and I would like an exception to occur exactly at the moment the bug is written please!).
In light of your code, if that's your interpretation of null, then your code is acting correctly, by throwing an exception.
It's a sentinel value for something else
This is also common: That null is being returned and that this has an explicit semantic meaning, hopefully described in the documentation. If you're ever written this statement:
if (x == null || x.isEmpty())
it is exceedingly likely you're using this semantic meaning of null. After all, that code says: "At least for the purposes of this if, there is no difference at all between an empty string and a null pointer.
I strongly recommend you never do this. It's not necessary (just return an empty string instead!!), and it leads to friction: If you have a method in a Person class named getTitle() that returns null when there is no title, and the project also states that title-less persons should just act as if the title is the empty string (Seems logical), then this is just wrong. Don't return null. Return "". After all, if I call person.getTitle().length(), then there is a undebatably correct answer to the question posed for someone with no title, and that is 0.
Sometimes, some system defines specific behaviour that strongly leans towards 'undefined/unknown/unset' behaviour for a given field. For example, let's say the rules are: If the person's .getStudentId() call returns a blank string that just means they don't have an ID yet. Then you should also never use null then. If a value can represent a thing, then it should represent that thing in only one way. Use null if you want exceptions if any code tries to ask anything at all about the nature of this value, use an existing value if one exists that does everything you want, and make a sentinel object that throws on certain calls but returns default values for others if you need really fine grained control.
Yes, if you ever write if (x == null || x.isEmpty()), that's right: That's a code smell. Code that is highly indicative of suboptimal design. (Exception: Boundary code. If you're receiving objects from a system or from code that isn't under your direct control, then you roll with the punches. But if their APIs are bad, you should write an in-between isolating layer that takes their badly designed stuff and translates it to well-designed stuff explicitly. That translation layer is allowed to write if (x == null || x.isEmpty()).
It sounds like this is the null you want: It sounds like you want the act of appending null to the stringbuilder to mean: "Just append nothing, then".
Thus, you want where you now have null to act as follows when you append that to a stringbuilder: To do nothing at all to that stringbuilder.
There is already an object that does what you want: It's "".
Thus:
mapToObj(idx ->
addNulls && idx == flexBoundary
? ""
: whitespaces[idx])
You might want to rename your addNulls variable to something else :)

Handling null values while extracting using java from MongoDB

Frequently, I extract the data from mongo database using java (because I have to do it across very large number of collection across many databases). In the process, I generally use
Eg:
time = ((myObject.containsField("time"))) ? (myObject.get("time").toString().isEmpty()) ? "Empty" : myObject.get("time").toString() : "NA";
to make sure if the string exists or it is empty. but how do we do a null check, I mean if time has a value null
Eg: time=null
How do we extract the value to script so that I can save it to the extract as some string which represents null value?
.get is resulting in to a NullPointerException. This is a run time check and I often extract more than 20 values for each record. What is the best way to do a null check?
your help is much appreciated. Thanks in advance!! :)
If .get() is throwing the the null pointer exception you could simply add another ternary case around it, for .get() to throw an NPE myObject must be null. Thus, this should work
time = myObject != null ? ((myObject.containsField("time")))?
(myObject.get("time").toString().isEmpty())?"Empty":myObject.get("time").toString():"NA" : "null";
To account for the above comments, .get doesn't appear to be what is throwing the NPE, .toString() must be. Alter the code thusly:
time = myObject.containsField("time") ? myObject.get("time") != null ?
(myObject.get("time").toString().isEmpty())?"Empty":myObject.get("time").toString():"NA" : "null";
The extra ternary block, will now check if the resulting "time" key results in a null pointer.

Checking if an Object is null at the same time as a value of one of it's fields

Which of these would be correct?
if(dialog != null && dialog.isShowing){}
if(dialog.isShowing && dialog != null){}
if(dialog != null){
if(dialog.isShowing){}
}
The first and third ones are both OK to use because they won't process past the null check. The second one can result in a NullPointerException because it's referencing dialog before you've checked if it's null.
The && operator in Java will stop evaluating (from left to right) as soon as it encounters a false. Therefore in
if(dialog != null && dialog.isShowing){}
dialog.isShowing() will not be called if the dialog is null and is therefore "safe" to use.
This:
if(dialog != null){
if(dialog.isShowing){}
}
will work as well, but generally nesting if-statements like this is avoided as it decreases readability.
Even though everything has been answered, for the sake of completeness:
The way Java evaluates conditional clauses is called Short circuit evaluation. This means that once the result of the condition is asserted, further clauses will not be evaluated.
Edit: My statement is not completely true actually. Java uses Short circuit evaluation when using || and && (which is the standard what every programmer uses, thus my statement in the first place), but you may force Java to evaluate all statements by using & and |
The && operator is called a short circuit operator. This means once the result is known. i.e., false && x is always false it doesn't evaluate the remaining expressions.
A variation on this is using the || short circuit, OR operation, like:
if(text == null || text.isEmpty())
It's shortcut logic. When first expression is false, Java will not check second expression, because whole expression is false definity.
First case is best practice.
Second case is incorrect.
You may use try and catch if you want to use the second one otherwise the first and the third one are correct.

null comparison

This might sound like a real dumb question but please bear with me :)
so I have a if condition in my code like if ((msgBO.getEmpId().equals("") == false )) {
// do something
} My question is, if I make the above statement as msgBO.getEmpId().equals(null) == false
would it make any difference or this way I am trying to compare two different things?
Yes, there is a big difference between "" (the empty String) and null (no String at all).
Any Object reference can point to null. That represents 'no data' or 'nothing.' The empty string "" represents a String with no length.
An example of this is the following:
String one = null;
String two = "";
int oneLength = one.length();
int twoLength = two.length();
The first call to length will throw a NullPointerException. And the second will return 0.
These are different things. In particular, the test
msgBO.getEmpId.equals(null) == false
a.k.a.
!msgBO.getEmpId.equals(null)
is guaranteed to always succeed (at least, if the equals method involved is written according to the standard set of rules), since no object is ever allowed to compare equal to null:
For any non-null reference value x, x.equals(null) should return false.
(Documentation of equals)
So, in other word, if you already know, that msgBO.getEmpId != null, then you also know the outcome of the call to equals. And unless you know that msgBO.getEmpId != null, calling equals is a NullPointerException waiting to happen. So, one often sees:
msgBO.getEmpId != null && msgBO.getEmpId.equals("...stuff...")
or even
"...stuff...".equals(msgBO.getEmpId)
"" (an empty string) and null are not the same. .equals(null) on a String will never return true.
A null reference and String of length 0 are two completely different things in Java. Two other points:
getEmpId is either a getter method missing the braces for method invocation or a public field, which is generally frowned upon (and badly named in this case).
if getEmpId is/returns null, teh calling equals() on it will caus a NullPointerException - which is why you should reverse the comparison when comparing with literal strings: if("foo".equals(variable))
Comparing a boolean expression explicitly using == is ugly. Instead you can use negation: if(!msgBO.getEmpId.equals("")) or if(!msgBO.getEmpId != null)
They are different , what you want is
msgBO.getEmpId == null
for the other case
You are trying to compare two different things. It might still work, but one is checking for an empty string and one is checking if the variable is null.
Also a faster check to see if the string is empty is just to check
if (string.length == 0).
(You will get an exception, however, if the string is null so don't do this if null checking, unless you want to handle the null case with the caught exception).
It does make a difference.
msgBO.getEmpId.equals("") compares msgBO.getEmpId with an empty String
msgBO.getEmpId.equals(null) compares msgBO.getEmpId with a null value. This is wrong because it will throw NullPointerException if msgBO.getEmpId is null. If you want to check if the value is null you should use such a condition instead: msgBO.getEmpId == null.
What is correct in this situation depends on the type of a value returned by msgBO.getEmpId. If it isn't String then only comparing with null makes sense. If it is String both values may have sense and then it depends how you represent an empty value of msgBO.getEmpId. In this case if you use null for an empty value you should compare with null and if you use "" for an empty value you should compare with "".

Does Java check all arguments in "&&" (and) operator even if one of them is false?

I have such code:
if(object != null && object.field != null){
object.field = "foo";
}
Assume that object is null.
Does this code result in nullPointerException or just if statement won't be executed?
If it does, how to refactor this code to be more elegant (if it is possible of course)?
&& does short circuit while & would not.
But with simple questions like this, it is best to just try it (ideone can help when you don't have access to a machine).
&& - http://ideone.com/LvV6w
& - http://ideone.com/X5PdU
Finally the place to check for sure would be the JLS §15.23. Not the most easy thing to read, the relevent section states:
The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
Java does have short circuit evaluation, i.e. your code should be ok
One way to know it! Test it! How? Well, make a method which prints out something:
public static boolean test(int i)
{
System.out.println(i);
return false;
}
...
if (test(1) && test(2) && test(3))
{
// not reached
}
This prints:
1
So the answer on your question is "no".
Best way to find out would be try it, especially for a single line question. Would have been faster, too.
The answer is that Java will not execute the body of the "if".
This will not throw any NullPointerException . The condition will be evaluated from left to right and the moment first false expression is found it will not evaluate remaining expression.
Maybe this other question helps you:
Differences in boolean operators: & vs && and | vs ||
Java has short circuit evaluation, so it will be fine.
The code looks ok to me, but do you actually need to check object.field != null? I think that test can be omitted as you never use the variable, just set it.
On a side-note, most programmers wouldn't access fields directly (object.field) but rather through getters/setters (object.setField(x);). Without any more context to go on, I can't say if this is appropriate in your case.
&& and || conditions stops at the point they can decide whether the condition is true/false, in your case, the condition will stop right after object != null and I think that your code is just fine for this case
If you want all of your boolean expressions evaluated regardless of the truth value of each, then you can use & and | instead of && and ||. However make sure you use these only on boolean expressions. Unlike && and ||, & and | also have a meaning for numeric types which is completely different from their meaning for booleans.
http://ibiblio.org/java/course/week2/46.html
Although short circuiting would work here, its not a guarantee that (like I have done many times) you'll get the order wrong when writing another, it would be better practice to nest those if statements and define the order you want the boolean checks to break:
if(object != null)
{
if(object.field != null)
{
object.field = "foo";
}
}
This does exactly the same as you're essentially saying, if the first boolean check fails don't do the second; it is also nullPointerException safe as object.field will not be checked unless object is not null
Using short-circuiting on booleans can become annoying later on as when you have a multiple bool if statement it becomes trickier to efficiently debug which part short circuited.

Categories