I can only understand recursion by thinking about what happens if I copy and paste all the code so that everything is in one place.
You can replace mystery(2) with three lines
mystery(1); System.out.println(8); mystery(1);
Therefore, your main method may also say
public static void main(String[] args) { mystery(1); System.out.println(8); mystery(1); }
You can replace both of these mystery(1); calls mystery(1); on the
mystery(0); System.out.println(4); mystery(0);
This means that the main method can also say
public static void main(String[] args) { mystery(0); System.out.println(4); mystery(0); System.out.println(8); mystery(0); System.out.println(4); mystery(0); }
mystery(0); does nothing, so main can just say
public static void main(String[] args) { System.out.println(4); System.out.println(8); System.out.println(4); }
source share