Conditional Assignment in Java

Is there a good way to destroy null values ​​in java, like in ruby, is:

x = null || "string" 

I want to do something like this.

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

To prevent the transfer of null values.

+4
source share
4 answers

No, there is no null safe syntax in Java. You must do it manually. Alternatively, you can create or use a utility program, for example commons-lang:

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

This way you get either a value or "" if it is null

+6
source

You can use Guava and its Objects.firstNonNull (removed from Guava 21.0):

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

Or for this particular case, Strings.nullToEmpty :

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

Of course, both of them can be statically imported if you use them heavily.

+12
source

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

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

but this is the best you can do.

+1
source

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

0
source

Source: https://habr.com/ru/post/1433811/


All Articles