Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects to methods java

Tags:

java

I'm using three objects: StringBuilder, Integer, and testobject - that are passed to a method to change its state.

As expected, the StringBuilder and testobject points to the same object and the state is change but it does not work for Integer object.

class testobject{
    int x = 1;
}

public class test{
    public static void main(String[] args){
        StringBuilder s1 = new StringBuilder("String");
        go(s1);
        System.out.println(s1);

        Integer s2 = new Integer("20");
        go1(s2);
        System.out.println(s2);

        testobject s3 = new testobject();
        go2(s3);
        System.out.println(s3.x);
    }

    static void go(StringBuilder s1){
        s1.append("Builder");
    }

    static void go1(Integer s2){
        s2 = 1;
    }
    static void go2(testobject s3){
        s3.x = 5;
    }

Result:

StringBuilder
20
5

ExpectedResult:

StringBuilder
1
5
like image 932
user1050619 Avatar asked Feb 16 '23 02:02

user1050619


1 Answers

Look at your three methods:

static void go(StringBuilder s1){
    s1.append("Builder");
}

static void go1(Integer s2){
    s2 = 1;
}

static void go2(testobject s3){
    s3.x = 5;
}

In go and go2, you're making a modification to the object that the parameter value refers to.

In go1, you're changing the value of the parameter variable itself. That's very different, and because Java always uses pass-by-value, that change isn't seen by the caller.

It's important to understand that objects aren't passed to the methods at all. Instead, references are. The value of s1, s2 and s3 are all references. If you think of the variables as like pieces of paper, each piece of paper has a house address on it, which was copied from a piece of paper declared in main.

The method bodies of go and go2 are like visiting the house whose address is on the piece of paper, and painting the front door. If you then visit the houses using the original pieces of paper, you still see the new colours on the front doors.

The method body of go1 is like scribbling out the address written on the piece of paper, and writing a new one on there instead. That doesn't make any change to a house, nor does it change the original piece of paper.

like image 178
Jon Skeet Avatar answered Feb 17 '23 20:02

Jon Skeet