Java switch runs all cases if no break - java

I'm confused about this example. if break is deleted then both Today is Saturday and Today is Sunday will be print. I need to know why this happends?
int day = 4;
switch (day) {
case 4:
System.out.println("Today is Saturday");
// break;
case 7:
System.out.println("Today is Sunday");
// break;
}
P.S: to those who are surprised why i asked such a simple question:
Its been a while i am learning Kotlin, that does not need to add break in when expression, so it made me confused when i was working on a java project that needs a switch statement

Your question is probably a duplicate of something else, but the reason is that case statement within a Java switch by default will flow onto the next case statement unless a break be explicitly mentioned. To better understand why the case statements behave this way, an example would make this clear. Let's say that you wanted the same logic to happen for Monday, Tuesday, and Wednesday. Then, you could use the following:
switch (day) {
case 1:
case 2:
case 3:
System.out.println("Today is Monday, Tuesday, or Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 7:
System.out.println("Today is Sunday");
break;
}

Break statement: Break statement is used to terminate the loop. When a break statement is encountered inside a loop, the loop is
immediately terminated.
Therefore, when we use the break statement inside the switch statement, it terminates the loop at that case, and the program control resumes at the next statement following the loop.
Answer to your Question: When the break statement is not used, the control of the program flows through each and every case until either it reaches the end of the switch block or a break statement is encountered.

Related

Unable to understand how it works case MONDAY : FRIDAY:

import java.time.LocalDate;
import static java.time.DayOfWeek.*;
public class Test
{
public static void main(String[] args)
{
var today=LocalDate.now().with(WEDNESDAY).getDayOfWeek();
switch(today)
{
case SUNDAY:
case SATURDAY:
System.out.println("Enjoy");
break;
case MONDAY : FRIDAY:
System.out.println("Boaring");
default:
System.out.println("QuestionMark");
}
}
}
How it is working. any one can you please help. Especially this line eating my mind :
case MONDAY : FRIDAY:
This looks like a nasty case of syntax abuse. In this particular case, case MONDAY: does what I think you expect.
However, the FRIDAY: has nothing at all to do with the switch block. It's a Java label attached to the following println statement, and since it's never referred to, it simply has no meaning other than to be seriously confusing.
Note: Never use labels. There are much clearer ways to express your ideas.
I think that chrylis has already nicely explained how your code works. As a little more background: Programming languages exist that accept a range of values as case label in a switch-like statement. However, in Java and other languages with C-like switch statements you need to specify each case individually, like this:
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
System.out.println("Boaring");
break;
You were also missing the break statement that I think was intended after printing Boaring (or the case would “fall through” to the next case and additionally print QuestionMark).
Java 12 has some improvements of the switch statement syntax. See for example the edit in this answer by YCF_L.

How switch works when a case has not been selected

I saw this code in the OCA Java 8 exam study guide which confused me.
int dayOfWeek = 5;
switch(dayOfWeek) {
case 0:
System.out.println("Sunday");
default:
System.out.println("Weekday");
case 6:
System.out.println("Saturday");
break;
}
The book says it prints Weekday and Saturday.
Why is this?
I thought the case had to be found to get selected since it is 5 is is not selected so nothing should happen.
As no case matches value of dayOfWeek, the default case is executed: printing "Weekday"
As the default case has no break, the next case that follows it is also executed, until it reaches end of switch or a break: printing "Saturday"
Simple: because you "fall" through cases. If you want to not fall through, you have to use break.
So the default is really that you execute all cases following the first match - until you hit the first break statement.
You can mention the cases for which you want to explicitly do something.
Otherwise, for all the remaining cases they will be handled in default.
Also, check the related Must the "default" case come last in a switch? for more explanation.
And as others have also pointed here, if you don't put break then it will go through all the remaining cases too without fail till it encounters a break.

Java calling a method in a switch

so I'm using a getRangedInt method to figure out the user's birth month and date, as well as a Scanner for user input. If they pick February (the prompt asks the user for their birth month number, so 1-12), then I need to change the month's max days to 28 (and so on for the other months with 30 days). I'm trying to use a switch to categorize the months, but when the program is run it simply skips over and the method is never called. The method itself works fine with other examples. What am I missing?
switch (daysInMonth)
{
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":
int birthDay = getRangedInt(input,"Enter your birth day: ",1,31);
break;
case "2":
birthDay = getRangedInt(input,"Enter your birth day: ",1,28);
break;
case "4":
case "6":
case "9":
case "11":
birthDay = getRangedInt(input,"Enter your birth day: ",1,30);
}
If you are reading daysInMonth as an integer then all the test cases will
be false because you are checking for a String value, case "1" checks for a
string "1", while case 1: will check for an integer.
Declare birthDay prior to entering the switch statement. The idea is that you want this value to be set by the time you visit one (and only one) case.
Depending on your definition of daysInMonth you might end up in an unhandled default case or not. You should think about how to define and constrain the switch controlling variable (perhaps with an enum) so you cannot have a default case.
Make sure that daysInMonth is String, and that the .equals() the case is doing does what you expect. I'm not sure what the compile-time errors mismatches like this will raise, but certainly a good IDE will warn you.
Your levels of abstraction are wrong.
You should not call getRangedInt() within a switch. Instead you should have a method called getNumberOfDays() which takes an input that selects a month (which could be a string like "January", "February", or an int, or an enum). That second method can use a switch in it; but you should not switch anywhere else. Reasoning: the knowledge about how many there are in a month should be ONLY in one place. In your solution, you need the very same switch in every place that will be dealing "days per month". Leading to code duplication, which should be avoided at all cost.
Then you call your method getRangedInt() using the return value of that other method.

Strange behavior of Switch Case statement in Java [duplicate]

This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed 7 years ago.
I understand that Java switch case are designed this way but why is this behavior in Java
int x = 1;
switch(x){
case 1: System.out.println(1);
case 2: System.out.println(2);
case 3: System.out.println(3);
default: System.out.println("default");
}
output : 1
2
3
default
My question is why case 2 and 3 are executed? I know I omitted break statement
but x was never 2 or 3 but case 2 and case 3 still executes?
There is no break statement so all case are executed
Use break statements
switch(x){
case 1: System.out.println(1);break;
case 2: System.out.println(2);break;
case 3: System.out.println(3);break;
default: System.out.println("default");
}
I know I omitted break statement but x was never 2 or 3 but case 2 and
case 3 still executes?
Straight from the doc :
The break statements are necessary because without them, statements in
switch blocks fall through: All statements after the matching case
label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.
You need to add break statement for each case. As there is no break statement all cases are getting executed.
You are missing the Break statement.
switch(x){
case 1: System.out.println(1);
break;
case 2: System.out.println(2);
break;
case 3: System.out.println(3);
break;
default: System.out.println("default");
}
Check the The switch Statement
The break statements are necessary because without them, statements in
switch blocks fall through: All statements after the matching case
label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.

Can I use switch case in Java instead of IF, if I need several cases to be evaluated

I have a primitive question but I can't actually recall the answer.
What if I use Switch Cases instead of IF\ELSE IF. Will all cases get evaluated or break will break out of the whole switch cases and return the first satisfied condition only.
In other words, what if I want to check if someone has a car, bike and plane. And in my particular case someone has all of them would switch return all three as true or it will return the first case only and ignore the rest because of the break?
Sorry for inconvenience.
Thank you
From the Official Java Tutorials :
Each break statement terminates the enclosing switch statement.
In your particular case, if someone has a car, bike or a plane, you should construct more complex if\else statement.
But if you still prefer to use switch, you can do the following:
switch (possession)
{
case CAR:
case BIKE:
case PLANE:
doSomething();
break;
}
It will break out at the first matching. the best thing to do in your case is using logical operators in if statements.
if (hasCar && hasBike && hasPlane)
{
...
}
The break terminates the switch-statement.
Besides, switch evaluates a single variable, your case sounds a bit more complex to me.
certainly break will break the switch-case flow after encountering first break statementif no break is found then it will start the execution of all statement starting from first matching case,you can implement the logic inside case.and one thing more switch case is little bit faster than if-else
please see Why switch is faster than if
With switch the first case it finds a match runs and then all the following cases regardless of matching or not, provided you don't use break. By using break,only the actual match case runs and it is almost always only one. Therefore I do not regard in your problem using switch as a good approach, since you can handle it better with if-else.
Perhaps you would need to rewrite a new style of Data Structure to confirm this. The easyest way that I think is with a Boolean Array (bool[]);
Continuing with your example if you has the
Owner Class
, with
bool bike, bool car, bool motocycle... properties, witch you can write a
public bool[] ownArray()
function, that can be evaluated.
I hope this helps.
myEnum = 3;
...
switch (myEnum) {
case 1: System.out.println("This will not print"); break;
case 2: System.out.println("This will not print"); break;
case 3: System.out.println("This will print!"); //no break!
case 4: System.out.println("So will this, because there wasn't a break"); break;
case 5: System.out.println("But this won't, there was a break");
}
Switch-case in java could evaluate one case at a time. The moment it gets into one of the case, it would keep on executing the next statements (no matter, if those statement were part of other case ); until it hit a break;
In nutshell, A switch statement gives you the option to test for a range of values for your variables. They can be used instead of long, complex if … else if statements. The structure of the switch statement is this:
switch ( variable_to_test ) {
case value1: code_here1;
break;
case value2: code_here2;
case value3: code_here3;
break;
default:
values_not_caught_above;
}
In the above example if value2 is satifies, it will execute code_here2 and code_here3 as well (because there is no break statement)
Sadly, you can't test for a range of values after case, just the one value. So you can't do this:
case (user <= 18):

Categories