Why the following code gives 4 as output...pls explain...I m a veryyy begginer....!?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the following code gives 4 as output...pls explain...I m a veryyy begginer....!??

public class Program { public static void main(String[] args) { int a = 2; int b = 0; switch (a){ case (2): ++b; case (3): ++b; case (7): ++b; case(1): ++b; } System.out.println(b);

7th May 2020, 3:13 PM
kristidhar pandit
kristidhar pandit - avatar
5 Answers
+ 2
Ja Play ....ooh. ...really smart & nice solution bro...thank u so much..😊🤗
7th May 2020, 4:28 PM
kristidhar pandit
kristidhar pandit - avatar
+ 1
Ya but ....as the cases are arranged randomly ....so my confusion is that... is the fall of control depends on arrangements like case(1) before case(2) ...or...when it gets it match ..it falls randomly???
7th May 2020, 3:29 PM
kristidhar pandit
kristidhar pandit - avatar
+ 1
Ja Play.. Ya but ....as the cases are arranged randomly ....so my confusion is that... is the fall of control depends on arrangements like case(1) before case(2) ...or...when it gets it match ..it falls randomly???
7th May 2020, 3:33 PM
kristidhar pandit
kristidhar pandit - avatar
+ 1
Ja Play ...brother .....as a beginner I have posted a little code ...pls see it & upvote ...pls😊🤗
7th May 2020, 4:31 PM
kristidhar pandit
kristidhar pandit - avatar
0
Because the break statement isn't used, so once a case is valid it will run all cases after that. In order to get 1 in output you need to use 'break'. For example: public class Program { public static void main(String[] args) { int a = 2; int b = 0; switch (a){ case (2): ++b; break; case (3): ++b; break; case (7): ++b; break; case(1): ++b; break; } System.out.println(b); } }
7th May 2020, 3:22 PM
Raj Chhatrala
Raj Chhatrala - avatar