Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to concatenate 2 Strings in Java

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:

  1. If both str1 and str2 are null, the method returns null
  2. If either str1 or str2 is null, it will just return the not null String
  3. If str1 and str2 are not null, it will concatenate them
  4. It never adds "null" to the result

Can anyone do this with less code?

like image 930
Ryan Avatar asked Mar 17 '10 13:03

Ryan


1 Answers

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.

like image 151
Jon Skeet Avatar answered Oct 17 '22 23:10

Jon Skeet