One step check for null value & emptiness of a string - java

I have a setter method.
Then when another (say generate) method is run, I need to check the value of my fields.
So in the case of String property, I need to know if it contains the value or if it was not set.
So it may be null, "" or something meaningful, there are 3 possibilities.
And it is rather boring to check first for a null value :
if (s != null)
then for an empty String
if (!s.isEmpty())
is there a one-step check here? You can tell me that I can initialize my String field with an empty String. [ IS IT COMMON? ] But what if someone passes a null value to the setter method setS?
so do we always have to check if the Object value is null or not before doing something with that object?
Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!

Commons library, StringUtils.isBlank() or StringUtils.isEmtpy().
isEmpty is equivalent to
s == null || s.length() == 0
isBlank is equivalent to
s == null || s.trim().length() == 0

if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}

In the jakarta commons there is a StringUtils.isEmpty(String).

use org.apache.commons.lang.StringUtils, the method StringUtils.isNotBlank check both nullity and emptiness.

Add maven dependency for com.google.guava
Then in your code:
import com.google.common.base.Strings;
if(!Strings.isNullOrEmpty(s)) {
// Do stuff here
}

If you are doing android development, you can use:
TextUtils.isEmpty (CharSequence str)
Added in API level 1
Returns true if the string is null or 0-length.

Related

Empty/NULL Short value in object, returns non-empty String, is this intended? [duplicate]

I was checking String.valueOf method and found that when null is passed to valueOf it returns "null" string instead of pure java null.
My question is why someone will return "null" string why not pure java null.
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
I am asking this because developer will have to check with equals method for "null" string and not like stringObj != null.
[update]: okay there were down votes for this question, I am not raising question in the api but in my current company there are lot of api which returns "null" string instead of pure java null that is why I asked this question to know whether is it a best practice to return "null" string if we found null string object.
You are looking for Objects#toString(java.lang.Object,java.lang.String)
The call
Objects.toString(obj, null)
returns null when object is null.
Because String.valueOf() returns a String representation, which for a null is "null".
The developer shouldn't be checking the return value at all, since it's meant for display purposes, not for checking whether a reference was null or not.
Because you only want a string representation of null and so it did.
Purpose of this method is to return the String representation.
Check link String.valueOf
I would only use valueOf for displaying something directly. It doesn't offer robust enough validation and sanity checking to pass the output directly into a database, and could lead to incomplete data or data corruption.
Using the following query I discovered there were null-values in the columns.
Select * from tableName x where x.name is null

Java NullPointerException check on chained methods

I want to check for a null pointer when accessing a field several classes deep (in a chain of get methods). However, if one of the earlier methods is null I get a NullPointerException anyways.
This is what I want to check, though it can still get a NullPointerException:
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
This the behavior I want the above code to exhibit:
if(x.getLocation() != null)
if(x.getLocation().getBuilding() != null)
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
The field on the pol is optional and should only be set if the above getter is not null. However the building and location objects could also be null, so now I must check to that they're valid.
Is there any sort of shorter way to check all the above like I want?
With Java 8's Optional<> class, you can map a value as so:
Optional.of(x)
.map(ClassOfX::getLocation)
.map(Location::getBuilding)
.map(Building::getSolidFuelInd)
.map(solidFuelInd -> solidFuelInd ? "Y" : "N")
.ifPresent(pol::setWood_heat_ind);
map calls will only be executed if the value of the optional isn't null thus avoiding the NullPointerException.
ifPresent's purpose is to call your setWood_heat_ind only if a value if available.
A nice single-call equivalent to null checks.
If its code reduction you want then you can save each call in a variable.
// note: Replace type with the correct type
type location = x.getLocation();
type building = location == null ? null : location.getBuilding();
// note: you don't have to check for null on primitive types
pol.setWood_heat_ind(building != null && building.getSolidFuelInd() ? "Y" : "N");
This is much cleaner and easier to follow.
Food for thought, you don't check for null on primitive types boolean, int, byte etc. so the last null check on building.getSolidFuelInd() is not needed
Java 8 has Optional<T> which would make for one chained expression, though verbose.
However Java 8 also has Stream<T> and you could have a
"stream" of 0 or 1 item, and then query with lambdas.
x.getLocation()
.map((loc) -> loc.getBuilding())
.map((building) -> building.getSolidFuelInd() != null)
.findFirst()
.ifPresent ...
Or
x.getLocation()
.map(Location::getBuilding)
.map(Building::getSolidFuelInd())
.filter(fuelInd -> fuelId != null)
.findFirst()
.ifPresent ...
It probably will be a matter of slow coming to terms with an application of those new terms.
You could just catch the exception
try{
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
}catch(NullPointerException e){
//e.printStackTrace(); or whatever you want
}
(Referring to your possible solution) checking for the returned values implies invoking the same methods more the once, that's why I would use this solution.
As Jay Harris pointed out, you can obviously check the values and save the return parameter, without having to invoke the same method again. You can do it in many different ways, here one
Object loc=null,build=null;
Boolean SFI = ((loc=x.getLocation())==null?null:
((build=loc.getBuilding())==null?null:
(build.getSolidFuelInd())));
if(SFI!=null)pol.setWood_heat_ind(SFI?"Y":"N");
But is it worth it? I made this more complicated than it could on purpose, but anyway, why doing that if you can try...catch in two simple lines?

When to use 'java.util.Objects.*'?

