+ 1

Java - Switch Statement

public class Program { public static void main(String[] args) { int x = 4; int y = 0; switch(--x){ case 3: y+=x; case 4: y+=x; case 2: y+=x; default: y++; break; } System.out.println(y); } } The output comes to 10. My calculation was 4. X value decrements from 4 to 3 and go to the switch value 3 and x value of 3 is added to y, and y value of 3 increments by one through default. I don't see how it arrives at 10. Please help.

4th Jan 2020, 5:53 PM
Han Lee
Han Lee - avatar
3 Respostas
+ 11
y=3 (after case 3) y=6 (after case 4) y=9 (after case 2) y=10 (after default case) "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached." This is known as fall through, you can read the same in java switch lesson using below link: https://www.sololearn.com/learn/Java/2145/?ref=app
4th Jan 2020, 6:02 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 3
switch is first check for the matching case, if found, then executes corresponding statements. If there is no break falthrough happens until a break encounters.. So there is no break after a case then a falthrough happens that means it's executes remaining proceeding cases also including default also if no break statement found. So Here, Case 3 matched y+=x; y=3 y+=x; y=6; y+=x; y=9; y++; y=10; break; //found so comes out switch. So answer is 10
4th Jan 2020, 6:11 PM
Jayakrishna 🇮🇳