Java Basics - Control Flow and Conditionals 3

Switch Statement

Can be used instead of using "if->else if->else" statements

int someValue = 444;
String someText;

switch(someValue){
   case 123: someText = "write this text for 123.";
     break;
   case 444: someText = "write this text for 444.";  //This piece of code will execute.
     break;
   case 178: someText = "write this text for 123.";
     break;
    default : someText = "nothing here";
}
System.out.println(someText);


break --> breaks out of each case
default -->default case executes when the other cases are not true.

Tip: when you have several identical cases, you can list them together like this, or you could just list "default" and let it catch any case not covered above.

For example case 8: case 9: default: schedule = "Free!"; break;

Comments

Popular posts from this blog

Java Basics - Variable and Data Types Part 1

Java Basics - Variable and Data Types Part 2

OOP - Objects and Classes