I was going through Java 7 features and they talked about java.util.Objects class.
What I am failing to understand is what is the functional difference betwee
java.util.Objects.toString(foo)
vs
foo == null ? "":foo.toString()
All I could see extra was a null check and functional notation instead of OOP style.
What am I missing ?
The main advantage of java.util.Objects.toString() is that you can easily use it on a return value that might be null, rather than needing to create a new local variable (or worse calling the function twice).
Compare
Foo f = getFoo();
String foo = (f==null) ? "null" : f.toString();
or the cringe-worthy and bug inducing
String foo = (getFoo()==null) ? "null" : getFoo().toString()
to the Objects.toString based version
String foo = Objects.toString(getFoo());
Calling Objects.toString(foo) just removes the need for you to remember to do null checks, and means you can use it directly on a method return value (e.g. Objects.toString(getPossibleNullObject())) without storing it in a variable first (or calling the method twice).
Note however that the method actually returns:
the result of calling toString for a non-null argument and "null" for a null argument
so it is actually equivalent to:
foo == null ? "null" : foo.toString();
if you want "" for a null value you can use the overload that passes a nullDefault return value Objects.toString(foo, "")

How to prevent null check before equals

I find stuff like this rather annoying and ugly in equals methods:
if (field == null)
{
if (other.field != null)
return false;
}
else if ( ! field.equals(other.field))
return false;
In C# I could've done this:
if( ! Object.Equals(field, other.field))
return false;
Is there something similar in Java, or what is the preferred way to do this kind if thing?
Java 7 offers java.util.Objects.equals.
Use commons-lang:
org.apache.commons.lang.ObjectUtils.equals(Object object1, Object object2)
Source code:
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
From Apache
http://commons.apache.org/lang/
That's about equivalent to what you do in C#
Guava equal which does this :
public static boolean equal(#Nullable Object a, #Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
or null object pattern
Guava also has the somewhat related comparison chain and a load of other goodies.
I would write it this way:
return field != null && other.field != null && field.equals(other.field);
which is not as elegant as the C# code line, but much shorter then the if tree you posted.
I accept all answers technically. Practically I will not use any of them in code I have under control because all provided solutions are working around the core problem: null-values. KEEP YOUR CORE MODEL FREE FROM NULL VALUES, and the question is obsolete in this case.
At system borders like third party libraries one has to deal with null values sometimes. They should converted into meaningful values for the core model. There the given solutions are helpful.
Even if Oracle recommends the equals-Methods to be null-safe, think about that: Once you accept null values your model it is getting fragile. The equals-method will not be the last method where you will check for null. You have to manage null-checks in your method call hierarchy. Methods may not be reusable out of the box anymore. Soon, every parameter will be checked for null.
I saw both sides:
On one side code full of null checks, methods that trust not a single parameter anymore and developers that are afraid to forget a null check.
On the other side code with full expressive statements that make clear assertions to have full functioning objects that can be used without fear of NullPointerExceptions.
As part of the Project Coin, there was a proposal for adding a series of null-safe operators to Java. Sadly, they didn't make it into Java 7, maybe they'll appear in Java 8. Here is the general idea of how they would work
Actually everyone follows there own way to do this and also i would like to introduce groovy here.
There is one way
field == null ? false : true; // So basically it will return true when it is not null.
In groovy there is null safe operator for objects. Lets take an example for class
A {
String name = "test1"
String surName = "test2"
public String returnName() {
return name + surName
}
}
A a = null
a?.name
// Mentioned operator ? will actually check whether a is null or not. then it will invoke name.
Note: i didn't applied semi colon in code as this is not require in groovy.
String.valueOf() will solve some of those problems if the toString is implemented for your classes. It will spit out the toString() answer or "null" if the pointer is null.
Use == operator when you are checking for object references, if both the references refers same object it will return true. Otherwise if you are looking for object content then go with .equals method of objects.
So null means it doesn't have any memory location given in heap. So it can be simply checked with '==' operator.

Looking through an array for an empty string

An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false.
hasEmpty=false;
for (int i=0;i<names.length;i++)
if (names[i].trim().equals("") || names[i]==null)
hasEmpty=true;
Whats wrong with my code?
Calling trim() first will result in a NullPointerException should a member of the array be null. Reverse the order of the conditions - the short-circuiting nature of || will then ensure that trim is only called on a real String object.
Consider names[i].trim().
When names[i] is a String, you really have something like someString.trim() which works fine.
When names[i] is a null, however, you really have something like null.trim(). You've already discovered that null doesn't allow a trim() method. (In fact, I'm not even really sure what 'null' is.)
Therefore, you must check for null before you invoke trim().
When you have a && b, where a and b are expressions, the checks are made left-to-right and the parser stops as soon as the issue is settled. So for the logical and operator (&&), if a is false then b is never checked. This is what allows
if (a != null && a.trim().length() > 0) { ... }
to work. if a is null, the a.trim() part is not executed since it would be pointless from a logical point of view; the value of the conditional has been decided.
Similarly for
if (a == null || a.trim().length() == 0) { ... }
if a is null then the a.trim() part is never performed and we don't get an error.
You can use the Apache Commons Lang's isBlank() to check a String:
if (StringUtils.isBlank(names[i]) {
...
}
StringUtils.isBlank is checking if the String is null or empty (i.e. if it is equals to "" when all blank characters are removed).
It's throwing a Null Pointer Exception because you're trying to run a method on a null object:
if (names[i].trim().equals("") || names[i]==null)
So, anytime that names[] has ONE name that's null, it will throw the exception. One way to solve the problem is to switch the boolean statements in this if statement:
if (names[i]==null || names[i].trim().equals(""))

Categories

Resources