Java - Switch statement and curly braces - java

I have a question associated with curly braces in switch-case block
switch( conditon ) {
case val1: {
// something
}
break;
case val2: {
// something
}
break;
default:
break;
}
or something like this:
switch( conditon ) {
case val1: {
// something
break;
}
case val2: {
// something
break;
}
default:
break;
}
A I know both codes should work the same way but I think there is some irrationalities here. As the break should cause jumping out from curly braces block so theoretically second code should do smoothen like this:
1. break course jumping out of block
2. switch continues execution case val2 or default cause outside the braces there isn't any break statement.
Which version you recommend to use and Are they really working the same way?

Try this:
{
System.out.println("A");
break;
System.out.println("B");
}
You'll see
$ javac Y.java
Y.java:35: error: break outside switch or loop
break;
^
1 error
This means: you can't use it in a block, it has no effect in combination with a block.
I would not put the break outside the block, but I've never seen coding rules demanding either way (and you could put up arguments for both sides). Maybe this is because blocks aren't used very frequently to separate visibility per switch branches.

Curly braces limit the scope of variables. And have no effect on flow control other than if, for, while, switch.. blocks, except for the cases where they're optional

Related

Is a switch executing all the cases without stopping?

I'm on Java 8v60. I tried to embed a switch regarding an exception group in a catch block. Apparently, the case are recognised, but once they get into the switch, they keep going through all the possible cases. Is this a Java bug?
It looks like this:
try {
...
} catch (DateTimeParseException exc) {
...
} catch (myException exc) {
switch (exc.getEvent()) {
case EVENT_ONE :
//once EVENT_ONE gets here;
case EVENT_TWO : case EVENT_THREE :
//it keeps going everywhere;
case EVENT_FOUR :
//and so on;
default :
//and here of course too.
//but if it's not one of the above, it just appears here only
}
...
Weird, isn't it. Any idea?
No. It's not a bug. You are not implemented switch properly. It's fall through. You need to have break after each case.
For ex :
switch (exc.getEvent()) {
case EVENT_ONE :
//once EVENT_ONE gets here;
break;
case EVENT_TWO : case EVENT_THREE :
//it keeps going everywhere;
break;
case EVENT_FOUR :
//and so on;
break;
Here is the official doc for the same
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. 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 statements jump to the right value, and continue up to the end of other cases.
If you like to exit the switch statement you have to use a break (or return in some situations).
This is useful to handle situations in wich many values can be handled at the same manner:
switch (x) {
case 0:
case 1:
case 2:
System.out.println("X is smaller than 3");
break;
case 3:
System.out.println("X is 3");
case 4:
System.out.println("X is 3 or 4");
break;
}
If the case selection is also a final condition for a method you can return from it.
public String checkX(int x) {
switch (x) {
case 0:
case 1:
case 2:
return "X is smaller than 3";
case 3:
return "X is 3";
case 4:
return ("X is necessary 4");
default:
return null;
}
}
}
Its not java bug. It's your logical bug.
put break statement after each case statement to avoid fall through situation.

Boolean logic in switch case statement - Java

switch (i) {
case ("+" || "/"):
setOperator("i");
break;
}
What is the best way to do this in Java?
Of course.
Just use
if(i.equals("+") || i.equals("/")) {
setOperator("i");
}
OR if you have to use a switch statement, you can do it this way:
switch(i) {
case "+":
case "/":
setOperator("i");
break;
}
Basically, you can't really have multiple cases the way you had thought about it. It's not the same structure as an if statement, where you can do various logical operations. Java does not go through and do an if statement for each of the cases.
Instead, each time you have case("foo"), Java sees this as something called a Case Label. It is the reason that we sometimes opt to use switch statements, even though they are very primitive and sometimes not very convenient. Because we have case labels, the computer only has to do one evaluation, and it can jump to correct place and execute the right code.
Here is a quote from a website that may help you:
A switch statement, as it is most often used, has the form:
switch (expression) {
case constant-1:
statements-1
break;
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement
This has exactly the same effect as the following multiway if statement, but the switch statement can be more efficient because the computer can evaluate one expression and jump directly to the correct case, whereas in the if statement, the computer must evaluate up to N expressions before it knows which set of statements to execute:
if (expression == constant-1) { // but use .equals for String!!
statements-2
}
else if (expression == constant-2) {
statements-3
}
else
.
.
.
else if (expression == constant-N) {
statements-N
}
else {
statements-(N+1)
}
switch (i) {
case ("+"):
case ("/"):
setOperator("i");
break;
}
yes you can do as: Fall through in swith case
switch (i) {
case "+":
case "/":
setOperator(i);
break;
}

Java - object for loop with condition?

This may sound silly but I couldn't find an answer by googling it.
When using a for loop in it's simplest form I can add conditions to break the loop in the for statement. example:
for(int i=0; i<100 && condition2 && condition3; i++){
//do stuff
}
When using an object for loop like this:
for(String s:string_table){
//do stuff
}
how can i add a condition to break the loop? I'm talking about adding conditions in the for statement. I know I can add the condition inside //do stuff part and break from there.
You cannot do that you have to go by putting the if statements in the for loop.
You cannot add anything else to the () part of the "enhanced for" statement. JLS ยง 14.14.2:
The enhanced for statement has the form:
for ( FormalParameter : Expression ) Statement
The type of the Expression must be Iterable or an array type.
(The "FormalParameter" means a variable declaration.)
The break; statement is the only way:
for (String s : string_table) {
if (condition) break;
// ...
}

Jumper in Java?

Is there any syntax that allows you to jump from one line to the other?
example:
System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
//goto line2 or something like that??
No, there is no goto statement, but there are several workarounds:
do {
//do stuff
if (condition) break; //this will jump--+
//do stuff // |
} while (false); // |
// here <-----------------------------------+
and
int id = 0;
while (true) {
switch (id) {
case 0:
//do stuff
if (condition) {id = 3; break;} //jumps to case 3:
case 1:
if (condition) {id = 1; break;} //jumps to case 1:
// ...
}
}
You can achieve this in a roundabout way, for example with a switch statement:
switch (lineNum) {
case 1: System.out.println("line 1");
case 2: System.out.println("line 2");
case 3: System.out.println("line 3");
case 4: System.out.println("line 4");
}
Now you must ensure lineNum has the appropriate value.
For any backward jumps you'll need a do or while loop.
Java intentionally does not support goto. This is to encourage (force) you to build the control flow using the proper conditional constructs.
In your example, the proper method would be a while-loop:
System.out.println("line");
while (true) {
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
}
If you think about it, there is no code flow pattern that cannot be expressed without the need for goto (it may require to stray from personal ingrained habits). The only time you may want to use goto is to avoid code duplication. If you encounter such a case, restructuring the code into a separate method that can be called where needed is a much cleaner solution.
There is no goto in Java although it is a reserved keyword.
A goto is considered a bad programming construct and, as such, was left out of Java.
what exactly do you want to achieve? you could use labels as in http://geekycoder.wordpress.com/2008/06/25/tipjava-using-block-label-as-goto/, anyway using goto like statements could lead to spaghetti code

How to do a case with multiple conditions?

In the 1 month experience I've had with any programming language, I've assumed that switch case conditions would accept anything in the parenthesis as a boolean checking thingamajig, ie
these:
|| && < >
Know what I mean?
something like
char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
System.out.println ("W or w");
}
Sadly, doesn't seem to work that way. I can't have boolean checking in switch case.
Is there a way around it?
By the way, terribly sorry if I'm sounding confusing. I don't quite know the names for everything in this language yet :X
Any answers appreciated
You can achieve an OR for cases like this:
switch (someChsr) {
case 'w':
case 'W':
// some code for 'w' or 'W'
break;
case 'x': // etc
}
Cases are like a "goto" and multiple gotos can share the same line to start execution.
You can do -
switch(c) {
case 'W':
case 'w': //your code which will satisfy both cases
break;
// ....
}
Every case is normally followed by a "break;" statement to indicate where execution should terminate. If you omit the "break;", then execution will continue. You can use this to support multiple cases which should be handled the same way:
char someChar = 'w';
{
case 'W':
// no break here
case 'w':
System.out.println ("W or w");
break;
}
Switch cases are branches for alternative evaluations of a given expression. The expression is given in the switch parenthesis and can be byte, short, char, and int data types.
The body of a switch statement is known as a switch block. A statement
in the switch block can be labeled with one or more case or default
labels. The switch statement evaluates its expression, then executes
all statements that follow the matching case label.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
For an alternate to switch statement(multiple if conditions), I think the best solution will be using an enum. For example: Consider the case below:-
public enum EnumExample {
OPTION1{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the first option.");
return void;
}
},
OPTION2{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the second option.");
return void;
}
},
OPTION3{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the third option.");
return void;
};
public static final String CLASS_NAME = Indicator.class.getName();
public abstract void execute();
}
The above enum can be used in the following fashion:
EnumExample.OPTION1.execute();
Hopefully this helps you guys.

Categories

Resources