Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to input a switch statment in my program and i wanted a clear understanding at where can i break and continue. Its break time and i didnt understand this code; can i get an understading please? I need clear and more informed explanation. I have searched And this is what i got but has not answered my question at what point do we break or continue and again this is what i saw. I need links; (Switch Statements)
public class SwitchTrying {
public static void main(String args[]){
char grade = 'B';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid ");
}
System.out.println("You got : " + grade);
}
}
Switch statements are are like a series of if statements, evaluated in the order they appear in the code. As soon as one of the conditions evaluates true, it starts executing all of the code after it until it hits a break.
In your example, you pass in grade 'B'. It first checks case 'A'. Obviously a 'B' isn't an 'A', so it skips that section of code (which would print out 'Excellent') and checks the next condition. Next, case 'B' evaluates true because you passed in a 'B', so it will now start executing all the code it sees until it reaches a break. That means it will print out 'Well Done', then it will hit the break after that and jump out of the switch statement.
This design means that you can have multiple different conditions execute the same code, like in your example. Both a 'B' and a 'C' will print out 'Well Done' because there is no break in between them.
You need a break at the end of each case block. Otherwise, every case block after the matching one will be executed until a break is encountered.
Switch statement above works like as follows:
if grade is "A", app prints "Excellent" and breaks out from the switch statment.
If Grade is either B or C, it prints "Welldone" and breaks out from the switch statement.
If Grade is D it prints "You passed" but since there is no break, app also goes to case F (right below D) and prints "Better try again" and then breaks out.
If Grade is F, app prints "Better try again" and then breaks out.
If any other value for Grade is given, App prints "Invalid".
And finally program prints "You got: XX" .
Since Grade is hardcoded in the program, only B branch works. Try chaning it to other values to see what happens.
Cheers.
Well let me introduce you to switch statements; A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Now Look at the example below; I will use this example;
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
case value :
//Statements
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
To answer your question at what point does one break note: I have indicated it is optional, hence you can apply a break point anywhere. Now we have several rules for the switch statement.
This might help you understand it more;
Note 1: A switch statement can have an optional default case, which
must appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
Note: Not every case needs to contain a break. If no break appears,
the flow of control will fall through to subsequent cases until a
break is reached.
Note: When a break statement is reached, the switch terminates, and
the flow of control jumps to the next line following the switch
statement.
Note:The value for a case must be the same data type as the variable
in the switch and it must be a constant or a literal.When the variable
being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
And always remember: The variable used in a switch statement can only
be a byte, short, int, or char
There is a pretty good tutorial at:
Switch Tutorial
There is nothing wrong with the code you posted.
As a note, however, a grade of 'B' or 'C' will produce the same result. The lack of a break statement in the case for 'B' causes execution to fall through to the next case statement - even though the condition doesn't match. The way it's written, it's like an 'OR' statement.
A value of 'D' will print "You passed" as well as "Better try again", also because of the lack of a break statement.
Take a look at the tutorial.
Good Luck!
Related
This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed last month.
I was trying to work on Multiple Choices for my java foundations and came up with this Code.
I am have experience with switch cases and all but this is the first time, I encounter this problem!
Can someone explain me how can that argument go into those cases like in 1, 2, 3 or 4 when the number itself is different?
public static void main(String[] args) {
switch (5) {
default:
case 1:System.out.println("1");
case 2:System.out.println("2");
case 3:System.out.println("3");break;
case 4:System.out.println("4");
}
}
The Output was:-
1
2
3
There are various flavours of switch. This one is the basic switch statement, the only one that was in java since the beginning. This simple flavour 'falls through', meaning, effectively 'switch' means 'jump to the right case statement, and just start running'. In this example, there are 4 case statements and none of them match; after all, you're asking the switch statement to find the case statement that goes with '5', and there isn't one.
Ordinarily that means the entire switch statement does nothing, but, there is a default: label in this switch block, which becomes the target case statement for everything that doesn't have an explicit case, thus, this switch statement jumps to default:.
Given that the basic switch falls through, it just 'falls through' to the case 1 block and just keeps falling through. However, that break; statement at the end of the 'case 3' set of statements exits the switch block and thus 4 is never printed.
This is not something you should ever be doing.
Fall-through is unexpected. Various linter tools straight up mark off fall-through as invalid code and will stop you from publishing/pushing to save you from yourself. All case (and default) blocks should end in a break;, and if you really need the fall through, add a comment // intentional fall-through to ensure other readers realize you wanted this feature.
The more modern flavours of switch no longer fall through. Which even more highlights the need not to rely on it.
the first case that will be matched is default, then all the code up to the break; will be executed. Try to move the default case to the end, add break to each of the cases and see how the behaviour change. Anyway, you should have break present in all your cases unless you want for one value match execute code in multiple consequent cases
Try to think about the process of it.
It checks the value passed to the switch() statement which is 5, but there is no case 5, so it goes to the default case.
But there is no code in the default case, so the logic goes to the next case which is case 1, it runs the code and print it.
Since there is no break statement, the logic goes to the next case which is case 2, it runs the code and print it.
Since there is no break statement, the logic goes to the next case which is case 3, it runs the code and print it.
The logic reaches the break statement in case 3, which stops the execution of the switch statement.
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.
The following code prints out 1,2,3 , if i change int i = 3; it will print out 3. I was wondering the reason behind this. I used debugger and it seems if i = 3 it goes to case 3 and print out 3 then program terminated.I believe when i=5, it goes to default , does this mean case 1,case 2 and case 3 all belong to the default clause?
int i = 5;
switch(i){
default:
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
Edit:
This question was from a test and it asks for the output for this code. So I am trying to figure out why the output is 1,2,3, i understand break; is needed but that is not what i wanted for the answer.
i == 5 doesn't match any of your cases, so control goes to default clause.
default clause is empty, with no break statement, and it immediately falls through to the case below — case 1 in your code.
case 1 prints "1" and, as it also doesn't have a break statement, falls through to case 2, and so on.
cases 1, 2, 3 do not belong to default — what matters is their order.
If you would reorder your switch statement and would write default clause as the last one, it would print nothing.
If you don't have break at any case or default it will fall through until it find break or end of case block. So in you case since you don't have break in default it fall through all the way to the end. Without break your program will print 1,2,3 for i>3.
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):
Consider the following code
int x = 1
switch(x) {
case 1:
System.out.println("1");
case 2:
System.out.println("2");
default:
System.out.println("no value found");
}
it prints
1
2
no value found
as expected because there is no break in each case statement
my doubt is that how execution goes to each case statement if there is no break in first one
because x is not equal 2 then also its execute case 2 block
but i understood default one because without break program continue its execution and execute the default statement
This is a remnant of the C programming language. In C switch is little more than a little syntactic sugar over a goto depending on the expression value and thus execution simply jumps to the appropriate case and continues from there. The labels in between are exactly that: labels. They are jump targets but don't affect control flow otherwise and from the compiler's point of view there is nothing in a label that merits a jump elsewhere (except there is INTERCAL's COMEFROM somewhere). So you have to put an explicit break after every case where you don't want to fall through to other options.
Java more or less inherited those semantics while eschewing some of the crazier C idioms.
C# on the other hand goes a bit further by disallowing fall-through entirely on non-empty case labels.
In my opinion though, this was a bit of a design error. Fall-through by default may be much easier to implement in the compiler (because you don't have to add a goto to the end of the switch and it aligns very nicely with how things actually work underneath), but in my experience there are vastly more programming errors by accidentally using fall-through than by accidentally not using it.
The most severe design error in my eyes is including the switch statement with all its weirdness in modern languages.
For reasons that are inherited from C++, execution naturally proceeds until the end of switch or a break. There is no test against cases as they are encountered.
switch is fall through. You need to add break before each next case unless you want that.
switch (x) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("no value found");
}
It's to do with how it's compiled and optimization.
It's why a switch is preferable to a bunch of chained if statements.
From java 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
The switch statement is not like an if-then-else statement. switch statement has multiple execution path.
The Documentation states:
Control flow continues with the first statement following the switch
block. 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.
The switch statement is an abstraction of a branch table, and a branch table also has an implicit fall-through and requires an additional jump instruction to avoid it. Read this SO answer as well.
As per JLS 14.11:
The body of a switch statement is known as a switch block.
If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence.
If all these statements complete normally, or if there are no statements after the matching case label, then the entire switch statement completes normally.
It's correct behaviour. "default" doesn't mean all possible answers. It means all answers without these written in cases.
int x=1
switch(x)
{
default:
System.out.println("no value found");
case 1:
System.out.println("1");
case 2:
System.out.println("2");
}
will print
1
2
won't print
no value found
1
2
when using breaks; statements and default value there is called only one "branch" for each value
Each break statement terminates the enclosing switch statement. 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 can use if-then-else just, the overhead of testing is increases..., which is avoided in switch-case, but break is necessary for proper execution...