Method to concatenate 2 Strings in Java

concatenation, java, refactoring, string

Solution

Sure:

public static String concat(String str1, String str2) {
  return str1 == null ? str2
      : str2 == null ? str1
      : str1 + str2;
}

Note that this takes care of the "both null" case in the first condition: if `str1` is null, then you either want to return null (if `str2` is null) or `str2` (if `str2` is not null) - both of which are handled by just returning `str2`.

Problem

I have a method in Java that concatenates 2 Strings. It currently works correctly, but I think it can be written better. ``` public static String concat(String str1, String str2) { String rVal = null; if (str1 != null || str2 != null) { rVal = ""; if (str1 != null) { rVal += str1; } if (str2 != null) { rVal += str2; } } return rVal; } ``` Here are some of the requirements: - If both str1 and str2 are null, the method returns null - If either str1 or str2 is null, it will just return the not null String - If str1 and str2 are not null, it will concatenate them - It never adds "null" to the result Can anyone do this with less code?

Original source