Java pass by reference

Asked 2 years ago, Updated 2 years ago, 103 views

What is the difference between the two codes below?

Code A:

Foo myFoo;
myFoo = createFoo();

CreateFoo method

public Foo createFoo()
{
   Foo foo = new Foo();
   return foo;
}

Code B:

Foo myFoo;
createFoo(myFoo);

public void createFoo(Foo foo)
{
   Foo f = new Foo();
   foo = f;
}

Is there a difference between the two codes? Thank you!

java parameter-passing pass-by-value pass-by-reference terminology

2022-09-22 21:12

1 Answers

Java always passes the arguments as non-reference values.

Let me show you an example:

public class Main
{
     public static void main(String[] args)
     {
          Foo f = new Foo("f");
          changeReference(f); // The reference value will not actually change
          ModifyReference(f); // The reference value of the object indicated by the variable "f" will change
     }
     public static void changeReference(Foo a)
     {
          Foo b = new Foo("b");
          a = b;
     }
     public static void modifyReference(Foo c)
     {
          c.setAttribute("c");
     }
}

Step by step:

1. Declare Foo-type variable f and assign Foo-type objects with "f" as attribute values.

Foo f = new Foo("f");

http://i.stack.imgur.com/arXpP.png

2. For the method, a reference of type Foo was declared and initialized to null.

public static void changeReference(Foo a)

http://i.stack.imgur.com/k2LBD.png

3. As you invoke the changeReference method, the object passed as a factor in reference a will be assigned.

changeReference(f);

http://i.stack.imgur.com/1Ez74.png

4. Declare a reference of Foo type b and assign an Foo type object with "b" as an attribute value

Foo b = new Foo("b");

http://i.stack.imgur.com/Krx4N.png

5. The a=b expression is equivalent to having reference a point to an object with a property value of "b", not f.

http://i.stack.imgur.com/rCluu.png

6. By calling the modifyReference(Fook) method, a reference c is generated and an object with the attribute value "f" is assigned.

http://i.stack.imgur.com/PRZPg.png

7. c.setAttribute("c"); the method will change the property value of the object that reference c points to, and the object will be the object that f points to.

http://i.stack.imgur.com/H9Qsf.png

I hope you now understand how Java delivers objects as factors.


2022-09-22 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.