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.

Shreyas singh said:   9 years ago
I think it's been initiating from case 4, so on case 4 j=2, case 5 j=3, default case j=4, so now we have value of x as 4, at the end its been said to add this two, so x+j =8.
(1)

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

Venkatesh said:   6 years ago
The default case value of j=3.
Once it comes out of switch case post-increment of j is there (i.e. Value of j=3 but j++ is there so j becomes 4.
So finally value will be x+j = 4+4 = 8.
So the answer will be 8.
(2)

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.