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:
Can anyone do this with less code?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With