What will the following code print out?

public class Main {
    public static void main(String[] args) {
        recur(99);
    }
    public static void recur(int a) {
        if (a <= 100) {
            System.out.println("a=" + a);
            recur(++a);
            System.out.println("a=" + a);
        }
    }
}
 
Explanation
a = 99 will be printed first, and after the prefix increment a recur() method will be executed again, but with a parameter which value is 100. Therefore, a = 100 will be printed out second. Next recur() will be called with a parameter value of 101, but the condition will not be executed because the passed parameter is greater than 100, and parameter value a = 101 will be printed. After this the program will return to its previous execution and will print out a = 100.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback