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?
Sure:
Note that this takes care of the “both null” case in the first condition: if
str1is null, then you either want to return null (ifstr2is null) orstr2(ifstr2is not null) – both of which are handled by just returningstr2.