St.Antario
St.Antario

Reputation: 27455

Understanding reference concept in Java

My question is about how references work in Java. As far as I've understood by reading of JLS 4.12.2 reference is a formal name allows to work with an object that reference points to. Consider the following code:

public class A{
    private int a = 0;

    void mutate(){
        a++;
    }
}

public void foo (A a){
    a.mutate();
}

public static void main(String[] args){
    A a = new A(); //a is a reference to the object of type A
    foo(a);
}

Is the reference a which is local to the main function the same as a reference which is used within foo function? I mean would operator == return true if we applied it to these references as one's operands?

Upvotes: 1

Views: 116

Answers (4)

seh
seh

Reputation: 15269

No, the reference a in main() is not the same as the parameter a in function foo(). All function arguments are passed by value in Java. Copying a reference (main's a) when calling on foo() creates a new reference that points to the same referent (the object created in main() by the expression new A()).

You will often hear people say colloquially that two references are "the same," but what that really means is that the two references point to the same object or referent. The references themselves may sit in different registers or memory location, but their value—the object to which they refer—can be the same, just like pointers and references in other languages.

Upvotes: 5

TheLostMind
TheLostMind

Reputation: 36304

Is the reference a which is local to the main function the same as a reference which is used within foo function?

No, the reference is different, the instance to which both references point is the same.

pubic void foo (A a){ 

a here is a copy of the reference of a of main() (or any function that calls it). The reference will be on the stack for this method and is lost when the method returns (Stack unwinds)

public static void main(String[] args){
    A a = new A(); //a is a reference to the object of type A  // A is a reference on the Stack and local to main().
    foo(a);
}

Upvotes: 5

ha9u63a7
ha9u63a7

Reputation: 6862

When you do

 foo(a)

You are technically calling mutate(a) from within foo(a). but the stack reference is different i.e. the reference a used in foo() and the reference in main() is not the same.

Upvotes: 3

Mike Thomsen
Mike Thomsen

Reputation: 37524

Is the reference a which is local to the main function the same as a reference which is used within foo function?

They point to the same memory address if that's what you mean.

Upvotes: 2

Related Questions