+ 1

Java: Why won't this function work without a kinda crappy workaround?

This is a simple function to reverse a string. If I run it as is it will go like this, Input: "abc" Output: "nullcba" private static String reverseString(String input){ String result; for(int i=input.length()-1; i>=0; i--){ result = (result + input.charAt(i)); } return result; } I have to do something like this to get a clean output? What am I missing? private static String reverseString(String input){ String result = ""; for(int i=input.length()-1; i>=0; i--){ if (result==null){ result=(""+input.charAt(i)); }else { result = (result + input.charAt(i)); } } return result; }

13th Apr 2020, 4:37 AM
Carl Payne
Carl Payne - avatar
1 Resposta
+ 5
Because you did not initialize String <result> in the first implementation; the String <result> is initialized by null. In second implementation you initialized <result> by "" (empty string).
13th Apr 2020, 4:46 AM
Ipang