I want to know the difference between these two codes even though they produce the same output:

CODE 1:

class ret { public static int add(int x) { if(x!=0) return x+add(x-1); return x; } public static void main(String args[]) { System.out.println(add(5)); } }

CODE 2:

class ret { public static int add(int x) { if(x!=0) return x+add(x-1); return 0; } public static void main(String args[]) { System.out.println(add(5)); } }

They both output 15 but how come the second code also output’s 15 instead of zero?My understanding is that the last call would be add(0) for code 2 and it would return zero.I also want to know is it okay to use multiple return statements or use a single return statement and replace the rest with local variables.I remember reading that single entry single exit model is a good practice.

## Answer

This is a recursive method, so when `x != 0`

, you will return the result of “`x`

added to calling the method again with `(x-1)`

“. The final call will always return `x == 0`

or `constant = 0`

, so you will return `15`

from both versions.

Single return vs. multiple return is a matter of debate. The former should be preferred as a rule. Generally it will be obvious where multiple return statements are acceptable as it will be simpler to understand the method with them than with the alternative code constructs required to engineer a single exit point. Also note you could rewrite `add`

as:

public static int add(int x) { return x == 0 ? 0 : (x + add(x-1)); }

Version 1:

add(5) call add(4) call add(3) call add(2) call add(1) call add(0) return (x = 0) return (x = 1) + (add(x-1) = 0) = 1 return (x = 2) + (add(x-1) = 1) = 3 return (x = 3) + (add(x-1) = 3) = 6 return (x = 4) + (add(x-1) = 6) = 10 return (x = 5) + (add(x-1) = 10) = 15

Version 2:

add(5) call add(4) call add(3) call add(2) call add(1) call add(0) return (constant = 0) // the only difference return (x = 1) + (add(x-1) = 0) = 1 return (x = 2) + (add(x-1) = 1) = 3 return (x = 3) + (add(x-1) = 3) = 6 return (x = 4) + (add(x-1) = 6) = 10 return (x = 5) + (add(x-1) = 10) = 15