Methods in Java

1. What is a Method?

A method in Java is a block of code that performs a specific task and runs only when it is called. Methods allow you to break your program into smaller, reusable pieces, making your code easier to read, test, and maintain. Every Java program must have at least one method: main(), which is the entry point of execution.

The general syntax of a Java method is:

// Full anatomy of a Java method:
//
//  accessModifier  returnType  methodName ( parameterList )
//       |               |           |            |
//       v               v           v            v
       public          int         add    (int a, int b)
       {
           // method body
           return a + b;   // return statement (required for non-void)
       }
//
// Access Modifier : controls visibility (public, private, protected, default)
// Return Type     : type of value returned; use 'void' if nothing is returned
// Method Name     : identifier following camelCase convention
// Parameter List  : comma-separated input variables (can be empty)
// Method Body     : statements inside curly braces { }
// Return Statement: sends value back to caller (omit for void methods)

Tip: Method names should be verbs or verb phrases in camelCase, e.g., calculateArea(), printMessage(), getUserName().

2. Types of Methods

Java methods fall into two broad categories:

Predefined (Built-in) Methods

These are methods already defined in the Java Standard Library. You can use them directly without writing any implementation.

public class PredefinedDemo {
    public static void main(String[] args) {
        // Math class methods
        System.out.println(Math.max(10, 20));     // 20
        System.out.println(Math.sqrt(49));         // 7.0
        System.out.println(Math.abs(-15));         // 15

        // String class methods
        String name = "Java Codeex";
        System.out.println(name.toUpperCase());    // Java Codeex
        System.out.println(name.length());         // 13
    }
}
20
7.0
15
Java Codeex
13

User-Defined Methods

These are methods you create yourself to perform custom logic specific to your program.

public class UserDefinedDemo {
    // User-defined method
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        greet("Alice");   // calling the user-defined method
        greet("Bob");
    }
}
Hello, Alice!
Hello, Bob!

3. Method Declaration and Calling

A method must be declared (defined) before or after main() within the class. It is then called (invoked) by its name followed by parentheses. Below is a complete example that adds two numbers:

public class Calculator {

    // Method declaration: returns the sum of two integers
    static int add(int a, int b) {
        int sum = a + b;
        return sum;
    }

    public static void main(String[] args) {
        // Method call: passing arguments 5 and 3
        int result = add(5, 3);
        System.out.println("Sum = " + result);

        // Calling inline inside println
        System.out.println("Sum of 10+20 = " + add(10, 20));
    }
}
Sum = 8
Sum of 10+20 = 30

Declaration vs Call: The method declaration defines what the method does. The method call actually executes it. You can call the same method as many times as needed.

4. Method Parameters and Arguments

Parameters are the variables listed in the method definition. Arguments are the actual values passed when calling the method. Java passes all primitive types by value, meaning a copy of the value is passed — the original variable is not affected.

Pass by Value

public class PassByValue {

    static void doubleIt(int num) {
        num = num * 2;   // modifies the local copy only
        System.out.println("Inside method: " + num);
    }

    public static void main(String[] args) {
        int x = 10;
        doubleIt(x);
        System.out.println("After method call: " + x);  // x is unchanged
    }
}
Inside method: 20
After method call: 10

Multiple Parameters

public class MultiParam {

    // Method with three parameters of different types
    static void describe(String name, int age, double gpa) {
        System.out.println(name + " is " + age + " years old with GPA " + gpa);
    }

    public static void main(String[] args) {
        describe("Alice", 20, 3.85);
        describe("Bob",   22, 3.40);
    }
}
Alice is 20 years old with GPA 3.85
Bob is 22 years old with GPA 3.4

Important: The number, order, and types of arguments in the method call must exactly match the parameter list in the method declaration.

5. Return Types

The return type declares what kind of value the method sends back to the caller. Use void when the method does not return anything. For all other return types, you must include a return statement.

public class ReturnTypesDemo {

    // void: no value returned
    static void printLine() {
        System.out.println("--------------------");
    }

    // returns an int
    static int square(int n) {
        return n * n;
    }

    // returns a String
    static String getGreeting(String name) {
        return "Welcome, " + name + "!";
    }

    // returns a boolean
    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    // returns a double
    static double circleArea(double radius) {
        return Math.PI * radius * radius;
    }

    public static void main(String[] args) {
        printLine();
        System.out.println(square(7));
        System.out.println(getGreeting("Alice"));
        System.out.println(isEven(4));
        System.out.printf("Area = %.2f%n", circleArea(5.0));
        printLine();
    }
}
--------------------
49
Welcome, Alice!
true
Area = 78.54
--------------------

6. Static Methods vs Instance Methods

