Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 4)
4.
What will be the output of the program?
public class SwitchTest 
{  
    public static void main(String[] args) 
    {
        System.out.println("value =" + switchIt(4)); 
    } 
    public static int switchIt(int x) 
    {
        int j = 1;  
        switch (x) 
        { 
            case l: j++; 
            case 2: j++;  
            case 3: j++; 
            case 4: j++; 
            case 5: j++; 
            default: j++; 
            } 
        return j + x;  
    } 
}
value = 2
value = 4
value = 6
value = 8
Answer: Option
Explanation:

Because there are no break statements, once the desired result is found, the program continues though each of the remaining options.

Discussion:
14 comments Page 2 of 2.

Unknown 21 said:   1 decade ago
Our condition is x=4;

Now, move to case 4, where x=4 and j=1 (a/c to loop , but after the complete execution of j++ in case 4, j becomes 2 (due to post increment i.e, ++).

Case 5: Starts with j=2; and after complete execution of j++ in case 5, j becomes 3.

Now, default takes j=3, and after execution of j++, j becomes 4.

And at return:x=4 and j=4; which gives 4+4=8.

Varooon said:   10 years ago
Default : j++; will also will be executed, Because of the Absence of "break" statement. This is the key thing to note here.

Venky said:   6 years ago
Nice, thanks for explaining.

Anukirti said:   5 years ago
How int j =1; is valid as we cannot declare any local variable inside a static method?


Post your comments here:

Your comments will be displayed after verification.