28/08/2025
By Imran M
By Imran M
In our first post, we brought objects to life. We gave them state (like a Dog‘s name and breed) and simple behaviors (like bark()). But so far, our objects are a bit… robotic. They always do the exact same thing. A bark() method that only ever prints “Woof! Woof!” isn’t very useful for a Chihuahua or a Great Dane.
To write truly powerful and flexible programs, our objects need to:
Perform actions that are unique to their current state.
Make decisions.
Repeat actions without redundant code.
This is where Methods and Control Flow become the beating heart of your Java applications. They are the logic and the rules that transform static blueprints into intelligent, interactive, and dynamic programs.
If a Class is a noun (a Car, a User, a BankAccount), then a Method is a verb. It’s the action the object can perform: car.drive(), user.login(), account.withdraw().
Control Flow is the logic that governs when and how those actions are performed. It’s the “if this, then that” and the “do this 10 times” of your code. It’s the brain that makes decisions.
Together, they form the engine of your program.
The simple void bark() method from last time has a limited vocabulary. To make it smarter, we need to teach it to accept input and give back output.
Parameters (Input): Variables you pass into a method to influence its behavior. Think of them as instructions.
Return Value (Output): The result that the method gives back after it’s done its work.
Let’s supercharge our Dog class.
public class Dog { String name; int age; // Method with a parameter to customize the action void bark(int numberOfBarks) { for (int i = 0; i < numberOfBarks; i++) { System.out.println("Woof!"); } } // Method with a return value int getHumanAge() { // A simple calculation: 1 dog year ≈ 7 human years return age * 7; } // Method with BOTH a parameter and a return value boolean isOlderThan(int otherAge) { return age > otherAge; } }
How to use these new powerful methods:
public static void main(String[] args) { Dog myDog = new Dog(); myDog.name = "Fido"; myDog.age = 5; myDog.bark(3); // Input: instruct it to bark 3 times. // Output: // Woof! // Woof! // Woof! int humanAge = myDog.getHumanAge(); // Gets output (return value) System.out.println(humanAge); // Output: 35 boolean isOlder = myDog.isOlderThan(3); // Input 3, gets a boolean output if (isOlder) { System.out.println("Fido is older!"); } }
if, else if, elseA program that only runs in a straight line is brittle. Real-world applications need to branch based on conditions. This is done with conditional statements.
public class LoginService { void loginUser(String username, String password) { // Check if the username is even provided (basic validation) if (username == null || username.isBlank()) { System.out.println("Username cannot be empty!"); return; // Exit the method early } else if (password.length() < 8) { System.out.println("Password is too short!"); return; } else if (isValidUser(username, password)) { // Assume this method exists System.out.println("Login successful! Welcome " + username); } else { System.out.println("Invalid username or password!"); } } // ... other code ... }
The if and else if statements check conditions in order. The first condition that is true has its code block executed. The else block is a catch-all if none of the previous conditions were met.
What if you need to print numbers 1 to 10? You wouldn’t write ten println statements. You use a loop. Loops automate repetitive tasks.
The for Loop: Use it when you know exactly how many times you want to repeat an action.
// Count from 1 to 10 for (int i = 1; i <= 10; i++) { System.out.println("Count: " + i); } // Iterate through an array (a collection of items) String[] fruits = {"Apple", "Banana", "Orange"}; for (int i = 0; i < fruits.length; i++) { System.out.println("Fruit: " + fruits[i]); }
The while Loop: Use it when you want to repeat an action until a certain condition is met, but you don’t know how many iterations it will take.
import java.util.Scanner; public class GuessingGame { public void playGame() { Scanner scanner = new Scanner(System.in); int secretNumber = 7; int guess = 0; // Keep looping as long as the guess is wrong while (guess != secretNumber) { System.out.print("Guess a number between 1 and 10: "); guess = scanner.nextInt(); if (guess != secretNumber) { System.out.println("Nope! Try again."); } } System.out.println("You got it! The number was " + secretNumber); scanner.close(); } }
Memory Hook: “Methods are verbs.” Name your methods after actions. calculateTotal(), sendEmail(), validateInput(). If you can’t think of a verb for what your method does, it might not be a well-defined method.
“Loops are your code’s copy-paste.” They do the tedious, repetitive work for you.
Recall Trigger: This snippet combines everything: methods with parameters/returns, conditionals, and a loop.
public class Calculator { // A method with parameters and a return value public double calculateAverage(int[] numbers) { if (numbers == null || numbers.length == 0) { // Decision: if array is empty return 0.0; // Return early to avoid errors } int sum = 0; for (int num : numbers) { // Loop: iterate through all numbers sum += num; // Add each number to the sum } return (double) sum / numbers.length; // Return the calculated result } }
You are now writing the core logic for virtually any application.
E-commerce: calculateTotal(cartItems) would loop through the items, sum their prices, and apply discount rules (using if statements).
User Systems: validatePassword(password) would use conditionals to check length, special characters, etc.
Games: A game loop (while (gameIsRunning)) continuously checks for player input, updates game state, and renders graphics.
Test your understanding before we move on to the superpower of OOP.
90% – Expert: You can write a method that takes an array of integers and returns the highest value. You can explain the difference between a for loop and a while loop and when to use each.
75% – Getting It: You look at the calculateAverage method and understand the flow: the if check, the purpose of the for loop, and the final calculation. You can write a simple method that takes a parameter.
<60% – Review Needed: The syntax of for (int i = 0; i < 10; i++) still looks confusing. Rewrite the loop examples by hand. Practice writing methods that take different parameters (e.g., greetUser(String name)) and return different types.
Next Up: You’ve built the foundation and the engine. Now it’s time for Java’s superpower. In the next post, we’ll dive into the core principles of Object-Oriented Programming: Inheritance, Polymorphism, and Encapsulation. This is where Java truly shines.
Note: This is the second post in a five-part series. Found this helpful? Share it with a fellow learner! The next post on Core OOP Principles is coming soon.