Operators and Control Flow
if and else work as you'd expect from any C-family language — a condition in parentheses, followed by a block.
Main.java
Try it yourself →public class Main {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
}
}Output
7 is odd
for and while
A classic for loop declares an index, a condition, and an increment all in its header. while just repeats as long as its condition holds, with no built-in index at all.
Main.java
Try it yourself →public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println("i = " + i);
}
int count = 0;
while (count < 3) {
System.out.println("count = " + count);
count++;
}
}
}Output
i = 0 i = 1 i = 2 count = 0 count = 1 count = 2
switch
switch compares a value against a series of constant cases, falling through to the next case unless you break. default catches anything not matched above it.
Main.java
Try it yourself →public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Unknown");
}
}
}Output
Wednesday
Next: methods — defining methods, parameters, return types, and method overloading.
Practice exercise
Set a variable score of type int to 73. Print "pass" if score is 60 or above, otherwise print "fail".