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 2 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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers