Unable to understand how it works case MONDAY : FRIDAY: - java

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.

Related

Which combination of switch and if/else is faster and why?

I have two sets of conditions. One has two possible values and the other has more (in this example I wrote 3 cases but there could be up to 8). Which code runs faster and is less error prompt (more accurate)?
code a)
if (letter.equals(a)) {
switch (number) {
case 1:
.........
case 2:
.........
case 3:
.........
}
} else if (letter.equals(b)) {
switch (number) {
case 1:
.........
case 2:
.........
case 3:
.........
}
}
code b)
switch (number) {
case 1:
if (letter.equals(a)) {
.........
} else if (letter.equals(b)) {
.........
}
case 2:
if (letter.equals(a)) {
.........
} else if (letter.equals(b)) {
.........
}
case 3:
if (letter.equals(a)) {
.........
} else if (letter.equals(b)) {
.........
}
}
Please tell me if you think there is a better option other than these two. (I could also create a parameter that gets both letter and number and create 6 cases using that.)
Thank you in advance!
Which code runs faster and is less error prompt (more accurate)?
Answer: In this specific case performance is not the issue. Because no matter how you are going to use this actual execution numbers are same. But you can improve the code readability and making it less errorprone.
Instead of worrying about performance, start with SOLID principle. Why don't you just break this big method into some smaller method which has a concrete responsibility. It will make code more beautiful and less error prone. For example:
Methods:
void processA(int number){
switch (number) {
case 1:
.........
case 2:
.........
case 3:
.........
}
}
void processB(int number){
switch (number) {
case 1:
.........
case 2:
.........
case 3:
.........
}
}
///
now from the main method you could simply call:
if (letter.equals(a)) {
// call the method which will process A
processA(number);
} else if (letter.equals(b)) {
// call the method which will process A
processB(number);
}
This is an example of a micro-optimisation that probably has no effect on your code, so 'which is faster' doesn't really matter here.
If you want to find out which of a particular combination of cases in your codebase then you probably want to use a benchmarking tool like JMH to figure out which is more appropriate for you. But unless this code is on the critical path it won't make a difference.
Code needs to be:
Correct
Readable
Performant
It's much better to focus on 1 & 2 than the last.
In this particular case, a switch-over-numbers is probably faster for the JVM under the covers, while switch-over-expressions will naturally involve more jumping around in the branches. I would therefore naively expect switch-over-int-followed-by-if will marginally edge out the other way around, but without proof this would be a hunch and not something to rely on. It's also quite likely that whatever benchmark is written there will be some kind of flaws, such that the JVM is automatically promoting the optimal test case combination to the first test, in which case it won't tell you what you think it is doing.
Ultimately, write it for readability/maintainability rather than performance, until you can prove this is on the hot loop, and then measure it explicitly.
There is another option:
switch (String.format("%1s%1d", letter, number) {
case "a1":
...
case "b1":
...
case "a2"
...
case "b2":
...
case "a3":
...
case "b3":
...
}
Better? Maybe, maybe not. But it is an alternative...

Java switch runs all cases if no break

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.

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.

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):

Why "switch" in java does check more cases than required? [duplicate]

This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed 9 years ago.
I already searched in stackoverflow for reasons concerning the question, why switch does not break after having found a matching case.
For example, I have written some code which simulates a dice. For every throw, I count up for statistical reasons (one, ... = int).
switch (actualThrow) {
case (1): one++;
case (2): two++;
case (3): three++;
case (4): four++;
case (5): five++;
case (6): six++;
}
I DO know, that case(3)-case(6) will be checked, if my throw was a 3 (Why do we need break after case statements?) and it will be prevented by inserting break;, but I want to understand, why obviously the following cases seem to be checked, but execute, although the condition is not fulfilled.
Imagine this scenario:
switch(trafficLight.state) {
case GREEN:
car.drive();
break;
case YELLOW:
car.drive();
break;
case RED:
car.stop();
break;
}
Seems kinda wasteful since GREEN and YELLOW both do the same thing. Java lets us consolidate so that multiple conditions take the same action:
switch(trafficLight.state) {
case GREEN:
case YELLOW:
// Now both GREEN and YELLOW will use this code
car.drive();
break;
case RED:
car.stop();
break;
}
Less code, same effect. That's all. That's the simple case mind you, there are other ways to use this that are less obvious and more prone to abuse.
When parsing through a switch-case statement, each case is simply a label. If anything matches a case then it will just go through until it either finds a break or the end of the statement (a }).
It is similar to the Java opcode (assembly code essentially). You use labels to jump to. Besides that, they don't really serve a purpose in the code.

Categories