Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.17)

17. 

What will be the output of the program?

public class Test 
{  
    public static void main(String args[]) 
    { 
        int i = 1, j = 0; 
        switch(i) 
        { 
            case 2: j += 6; 
            case 4: j += 1; 
            default: j += 2; 
            case 0: j += 4; 
        } 
        System.out.println("j = " + j); 
    } 
}

[A]. j = 0
[B]. j = 2
[C]. j = 4
[D]. j = 6

Answer: Option D

Explanation:

Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. The result is j = 6.


Apurva said: (Jul 24, 2010)  
Well actually you find contradictory explanation in the above ques and ques no 4 in the above set... The two contradict in the usage of default

Dev said: (Feb 2, 2013)  
Why should Case 0: will execute when switched (i) and the value of i = 1 ?

Vikas Yadav said: (Dec 18, 2013)  
Simple solution would be that it i=1 so it will go to first case statement which is case 2: j+=6;

Therefore ans is 6 then it will not go to default as it finds the answer.

Juliusagustin said: (Jul 19, 2014)  
Yeah. Why would Case 0: will execute when the value of i on switch is 1 and not 0?

Sanglc said: (Aug 7, 2014)  
I don't think it's right result. It must be j=2.

Although there are no break statements, but program won't go to case 0. because when it compares i=0, it will abort.

Sheetal said: (Nov 19, 2014)  
Please give justification to the answer.

Shekar said: (Dec 11, 2014)  
Then, What about case 2, 3 in execution?

Mike said: (Oct 1, 2015)  
Once a match is found all remaining statements are executed until a break statement is encountered.

Saba said: (Jul 4, 2017)  
Please explain.

Pritam said: (Nov 4, 2017)  
Ans is correct because 1st one fetch default j=2 and then access last case of switch. Because there have no break statement so ans is now 6.

Naveen said: (Jan 11, 2020)  
The answer is 6.

How Switch works;

1. First of all, the order of default and case statements is not restricted. They can appear in any order.
2. First, JVM looks for the matching case and executes if found. If no case found, goes to default.
Hence, It checks the cases, no case found, hence executes default first. Since there is no break, it executes the statements followed after.

Note: Default is always matching.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.