Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created April 24, 2022 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablohdzvizcarra/3f6698f9e3b10694694829ff411c0aa1 to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/3f6698f9e3b10694694829ff411c0aa1 to your computer and use it in GitHub Desktop.
diferents ways to execute switch statement in Java
package jvm.pablohdz.restapidesignpatterns;
public class TestSwitchStatement {
public void classicVersion(int number) {
switch (number) {
case 1:
callMethod("one");
break;
case 2:
callMethod("two");
break;
default:
callMethod("many");
break;
}
}
public void classicVersion2(int number) {
switch (number) {
case 1:
case 2:
callMethod("few");
break;
default:
callMethod("many");
break;
}
}
public void arrowVersion(int number){
switch (number) {
case 1 -> callMethod("one");
case 2 -> callMethod("two");
default -> callMethod("many");
}
}
public void arrowVersionTwo(int number){
switch (number) {
case 1 -> {
var str = "one";
callMethod(str);
}
case 2 -> {
var str = "two";
callMethod(str);
}
default -> {
var str = "many";
callMethod(str);
}
}
}
public void arrowVersionThree(int number){
var string = switch (number) {
case 1 -> "one";
case 2 -> "two";
default -> "many";
};
callMethod(string);
}
public enum Count {
ONE, TWO, MANY
}
public void arrowVersionFour(Count count) {
var string = switch (count) {
case ONE -> "one";
case TWO -> "two";
case MANY -> "many";
};
callMethod(string);
}
public void arrowVersionFive(int number) {
switch (number) {
case 1 -> callMethod("one");
case 2 -> callMethod("two");
default -> callMethod("many");
}
}
public void arrowVersionSix(int number) {
var string = switch (number) {
case 1, 2 -> "fex";
default -> "many";
};
}
public void arrowVersionSeven(Object object) {
switch (object) {
case String str -> callMethod(str);
case Number i -> callMethod(i.toString());
default -> throw new IllegalStateException("Unexpected value: " + object);
};
}
private void callMethod(String one) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment