Methods & Parameters

☕ Java Lesson 9 Beginner

Methods are reusable, modular code blocks that perform specific operations. In Java, methods must reside inside classes and define return types and argument signatures.

1 Method Declarations & Overloading

A method structure contains a visibility modifier, return type, name, and parameter list:

  • Method Signature: Comprises the method name and parameter types. Return types are not part of the signature.
  • Method Overloading: Defining multiple methods with the same name but different parameter lists (number, order, or type of arguments).
2 Pass-by-Value in Java

Java is strictly Pass-by-Value. When passing arguments to a method:

  • For primitives, Java copies the value. Modifications inside the method do not affect the original variable.
  • For objects, Java copies the reference pointer address. Modifying properties of the object inside the method does affect the original object because both reference copies point to the same memory heap location.
Java — Methods & Overloading ▶ Run Code
public class Main {
    // Basic method returning integer
    public static int add(int x, int y) {
        return x + y;
    }

    // Overloaded method adding doubles
    public static double add(double x, double y) {
        return x + y;
    }

    // Demonstrating pass-by-value on primitive
    public static void modifyPrimitive(int val) {
        val = 100; // Altering local copy only
    }

    public static void main(String[] args) {
        int sumInt = add(5, 10);
        double sumDouble = add(2.5, 3.5);
        System.out.println("Integer Sum: " + sumInt);
        System.out.println("Overloaded Double Sum: " + sumDouble);

        int originalNum = 10;
        modifyPrimitive(originalNum);
        System.out.println("Primitive after modification call: " + originalNum); // Remains 10
    }
}
3 Code Challenge
Challenge: Write a method called `calculateArea` that takes a single double parameter (representing a circle's radius) and returns its computed area. Overload this method by defining another `calculateArea` that takes two parameters (double length, double width) to compute a rectangle's area. Call both inside `main()` and print results.