alchemist
alchemist

Reputation: 41

Passing primitive type as pass by reference by wrapping in class of primitive type

I am passing 2 Boolean objects to a function. I know Java is pass by value but since I am using objects as parameters it should be passing the address of those parameters instead of the value. But after updating the object values in function I don't see updated values in main. What am I missing here?

public class Test1 {
    public static void main(String[] args){
        Boolean b1 = new Boolean(false);
        Boolean b2 = new Boolean(false);

        System.out.println(b1+" "+b2);
        func1(b1, b2);
        System.out.println(b1+" "+b2);
    }

    static void func1(Boolean b1, Boolean b2){
        System.out.println(b1+" "+b2);
        b1 = !b1;
        b2 = !b2;
        System.out.println(b1+" "+b2);
    }
}

Upvotes: 1

Views: 101

Answers (3)

Harsh
Harsh

Reputation: 644

Everything in java is pass by value. You are passing objects which are of type wrapper class, those objects are immutable, meaning, their value is fixed. As objects are passed as a parameter which are some kind of references, it's called as pass by reference. So in your case it's pass by reference, and value remains unchanged because of their nature which is immutable.

Upvotes: 1

Kalinovcic
Kalinovcic

Reputation: 568

b1 = !b1 is syntactic sugar for b1 = new Boolean(!b1.booleanValue). Because of this, you don't modify the original object that was sent as a parameter to the function, but instead create a new Boolean object.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

The wrapper types are immutable so you're creating new (local) references there. For the behavior you expect you can pass an array (note that arrays are Object instances in Java).

public static void main(String[] args) {
    boolean[] arr = { true, false };
    System.out.println(arr[0] + " " + arr[1]);
    func1(arr);
    System.out.println(arr[0] + " " + arr[1]);
}

static void func1(boolean[] arr) {
    System.out.println(arr[0] + " " + arr[1]);
    arr[0] = !arr[0];
    arr[1] = !arr[1];
    System.out.println(arr[0] + " " + arr[1]);
}

Output is

true false
true false
false true
false true

Upvotes: 4

Related Questions