I am trying to practice for a QA interview and I want to handle as many test cases as I can think of. I believe my method works for every case except when the input is null
I am not sure how to handle that exception. The compiler will give me an error first before the code even runs. So I am not sure how to deal with that exception. I read around and catch
ing the NullPointerException
is not recommended. How would I deal with handling a null
input. Also if anyone else can think of other test cases, I would be happy to test and have a look at it!
Here are my test cases:
""
"abcdef"
"abbbba"
null
not quite sure how to handle
escape characters
"\n" --> "n\"
"\t" --> "t\"
special characters such as
áe --> eá
Code:
public static String reverseStr(String str) {
int len = str.length();
if (len <= 0) {
return "Empty String";
}
char[] strArr = new char[len];
int count = 0;
for (int i = len - 1; i >= 0; i--) {
strArr[count] = str.charAt(i);
count++;
}
return new String(strArr);
}
After further suggestions here is the updated code:
public static String reverseStr(String str) {
if ( str == null ) {
return null;
}
int len = str.length();
if (len <= 0) {
return "";
}
char[] strArr = new char[len];
int count = 0;
for (int i = len - 1; i >= 0; i--) {
strArr[count] = str.charAt(i);
count++;
}
return new String(strArr);
}