if (condition) {
// Code executes if condition is true
}
if (condition) {
// Executes if true
} else {
// Executes if false
}
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition2 is true
} else {
// Executes if none of the above conditions are true
}
result = (condition) ? valueIfTrue : valueIfFalse;
Used for selecting one of many code blocks to execute.
switch (expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
default:
// Default code block
}
expression
must be of type byte
, short
, char
, int
, String
, or enum
.break
prevents fall-through.default
is optional.while (condition) {
// Executes while condition is true
}
do {
// Executes at least once
} while (condition);
for (initialization; condition; update) {
// Executes until condition is false
}
for (type var : arrayOrCollection) {
// Iterates through elements
}
for (int i = 0; i < 10; i++) {
if (i == 5) break;
}
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
// Skips even numbers
}
return; // For void methods
return value; // For methods with return types
Used with break
and continue
to affect outer loops.
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) break outer;
}
}