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.
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
Dev said:
1 decade ago
Why should Case 0: will execute when switched (i) and the value of i = 1 ?
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.
JuliusAgustin said:
1 decade ago
Yeah. Why would Case 0: will execute when the value of i on switch is 1 and not 0?
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.
Sheetal said:
1 decade ago
Please give justification to the answer.
Shekar said:
1 decade ago
Then, What about case 2, 3 in execution?
Mike said:
10 years ago
Once a match is found all remaining statements are executed until a break statement is encountered.
Saba said:
8 years ago
Please explain.
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers