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.

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

Ishrat said:   1 decade ago
Please someone explain this problem how 8 comes ?

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

Srikanth said:   1 decade ago
@Aashish, thank you.


Post your comments here:

Your comments will be displayed after verification.