Conditions and loops
if, switch, for, while and the enhanced for loop.
Java
public class Main {
public static void main(String[] args) {
int marks = 76;
if (marks >= 75) {
System.out.println("Distinction");
} else if (marks >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}Output
Distinction
switch
The arrow form needs no break and cannot fall through by accident.
Java
public class Main {
public static void main(String[] args) {
int day = 6;
String type = switch (day) {
case 6, 7 -> "Weekend";
default -> "Weekday";
};
System.out.println(type);
}
}Output
Weekend
Loops
Java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.print(i + " ");
}
System.out.println();
int n = 10;
while (n > 0) {
n -= 4;
}
System.out.println(n);
int[] marks = {70, 80};
for (int m : marks) {
System.out.println(m);
}
}
}Output
1 2 3 -2 70 80