Lesson 6 • Intermediate

    Java Methods

    Right now, all your code lives inside main(). That works for small programs, but imagine a 500-line main() method — impossible to read, debug, or reuse! Methods let you split your code into small, named, reusable pieces. Think of them like recipe cards: each method does one thing, and you call it by name whenever you need it.

    What You'll Learn

    • ✅ What methods are and why every Java program needs them
    • ✅ How to create a method — the complete syntax explained piece by piece
    • ✅ Parameters — passing data into a method
    • ✅ Return values — getting results back from a method
    • void methods vs methods that return a value
    • ✅ Method overloading — same name, different parameters
    • ✅ Pass-by-value — how Java handles arguments (this trips up many beginners!)
    • ✅ Best practices for writing clean, maintainable methods

    💡 Real-World Analogy: Recipe Cards

    A method is like a recipe card. It has a name ("Chocolate Cake"), ingredients (parameters — flour, sugar, eggs), instructions (the method body), and a result (return value — a finished cake). You write the recipe once, and you can follow it any time without memorizing the steps — just call the recipe by name.

    1️⃣ Creating Your First Method

    Every method has a specific structure. Let's break it down piece by piece:

    // Method anatomy:
    // [access] [static] returnType methodName(parameters) {
    //     // body — the code that runs
    //     return value;  // (if not void)
    // }
    
    public static void sayHello() {
        System.out.println("Hello, World!");
    }
    
    // Let's break each part down:
    // public  → Who can use this method (anyone)
    // static  → Can be called without creating an object
    // void    → This method doesn't return a value
    // sayHello → The name (use a verb!)
    // ()      → No parameters needed

    To call (use) this method:

    public static void main(String[] args) {
        sayHello();   // Prints: Hello, World!
        sayHello();   // Prints it again — reusable!
        sayHello();   // And again!
    }

    🔑 Key insight: You define a method once (write the recipe), then call it as many times as you want (follow the recipe). The code inside the method only runs when you call it — defining it doesn't execute it.

    2️⃣ Parameters — Passing Data Into Methods

    Most methods need some data to work with. Parameters are variables listed in the method definition that receive values when the method is called. The values you pass in are called arguments.

    // One parameter
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
    
    greet("Alice");    // Hello, Alice!
    greet("Bob");      // Hello, Bob!
    
    // Multiple parameters
    public static void printSum(int a, int b) {
        System.out.println(a + " + " + b + " = " + (a + b));
    }
    
    printSum(5, 3);    // 5 + 3 = 8
    printSum(10, 20);  // 10 + 20 = 30

    Parameter vs Argument:

    • Parameter = the variable name in the method definition (String name)
    • Argument = the actual value you pass when calling ("Alice")

    Think of it like a form: the parameter is the blank field label ("Name: ___"), and the argument is what you fill in ("Alice").

    3️⃣ Return Values — Getting Results Back

    A void method does something but doesn't give you anything back (like printing). A return method computes a value and hands it back to whoever called it. You can then store that value, print it, or use it in another calculation.

    void — "Do something"

    void greet(String name) {
        System.out.println("Hi, " + name);
        // No return needed
    }
    
    greet("Alice");
    // Can't store the result:
    // String x = greet("Alice"); ❌

    Return — "Give me something"

    int add(int a, int b) {
        return a + b;
    }
    
    // Store and use the result:
    int result = add(5, 3);   // 8
    int total = add(10, add(2, 3));
    // add(2,3) returns 5
    // add(10, 5) returns 15
    // More return examples:
    public static double calculateTax(double price, double rate) {
        return price * rate;
    }
    
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }
    
    public static String getGrade(int score) {
        if (score >= 90) return "A";
        if (score >= 80) return "B";
        if (score >= 70) return "C";
        return "F";
    }
    
    // Using them:
    double tax = calculateTax(100.0, 0.08);  // 8.0
    boolean even = isEven(7);                 // false
    String grade = getGrade(85);              // "B"

    Try It: Creating & Calling Methods

    Build methods with parameters and return values

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Java Methods — simulated in JavaScript
    console.log("=== Creating & Calling Methods ===\n");
    
    // 1️⃣ Void method (no return value)
    function greet(name) {
      console.log("   Hello, " + name + "! 👋");
    }
    console.log("1. VOID METHODS:");
    greet("Alice");
    greet("Bob");
    greet("Charlie");
    
    // 2️⃣ Return methods
    function add(a, b) { return a + b; }
    function multiply(a, b) { return a * b; }
    
    console.log("\n2. RETURN METHODS:");
    console.log("   add(5, 3
    ...

    4️⃣ Method Overloading — Same Name, Different Parameters

    Java allows you to have multiple methods with the same name, as long as they have different parameter lists. The compiler picks the right version based on the arguments you pass. This is called overloading.

    // Three "add" methods — different parameter types/counts
    static int add(int a, int b) {
        return a + b;
    }
    
    static double add(double a, double b) {
        return a + b;
    }
    
    static int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Java picks the right one automatically:
    add(5, 3);          // → calls int version → 8
    add(5.5, 3.2);      // → calls double version → 8.7
    add(1, 2, 3);       // → calls 3-parameter version → 6

    Real-world example: System.out.println() is overloaded! It can print a String, int, double, boolean, char — there are actually 10+ versions of println(), and Java picks the right one based on what you pass.

    ⚠️ You CANNOT overload by return type alone:

    int  calculate(int x) { ... }
    double calculate(int x) { ... }  // ❌ Won't compile!
    // Same name AND same parameters — Java can't tell them apart

    5️⃣ Pass-by-Value — How Java Handles Arguments

    This concept confuses many beginners, so pay close attention. Java is always pass-by-value. This means when you pass a variable to a method, the method gets a copy of the value, not the original variable. Changes inside the method don't affect the original.

    static void tryToDouble(int x) {
        x = x * 2;  // Changes the COPY, not the original
        System.out.println("Inside method: x = " + x);  // 20
    }
    
    public static void main(String[] args) {
        int num = 10;
        tryToDouble(num);
        System.out.println("After method: num = " + num);  // Still 10!
    }
    
    // The method got a copy of 10, doubled it to 20 internally,
    // but the original 'num' variable was never touched.

    🔑 The workaround: If you need a method to produce a new value, use return:

    static int doubleIt(int x) {
        return x * 2;
    }
    int num = 10;
    num = doubleIt(num);  // Now num is 20!

    6️⃣ Variable Scope — Where Variables Live

    Variables declared inside a method are local to that method — they don't exist outside it. This is called scope. Each method is like its own room: you can't see what's inside another room.

    static void methodA() {
        int x = 10;  // x only exists in methodA
        System.out.println(x);  // ✅ Works
    }
    
    static void methodB() {
        System.out.println(x);  // ❌ ERROR! x doesn't exist here
    }
    
    // Parameters are also local:
    static void greet(String name) {
        // 'name' only exists inside greet()
    }
    // Can't use 'name' out here!

    💡 This is a feature, not a bug! Scope prevents methods from accidentally interfering with each other. You can use the same variable name (result, i, temp) in different methods without any conflict.

    Try It: Overloading & Pass-by-Value

    See how Java picks the right overloaded method and handles copies

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Overloading & Pass-by-Value — Java logic simulated in JavaScript
    console.log("=== Overloading & Pass-by-Value ===\n");
    
    // 1️⃣ Simulated method overloading
    function area(a, b) {
      if (b === undefined) {
        // Circle: area(radius)
        return { shape: "Circle", result: (Math.PI * a * a).toFixed(2) };
      } else {
        // Rectangle: area(width, height)
        return { shape: "Rectangle", result: (a * b).toFixed(2) };
      }
    }
    
    console.log("1. METHOD OV
    ...

    7️⃣ Static vs Instance Methods (Preview)

    You've been using static methods so far because they work without creating objects. Once you learn OOP (Lesson 9), you'll use instance methods too. Here's a quick preview:

    Static Method

    Call directly on the class. No object needed.

    Math.max(5, 10);       // 10
    Math.sqrt(16);         // 4.0
    Integer.parseInt("42"); // 42

    Instance Method

    Must create an object first.

    String name = "Hello";
    name.length();         // 5
    name.toUpperCase();    // "HELLO"
    name.charAt(0);        // 'H'

    For now, keep using static for all your methods. You'll understand the difference deeply in the OOP lesson.

    Try It: Build a Mini Calculator

    Create a calculator using methods for each operation

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Mini Calculator — Java logic simulated in JavaScript
    console.log("=== 🧮 Mini Calculator ===\n");
    
    // Define operations as methods
    function add(a, b) { return a + b; }
    function subtract(a, b) { return a - b; }
    function multiply(a, b) { return a * b; }
    function divide(a, b) {
      if (b === 0) return "Error: Cannot divide by zero!";
      return a / b;
    }
    function power(base, exp) {
      let result = 1;
      for (let i = 0; i < exp; i++) result *= base;
      
    ...

    Common Mistakes

    • ❌ Missing return statement:
      int add(int a, int b) {
          int sum = a + b;
          // ❌ Forgot to return sum! Compiler error.
      }
    • ❌ Ignoring the return value:
      add(5, 3);  // ❌ Calculates 8 but throws it away!
      int result = add(5, 3);  // ✅ Store the result
    • ❌ Methods too long: If your method is over 20 lines, it probably does too much. Split it into smaller methods.
    • ❌ Overloading by return type only: int foo() and String foo() won't compile — the parameters must differ.
    • ❌ Not calling the method: Defining a method doesn't run it! You must call it from main() or another method.

    Clean Method Guidelines

    💡 Single Responsibility: Each method should do ONE thing and do it well. calculateTax() — yes. calculateTaxAndPrintAndSaveToFile() — no!

    💡 Descriptive names with verbs: calculateShippingCost(), isValid(), getUserName() — not calc(), check(), get().

    💡 Keep methods small: Ideally 5-15 lines. Maximum 20-30 lines. If it's longer, break it up.

    💡 Limit parameters: 0-3 parameters is ideal. If you need 4+, consider grouping them into an object.

    💡 No surprises: A method named getTotal() should only return a total — it shouldn't also print something or save to a file.

    📋 Quick Reference

    ConceptSyntaxNotes
    Void methodvoid methodName(params)Performs action, no return
    Return methodint methodName(params)Must return matching type
    Parametersmethod(int a, String b)Input data for the method
    OverloadingSame name, different paramsCompile-time polymorphism
    Static methodstatic int add(int a, int b)Call without creating an object
    Pass-by-valuemethod(primitiveVar)Method gets a copy of the value
    ScopeVariables inside { }Only visible within that block

    🎉 Lesson Complete!

    You now know how to write clean, reusable methods with parameters, return values, overloading, and proper scope! Methods are the foundation of organized Java code — every professional program is built from hundreds of small, focused methods.

    Next up: Arrays — store and access collections of data to process lists, tables, and datasets efficiently.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service