-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Beginner Part2
- Introduction
- Conditional Statements
- Switch Statements
- Loops - For Loops
- Loops - While Loops
- Loops - Do-While Loops
- Loop Control - Break and Continue
- Nested Loops
- Practice Exercises
Control flow determines the order in which your code runs. By default, Java executes statements one after another. But what if you want to make decisions? What if you want to repeat something? That's where control flow comes in!
In this guide, you'll learn:
- How to make decisions with if/else
- How to choose between multiple options with switch
- How to repeat code with loops
Conditional statements let your program make decisions based on conditions.
The if statement runs code only when a condition is true.
int age = 18;
if (age >= 18) {
System.out.println("You are an adult!");
}Add an else block to run code when the condition is false.
int age = 16;
if (age >= 18) {
System.out.println("You are an adult!");
} else {
System.out.println("You are a minor!");
}Chain multiple conditions together.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}Remember these from Part 1?
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater or equal | a >= b |
<= |
Less or equal | a <= b |
Combine multiple conditions:
int age = 25;
int income = 50000;
if (age >= 18 && income >= 30000) {
System.out.println("You qualify for the loan!");
}
// OR example
boolean hasCard = false;
boolean hasCash = true;
if (hasCard || hasCash) {
System.out.println("You can make a purchase!");
}| Operator | Meaning | Example |
|---|---|---|
&& |
AND (both must be true) | a && b |
|| |
OR (at least one must be true) | a || b |
! |
NOT (reverses true/false) | !a |
A compact if-else in one line:
// Instead of:
String result;
if (age >= 18) {
result = "Adult";
} else {
result = "Minor";
}
// You can write:
String result = (age >= 18) ? "Adult" : "Minor";When you have many conditions to check, switch can be cleaner than if-else.
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println(dayName); // WednesdayGroup cases together:
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("You passed!");
break;
case 'D':
case 'F':
System.out.println("You failed.");
break;
default:
System.out.println("Invalid grade.");
}A shorter way to use switch:
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid";
};Note: The
->syntax requires Java 14 or later. Use the traditionalswitchfor older versions.
- Cleaner than long if-else chains
- Good for menus and choices
- Can be used as an expression (Java 14+)
Loops let you repeat code multiple times. The for loop is perfect when you know how many times to repeat.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5The three parts:
-
int i = 1- Start: where to begin -
i <= 5- Condition: when to stop -
i++- Update: what to do each time
for (int i = 0; i < 10; i++) {
// Code runs 10 times (i = 0,1,2,3,4,5,6,7,8,9)
}
for (int i = 10; i > 0; i--) {
// Countdown from 10 to 1
}
for (int i = 0; i <= 20; i += 2) {
// Even numbers from 0 to 20
}Loop through arrays and collections without an index:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// Output:
// Apple
// Banana
// CherryThe while loop repeats as long as a condition is true. Use it when you don't know how many times to repeat.
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++; // Don't forget this or it loops forever!
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5// For loop - when you know the count
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// While loop - when count is unknown
Scanner scanner = new Scanner(System.in);
int number;
System.out.println("Enter a positive number:");
number = scanner.nextInt();
while (number <= 0) {
System.out.println("Invalid! Enter positive:");
number = scanner.nextInt();
}
System.out.println("Thanks!");Be careful! If the condition never becomes false, the loop runs forever:
// BAD - infinite loop!
// while (true) {
// System.out.println("This runs forever!");
// }The do-while loop runs the code at least once before checking the condition.
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 5);
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5// While - might not run at all
int num = 10;
while (num < 5) {
System.out.println("This won't print");
}
// Do-While - runs at least once
do {
System.out.println("This WILL print once");
} while (num < 5);Scanner scanner = new Scanner(System.in);
String choice;
do {
System.out.println("Menu: 1. Play 2. Score 3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextLine();
switch (choice) {
case "1": System.out.println("Playing..."); break;
case "2": System.out.println("Score: 100"); break;
case "3": System.out.println("Goodbye!"); break;
default: System.out.println("Invalid choice!");
}
} while (!choice.equals("3"));for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}
// Output: 1, 2, 3, 4for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip when i is 3
}
System.out.println(i);
}
// Output: 1, 2, 4, 5 (3 is skipped)Break - Finding an item:
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
for (String name : names) {
if (name.equals("Charlie")) {
System.out.println("Found Charlie!");
break; // No need to keep searching
}
}Continue - Filtering:
// Print only even numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
System.out.println(i);
}A loop inside another loop! This is useful for patterns and grids.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
}
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
// ... and so on// Print a square of stars
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print("* ");
}
System.out.println(); // New line after each row
}
// Output:
// * * * *
// * * * *
// * * * *
// * * * * // Print 1-5 times table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.printf("%2d x %2d = %2d ", i, j, i*j);
}
System.out.println();
}Write a program that asks for a number and tells if it's even or odd.
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println("Even!");
} else {
System.out.println("Odd!");
}
}
}Convert a numeric score to a letter grade.
public class GradeCalculator {
public static void main(String[] args) {
int score = 87;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade: " + grade);
}
}Use a for loop to print numbers 1 to 10.
public class CountToTen {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}Calculate the sum of 1 to 100.
public class SumNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum); // 5050
}
}Print the 5 times table using a loop.
public class TimesTable {
public static void main(String[] args) {
int num = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}Find the largest number in an array.
public class FindMax {
public static void main(String[] args) {
int[] numbers = {5, 12, 3, 8, 99, 1};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max); // 99
}
}Print numbers 1 to 20, but:
- Print "Fizz" for multiples of 3
- Print "Buzz" for multiples of 5
- Print "FizzBuzz" for multiples of both
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}In this guide, you learned:
- ✅ How to make decisions with if, else if, and else
- ✅ How to use comparison and logical operators
- ✅ How to use the ternary operator for short conditions
- ✅ How to use switch statements for multiple choices
- ✅ How to use for loops when you know the count
- ✅ How to use while loops when you don't know the count
- ✅ How to use do-while loops for at-least-once execution
- ✅ How to control loops with break and continue
- ✅ How to use nested loops for patterns
Next Steps: Move on to Java Beginner Part 3 to learn about methods and arrays!
Great job! Keep practicing! 🎉