Java Cours

Java Conditions and Loops

Tutoriel Python 3 pour débutants.

if / else if / else

int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}

Ternary Operator

int x = 10;
String result = (x % 2 == 0) ? "even" : "odd";
System.out.println(result); // "even"

switch Statement

String day = "MONDAY";
switch (day) {
    case "SATURDAY":
    case "SUNDAY":
        System.out.println("Weekend!");
        break;
    default:
        System.out.println("Weekday");
}

switch Expression (Java 14+)

String type = switch (day) {
    case "SATURDAY", "SUNDAY" -> "Weekend";
    default -> "Weekday";
};

for Loop

for (int i = 0; i < 5; i++) {
    System.out.println("i = " + i);
}

// Enhanced for (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

while and do-while

int count = 0;
while (count < 3) {
    System.out.println("count: " + count);
    count++;
}

// do-while runs at least once
int x = 10;
do {
    System.out.println(x);
    x--;
} while (x > 0);

break and continue

for (int i = 0; i < 10; i++) {
    if (i == 5) break;    // exit loop
    if (i % 2 == 0) continue; // skip even numbers
    System.out.println(i); // prints 1, 3
}