Java Programming - Flow Control - Discussion
Discussion Forum : 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);
}
}
Answer: Option
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.
Discussion:
11 comments Page 1 of 2.
Naveen said:
6 years ago
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.
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.
Vikas Yadav said:
1 decade ago
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.
Therefore ans is 6 then it will not go to default as it finds the answer.
Sanglc said:
1 decade ago
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.
Although there are no break statements, but program won't go to case 0. because when it compares i=0, it will abort.
Apurva said:
2 decades ago
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
Pritam said:
8 years ago
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.
Mike said:
10 years ago
Once a match is found all remaining statements are executed until a break statement is encountered.
JuliusAgustin said:
1 decade ago
Yeah. Why would Case 0: will execute when the value of i on switch is 1 and not 0?
Dev said:
1 decade ago
Why should Case 0: will execute when switched (i) and the value of i = 1 ?
Sheetal said:
1 decade ago
Please give justification to the answer.
Shekar said:
1 decade ago
Then, What about case 2, 3 in execution?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers