How does recursive method to count white spaces in a string work?

java, oop, recursion

Solution

Since the method returns an int, not a string, it adds the numbers, not concatenates as characters/strings. ie

0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4

not

"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0" 
== "01000000100100000010"

below returns an int, since countspaces returns an int

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));

Problem

I'm trying to fully understand how the method works, see the code below: ``` public static void main(String[] args) { System.out.println(countspaces("a number of spaces ")); } public static int countspaces(String s) { if (s.length() == 0) return 0; else return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1)); } ``` I've debugged the method using BlueJ. The line: ``` return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1)); ``` firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by ``` (s.charAt(0) == ' ' ? 1 : 0) ``` and ignoring the 0's. Please advise me what is missing from my reasoning. Many Thanks Grzegorz(Greg)

Original source