4

Is there a good way to do away with null values in java like in ruby there is:

x = null || "string"

I want to do somthing like this.

String line = reader.readLine() || "";

To prevent null values being passed.

4 Answers 4

12

You could use Guava and its Objects.firstNonNull method (Removed from Guava 21.0):

String line = Objects.firstNonNull(reader.readLine(), "");

Or for this specific case, Strings.nullToEmpty:

String line = Strings.nullToEmpty(reader.readLine());

Of course both of those can be statically imported if you find yourself using them a lot.

Sign up to request clarification or add additional context in comments.

6 Comments

Guava is amazing, you should take the time to familiarize yourself with it. I will not work on a Java project again without it.
@Bill: I concur absolutely :)
Is it really worth embedding an entire library to deal with something that simple? Why not just add a line of code to check if your string is null?
@svz same thoughts here. It is a 2MB library! It is an "enterprise" library from Google. Certainly overkill.
@svz: Yes, it is - because it gives you way more than just that, and once you've made the decision to use it for one thing, you'll find it helps all over the place. For any one specific thing it may be overkill - but for the whole combined package, it's wonderful.
|
6

No, there is no null-safe syntax in Java. You should do it manually. Alternatively, you can create or use an utility like commons-lang:

String line = StringUtils.trimToEmpty(reader.readLine());

That way you'll get either the value, or "" if it's null

Comments

1

Not really. You can assign the result of readline() to a temp variable and then conditionally assign it:

String t = reader.readline();
String line = t == null ? "default" : t;

but that's about the best you can do.

Comments

0

readLine() can return null as well. You should just check for null when you need to use the String.

2 Comments

I think that was the point. If readLine returns null then use empty string instead.
@JamesMontagne, he stated he wanted something like this: String line = reader.readLine() || ""; If readLine can return null, and if this construct is allowed, you still can be left with a null. I know Guava and Apache libraries are really good, but we are going to end up soon with applications built with 30 libraries sitting on top of each other. So I still think this is the best answer. Does he really need a 2MB "enterprise" library for this? You all decide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.