+ 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);
5 ответов
+ 2
Ja Play ....ooh. ...really smart & nice solution bro...thank u so much..😊🤗
+ 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???
+ 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???
+ 1
Ja Play ...brother .....as a beginner I have posted a little code ...pls see it & upvote ...pls😊🤗
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);
}
}