简体   繁体   中英

How to verify call by value of Java?

I read that Java does everything by call by value . I was wondering how to verify this fact? As far as I understand, in case of objects(not primitives) functions get its own copy of reference but points to same object. In that case, reference of that object in callee function and caller function should be different? How can I verify that? In other words, how to print the reference of the object.

System.out.println(object);  //does this print reference i.e text following @

EDIT: I understand that modifying object in callee function does change the value in caller function. I am interested in how to print the references of objects as in what property can I print on console that clearly shows me 2 different reference.

Java passes references by value . This means you'll get a copy of the reference, so once you dereference that you'll get to the same object in the heap as with the original reference.

But if Java was pass by reference:

public static void nullify(Object obj) {
    obj = null;
}

public static void main(...) {

    String x = "Hello";        
    nullify(x);

    System.out.println(x);
}

The call to Sop would print null if Java was pass by reference. But it isn't, so x is unchanged and you'll get Hello .

Assuming Class A property aa

A a= new A();
a.aa = 1;
// print a.aa here should be 1
method(a);
// here a.aa should be 2


Void method(A a) {
  a.aa =2;
  a = new A();
  a.aa = 3;
}

So this shows reference was passed as value. When you change the object in the method it does not change the reference of caller.

I think the String Object@1ed3af is composed of the class name of your object and it's hashcode, separated by a @. This is a unique string, identifying it.
Read this topic to get a full explanation !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM