c2 = h (first char of hello), if it is not equal to c to_return += c2? what does this mean, more importantly what is +=
Basically, if the current first char
of the String
is not equal to c
(the character to remove), append it to the to_return
value. +=
is a shorthand (in this String
concatenation) for to_return = to_return + c
The next step is very confusing for me too! s = s.substring(1); what does this do in this case I only understand substrings by (1,4) etc!
s.substring(1)
creates a new String
of s
starting from the second character, remember, String
is, essentially, 0
indexed character array. This is basically trimming of the first character of the s
and assigning the result back to s
.
So, for example, if s
equals Hello
, after s = s.substring(1)
, s
will be equal to ello
Think of it like s.substring(1, s.length() - 1)
. Take a look at String#substring(int)
for more details
return to_return; // won't be reached
is true, but
if (s.equals(""))
return to_return;
Ensures that it will, eventually return a value. Personally, I like to have a single entry and exit point for all my methods, as it reduces the complexity of probability that you'll miss something that will have you scratching your head, but that's just me...
The reason that the last return
is required is because the compiler can't determine if the method could ever return or not.