Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional assignemnt in Java

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.

like image 834
Pablo Jomer Avatar asked Dec 01 '22 23:12

Pablo Jomer


1 Answers

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.

like image 118
Jon Skeet Avatar answered Dec 09 '22 13:12

Jon Skeet