JAVA CONDITIONS
Java switch statement
switch selects one of several code blocks based on the value of a single expression. When checking many distinct options, this construct can be easier to read than a long if...else if chain.
How does switch work?
switchexpression is evaluated once.- The result is compared in order with the
casevalues. - When a match is found, the corresponding code block starts running.
breakends the entireswitchstatement.- If there is no match, the optional
defaultblock.
switch syntax
switch (išraiška) {
case reikšmė1:
// Runs the first code block
break;
case reikšmė2:
// Runs the second code block
break;
default:
// Runs when no value matches
} Each case value must be compatible with the switch expression's type and must be unique within the block.
Status code example
The program can select a message based on a task's status code:
int busenosKodas = 2;
switch (busenosKodas) {
case 1:
System.out.println("Užduotis paruošta");
break;
case 2:
System.out.println("Užduotis vykdoma");
break;
case 3:
System.out.println("Užduotis baigta");
break;
default:
System.out.println("Nežinoma būsena");
}
// Prints: Užduotis vykdoma The expression's value is 2, so the second caseruns. Upon reaching break, the program exits the switch and does not run the other options.
The break keyword
break stops the switchwhen the selected branch finishes. Without it, execution would continue into the next case block without even checking its value. This behavior is called fall-through).
Omit it only when you deliberately want the same action for several values.
The default keyword
default handles all values without a separate case:
String role = "svečias";
switch (role) {
case "administratorius":
System.out.println("Visos teisės");
break;
case "narys":
System.out.println("Nario teisės");
break;
default:
System.out.println("Tik peržiūros teisės");
}
// Prints: Tik peržiūros teisės The value “svečias” (“guest”) matches none of the casevalues, so only viewing permission is granted. When default is the last block, a following break is not required.
Multiple case labels with the same action
You can group values by allowing fall-through and writing shared code in the last branch:
char kategorija = 'B';
switch (kategorija) {
case 'A':
case 'B':
System.out.println("Prioritetinė kategorija");
break;
case 'C':
System.out.println("Standartinė kategorija");
break;
default:
System.out.println("Kategorija neatpažinta");
}Both 'A'and 'B' reach the same message, and the shared break ends the statement.
switch or else if?
switch is useful when a single expression is compared with specific values. For ranges, complex comparisons or multiple different Boolean expressions, a clearer choice is usually an if...else if chain.