Static methods belong to the class itself and can be called without creating an object. Instance methods belong to an object — you must create an instance of the class before calling them.

Feature Static Method Instance Method
Belongs to Class Object (instance)
Keyword static (no static keyword)
Call syntax ClassName.method() obj.method()
Accesses instance fields? No Yes
Typical use Utility / helper functions Behavior depending on object state
public class MethodTypes {

    String name;   // instance field

    // Instance method — uses instance field
    void setName(String n) {
        this.name = n;
    }

    void printName() {
        System.out.println("Name: " + name);
    }

    // Static method — no access to instance fields
    static int multiply(int a, int b) {
        return a * b;
    }

    public static void main(String[] args) {
        // Calling static method — no object needed
        System.out.println("5 x 6 = " + multiply(5, 6));

        // Calling instance method — object required
        MethodTypes obj = new MethodTypes();
        obj.setName("Java");
        obj.printName();
    }
}
5 x 6 = 30
Name: Java

7. Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameter lists (different number, types, or order of parameters). The correct method is chosen by the compiler at compile time based on the arguments passed.

public class Overloading {

    // Example 1: different number of parameters
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    // Example 2: different parameter types
    static double add(double a, double b) {
        return a + b;
    }

    // Example 3: different order of types
    static String format(String label, int value) {
        return label + " = " + value;
    }

    static String format(int value, String label) {
        return value + " -> " + label;
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));            // calls add(int, int)
        System.out.println(add(3, 4, 5));         // calls add(int, int, int)
        System.out.println(add(2.5, 3.5));        // calls add(double, double)
        System.out.println(format("Score", 99));  // calls format(String, int)
        System.out.println(format(42, "Answer")); // calls format(int, String)
    }
}
7
12
6.0
Score = 99
42 -> Answer

Note: Overloading is resolved at compile time (static polymorphism). You cannot overload methods by changing only the return type — the parameter list must differ.

8. Access Modifiers

Access modifiers control the visibility of a method (or field/class) from other classes and packages.

Modifier Same Class Same Package Subclass Other Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default (no keyword) Yes Yes No No
private Yes No No No
public class AccessDemo {

    public void publicMethod() {
        System.out.println("Accessible everywhere");
    }

    protected void protectedMethod() {
        System.out.println("Accessible in same package and subclasses");
    }

    void defaultMethod() {
        // No modifier = package-private
        System.out.println("Accessible only within the same package");
    }

    private void privateMethod() {
        System.out.println("Accessible only within this class");
    }

    public void callPrivate() {
        privateMethod();   // OK — called from same class
    }
}

Best Practice: Use private for helper methods used only within the class. Use public for the API of your class. Minimize exposure to what callers actually need.

9. Command Line Arguments

When you run a Java program from the terminal, you can pass values directly to the main() method via the String[] args parameter. Each space-separated token becomes an element of the args array.

public class CommandLineArgs {

    public static void main(String[] args) {
        // args.length tells how many arguments were passed
        System.out.println("Number of arguments: " + args.length);

        // Loop through all arguments
        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i + "] = " + args[i]);
        }

        // Practical example: add two numbers from command line
        if (args.length == 2) {
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            System.out.println("Sum = " + (a + b));
        }
    }
}

Compile and run from the terminal:

javac CommandLineArgs.java
java CommandLineArgs 10 25
Number of arguments: 2
args[0] = 10
args[1] = 25
Sum = 35

Remember: Command line arguments are always received as String. Convert them to the required type using Integer.parseInt(), Double.parseDouble(), etc.

10. Variable Arguments (Varargs)

Varargs (variable-length arguments) allow a method to accept zero or more arguments of a specified type without defining overloaded versions. The syntax uses three dots (...) after the type. Internally, Java treats varargs as an array.

public class VarargsDemo {

    // Accepts any number of int arguments
    static int sum(int... nums) {
        int total = 0;
        for (int n : nums) {
            total += n;
        }
        return total;
    }

    // Varargs with a required leading parameter
    static void printAll(String label, String... items) {
        System.out.print(label + ": ");
        for (String item : items) {
            System.out.print(item + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        System.out.println(sum());               // 0  (zero args)
        System.out.println(sum(5));              // 5
        System.out.println(sum(1, 2, 3));        // 6
        System.out.println(sum(10, 20, 30, 40)); // 100

        printAll("Fruits", "Apple", "Mango", "Banana");
        printAll("Colors", "Red", "Blue");
    }
}
0
5
6
100
Fruits: Apple Mango Banana
Colors: Red Blue

Rules for Varargs: (1) A method can have only one varargs parameter. (2) The varargs parameter must be the last parameter in the list. (3) You can pass an array directly as a varargs argument.

Continue learning