Question

"Java is pass-by-value"
-Java Language Specification

However, there are things that confuses me. Please take a glimpse of my example

public class Main {

    public static void main(String[] args) {

        StringBuilder myBuilder = new StringBuilder("Michael");

        editString(myBuilder);

        System.out.println(myBuilder);

    }

    public static void editString(StringBuilder x){
        x.append(" Ardan");
    }

}

Output:

Michael Ardan

And this example:

public class Main {

    public static void main(String[] args) {

        int myInt = 10;

        editInt(myInt);

        System.out.println(myInt);

    }

    public static void editInt(int x){
        x ++;
    }
}

Output:

10

I tried reading other articles and it all says that Java is always pass-by-value. I've done some test scenario. Comparing both example to each other made me think that Java's Objects are pass-by-reference and primitive types are pass-by-value. However, if you tried to replace the int primitive type into Integer Object, the result would be the same. I would love if somebody explain these two examples here.

Was it helpful?

Solution

Strictly speaking, Java is pass-by-value.

However, what gets passed by value is a "pointer" to an object. So you will be able to access and modify the state of that object from inside the called method (and those changes are visible to everyone else who has a "pointer" to the same object).

Pass-by-reference would mean that you can change where the variable on the calling side points to. That you cannot do in Java.

For example

  public static void editString(StringBuilder x){
     x = new StringBuilder("Foo");
  }

has no effect outside of the method. In pass-by-reference, you would actually be assigning that new StringBuilder back into the calling method variable.

OTHER TIPS

you are right , java object always pass-by-reference, but,you can see the source code of wrapper class like 'Integer','String','Short' and so on.they are 'value' are definded as final .it can not be changed .so ,the question 'if you tried to replace the int primitive type into Integer Object, the result would be the same.' which related with it.when you replace with Integer Object and change the value in you method. the Object changes. so, you can see the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top