0

Switch Statement

About this code: int day = 3; switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; } // Outputs "Wednesday" I tried to delete "break" on the second the third case, but the result is still Wednesday. Why ? You said: If no break appears, the flow of control will fall through to subsequent cases until a break is reached. What should I do to make appear Monday or Tuesday ?

24th May 2018, 2:53 PM
Fabio
2 Antworten
+ 2
The output's "Wednesday" because the variable "day" has been initialised with value '3'. To get output as : "Monday" --> set value of "day" as '1' "Tuesday" --> set value of "day" as '2' Happy Coding!
24th May 2018, 3:09 PM
Rahul George
Rahul George - avatar
0
because the lack of a break is only noticeable after a case has been executed, only then does it do everything until it encounters a break. if there is no break on the second one, that doesn't matter, it won't even execute case 2 because "day" is still 3
24th May 2018, 8:16 PM
hinanawi
hinanawi - avatar