MyMisPal
← Java lessons
Lesson 3 of 9

Conditions and switch

JAVA · inside main
int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}
Output
B

The condition goes in ( ) and the code in { }. Java's logical operators are && (and), || (or) and ! (not).

JAVA · inside main
String dept = "IT";
switch (dept) {
    case "IT" -> System.out.println("Floor 3");
    case "HR" -> System.out.println("Floor 1");
    default -> System.out.println("Ask reception");
}
Output
Floor 3
Watch outCompare strings with .equals(), not ==. == checks whether they are the same object in memory, not whether the text matches.
JAVA · inside main
String a = "MIS";
String b = new String("MIS");
System.out.println(a == b);
System.out.println(a.equals(b));
Output
false
true
Same idea in both languages
Python
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
Java
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
}
Spotted a mistake on this page, or have an idea to improve the site?