Method to concatenate 2 Strings in Java

Posted by GooF on Stack Overflow See other posts from Stack Overflow or by GooF
Published on 2010-03-17T13:24:32Z Indexed on 2010/03/17 13:31 UTC
Read the original article Hit count: 145

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about refactoring