Tsallaka zuwa abun ciki
Justice Tech School

Varargs and Pass by Value

A varargs parameter accepts any number of arguments. Java always passes by value: primitives are copied, and object references are copied too, so a method can change an object but not the caller variable.

Example
public class Main {
    static int sum(int... n) { int t = 0; for (int x : n) t += x; return t; }
    static void change(int[] a, int v) { a[0] = 99; v = 99; }
    public static void main(String[] args) {
        System.out.println(sum(1, 2, 3, 4));
        int[] arr = {1}; int val = 1;
        change(arr, val);
        System.out.println(arr[0] + " " + val);
    }
}

Result

10
99 1

Exercise

Accept many values.

static int f(int n)

Quiz Test

Is Java pass by reference?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.