Let’s dive into the concepts of “pass by value” and “pass by reference” in Java.

Java’s method parameter passing: primitives copy values, objects pass references, affecting original data differently.

When you pass a primitive type (like int, float, char, etc.) to a method in Java, you’re actually passing a copy of the value stored in that variable. This means that if you change the value inside the method, it won’t affect the original value outside of the method.

public class PassByValueExample {

    public static void main(String[] args) {
        int x = 10;
        System.out.println("Before calling method: " + x);
        changeValue(x);
        System.out.println("After calling method: " + x);
    }

    public static void changeValue(int num) {
        num = 20;
        System.out.println("Inside method: " + num);
    }
}

In this example, even though we change the value of num inside the changeValue method, the original value of num remains unchanged outside the method. This is because Java passes the value of num to the method, not the reference to it.

When you pass an object (instances of classes) to a method in Java, you’re actually passing a reference to that object. This means that if you change the state of the object inside the method, it will affect the original object outside of the method.

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class PassByReferenceExample {
    public static void main(String[] args) {
        Person person = new Person("Alice");
        System.out.println("Before calling changeName method: " + person.getName());
        changeName(person);
        System.out.println("After calling changeName method: " + person.getName());
    }

    public static void changeName(Person person) {
        person.setName("Bob"); // Changes the name of the person inside the method
        System.out.println("Inside changeName method: " + person.getName());
    }
}

In this example, when we change the name of the Person object inside the changeName method, it affects the original object outside the method. This is because Java passes the reference to the Person object, not a copy of it.

In Java, everything is pass by value. When you pass a primitive type, you pass a copy of its value. When you pass an object, you pass a copy of its reference. However, since the reference points to the same object in memory, changes made to the object within the method are reflected outside the method. So, while it may seem like pass by reference for objects, it’s technically still pass by value.

Atomic Variables in Java

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *