Java.How are variables passed to methods, by value or by reference?

In Java, variables are always passed by value, but the behavior differs depending on whether the variable holds a primitive type or a reference type.

1. Passing Primitives (Pass-by-Value)

  • When you pass a primitive (e.g., int, double, boolean) to a method, Java passes a copy of the actual value.
  • Any modification inside the method does not affect the original variable.

Example:

public class Test {
    public static void modify(int x) {
        x = 10; // Changes only the local copy
    }

    public static void main(String[] args) {
        int a = 5;
        modify(a);
        System.out.println(a); // Output: 5 (original value remains unchanged)
    }
}

2. Passing Objects (Pass-by-Value of the Reference)

  • When you pass an object to a method, Java passes a copy of the reference (not the actual object).
  • Inside the method, both the original variable and the parameter point to the same object in memory.
  • If you modify the object’s state (change its fields), the changes will be visible outside the method.
  • However, if you reassign the reference inside the method, it only changes locally and does not affect the original reference.

Example 1 (Modifying the object’s state – Affects the original object):

class Person {
    String name;
}

public class Test {
    public static void modify(Person p) {
        p.name = "Alice"; // Modifies the original object's state
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Bob";

        modify(person);
        System.out.println(person.name); // Output: Alice (modification persists)
    }
}

Example 2 (Reassigning the reference – Does NOT affect the original reference):

class Person {
    String name;
}

public class Test {
    public static void modify(Person p) {
        p = new Person(); // Changes only the local copy of the reference
        p.name = "Charlie";
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Bob";

        modify(person);
        System.out.println(person.name); // Output: Bob (original reference unchanged)
    }
}

Summary

  • Primitive types: Passed by value (method receives a copy, original remains unchanged).
  • Reference types: The reference is passed by value (method receives a copy of the reference).
    • Modifying the object’s fields does affect the original object.
    • Reassigning the reference inside the method does not affect the original reference.
This entry was posted in Без рубрики. Bookmark the permalink.