Java Starter · free course

Free course · Lesson 2 of 5

Control Flow & Methods

In this lesson you will

  • Choose between branches with if/else
  • Repeat work with loops and move logic into methods

Java's if / else if / else and for / while loops look similar to many languages, but every condition must evaluate to a real boolean — there's no "truthy" shortcut. A method is Java's word for a function that belongs to a class.

  • for (int i = 0; i < 10; i++) { } is the classic counting loop.
  • Methods declare a return type: public static int add(int a, int b).
  • void means a method returns nothing — it just performs an action.
  • Method overloading lets you define the same method name with different parameters.

💡 Practical Skill: Structuring logic into small, well-named static methods early makes the jump to full object-oriented design (Module 4) much easier.

Worked exampleAttendance Threshold Check
Java
public class Main {    static String checkStatus(int classesAttended, int totalClasses) {        double rate = (double) classesAttended / totalClasses * 100;        if (rate >= 80) {            return "Eligible for certificate";        } else if (rate >= 60) {            return "Needs make-up session";        } else {            return "At risk — contact student";        }    }     public static void main(String[] args) {        int[] attendance = {18, 15, 20, 9, 17};        for (int i = 0; i < attendance.length; i++) {            String status = checkStatus(attendance[i], 20);            System.out.println("Student " + (i + 1) + ": " + status);        }    }}

Practice exercise

Write a method that returns 'Pass' or 'Fail' for a mark, then use a loop to print the result for five marks stored in your program.

Key takeaways

  • Conditions control which code runs; loops control how often
  • Methods give a name to one job and can be reused
  • Compare Strings with equals(), not ==
In the full program Module 2: Decisions, Loops and Methods in Java See how this topic is taught in depth, with practical activities and an assessment.

Free self-study lesson — no certificate. For the full instructor-led program, see registration options.