Parameters and Arguments

Passing Data In

Parameters are the variables listed in the method definition. Arguments are the actual values you pass when calling. They are matched by position and type.

Example

public class Main {
    static void greet(String name, int age) {
        System.out.println("Hi " + name + ", you are " + age);
    }

    static void printReceipt(String item, int qty, double price) {
        System.out.printf("%s x%d = Rs. %.2f%n", item, qty, qty * price);
    }

    public static void main(String[] args) {
        greet("Rahul", 23);
        greet("Divya", 21);
        printReceipt("Notebook", 3, 45.0);
        printReceipt("Pen", 10, 12.5);
    }
}

Output

Hi Rahul, you are 23
Hi Divya, you are 21
Notebook x3 = Rs. 135.00
Pen x10 = Rs. 125.00

Pass by Value

Example

Java always passes a copy of the argument. Changing a primitive parameter does not affect the caller. For arrays and objects the copy is a copy of the reference, so the method can change the object it points to.

import java.util.Arrays;

public class Main {
    static void tryToChange(int x) {
        x = 100;
    }

    static void addBonus(int[] marks) {
        for (int i = 0; i < marks.length; i++) marks[i] += 5;
    }

    public static void main(String[] args) {
        int value = 10;
        tryToChange(value);
        System.out.println("value = " + value);

        int[] marks = {60, 70};
        addBonus(marks);
        System.out.println("marks = " + Arrays.toString(marks));
    }
}

Output

value = 10
marks = [65, 75]

Varargs

Example

A parameter written as type... name accepts any number of arguments (it becomes an array).

public class Main {
    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(5));
        System.out.println(sum(1, 2, 3, 4));
    }
}

Output

0
5
10