Java Basics: Your First Programs
Decisions and Loops
In this lesson you will
- Choose between paths with if, else if, else and switch
- Combine conditions with &&, || and !
- Repeat code with for, enhanced for, while and do-while
Introduction
Programs become useful when they can decide and repeat. This lesson covers both. If you know another language, the ideas will be familiar, and only the exact spelling differs.
Comparisons and logic
Comparison operators give a boolean: ==, !=, <, >, <=, >=. Combine them with && (and), || (or) and ! (not).
Java
public class Main {
public static void main(String[] args) {
int age = 15;
System.out.println(age >= 12);
System.out.println(age == 15);
System.out.println(age > 12 && age < 18);
System.out.println(age < 5 || age > 65);
System.out.println(!(age > 12));
}
}true
true
true
false
falseA single = stores a value. A double == compares. (For text, never use ==, as the strings lesson explains.)
if, else if, else
Java
public class Main {
public static void main(String[] args) {
int temperature = 28;
if (temperature > 30) {
System.out.println("Hot");
} else if (temperature > 20) {
System.out.println("Warm");
} else {
System.out.println("Cool");
}
}
}WarmThe condition goes in round brackets, and the code in curly brackets. Java checks from the top and runs the first branch whose condition is true. Unlike Python, indentation is not required: the braces matter. Still, indent consistently, because it is how humans read the code.
Quick quiz
Which operator means 'and' in Java conditions?
The ternary operator
A compact if-else that produces a value: condition ? valueIfTrue : valueIfFalse.
Java
public class Main {
public static void main(String[] args) {
int score = 72;
String result = score >= 50 ? "pass" : "fail";
System.out.println(result);
}
}passswitch
When one value is compared to many options, switch is tidier. Modern Java (14 and newer) has an arrow form that is shorter and avoids the old "fall through" bug.
Java
public class Main {
public static void main(String[] args) {
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 6, 7 -> "Weekend";
default -> "Another day";
};
System.out.println(name);
}
}Wednesdayswitch here is an expression that produces a value, and default handles everything else. Several values can share one case, like case 6, 7.
for loops
A for loop has three parts in its brackets: where to start, when to keep going, and what to do after each round.
Java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Round " + i);
}
}
}Round 1
Round 2
Round 3
Round 4
Round 5Read for (int i = 1; i <= 5; i++) as: start with i = 1, continue while i <= 5, and add 1 to i after each round.
while and do-while
while checks the condition before each round. do-while checks after, so it always runs at least once.
Java
public class Main {
public static void main(String[] args) {
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Liftoff!");
int n = 10;
do {
System.out.println("n is " + n);
n++;
} while (n < 10);
}
}3
2
1
Liftoff!
n is 10The do-while body ran once even though n < 10 was false from the start. If nothing in a while loop ever changes the condition, it runs forever, which is an infinite loop.
break and continue
break leaves the loop. continue skips to the next round.
Java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
if (i > 7) {
break;
}
System.out.println(i);
}
}
}1
3
5
7Nested loops
A loop inside a loop. The inner loop runs completely for each round of the outer one.
Java
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(row * col + "\t");
}
System.out.println();
}
}
}1 2 3 4
2 4 6 8
3 6 9 12 Quick quiz
How is do-while different from while?
FizzBuzz
A classic exercise combining everything: for numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, otherwise the number.
Java
public class Main {
public static void main(String[] args) {
for (int n = 1; n <= 15; n++) {
if (n % 15 == 0) {
System.out.println("FizzBuzz");
} else if (n % 3 == 0) {
System.out.println("Fizz");
} else if (n % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(n);
}
}
}
}1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTry it yourself
On your computer, write a program that uses a loop to add up all the numbers from 1 to 100 and prints 5050. Then change it to add only the even numbers, which gives 2550.
Summary
- Comparisons give
boolean. Combine with&&,||and!. if/else if/elsechoose a branch.switchwith arrows picks among many values.for,whileanddo-whilerepeat code.breakleaves a loop andcontinueskips a round.- Braces mark blocks in Java. Indentation is for readers, not for the compiler.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading