I have written following program to test the equals and Java pass by value functionality (as per documentation Java is pass by value), so when I pass object a
to the method I am actually passing the heap values. What is if I change the reference of the object in the method? What will happen?
package equalstest;
public class EqualsMethodTest {
public static void main(String[] args) {
EqualsMethodTest a = new EqualsMethodTest();
EqualsMethodTest b = new EqualsMethodTest();
System.out.println(" Comparing a and B");
System.out.println(a == b);
System.out.println(a.equals(b));
EqualsMethodTest c = compare(a, b);
System.out.println(" Comparing B and C after interchanging references");
System.out.println(b == c);
System.out.println(b.equals(c));
System.out.println(" Comparing A and C after interchanging references");
System.out.println(a == c);
System.out.println(a.equals(c));
}
static EqualsMethodTest compare(EqualsMethodTest a, EqualsMethodTest b) {
EqualsMethodTest c = a;
a = b;
return c;
}
}
I am getting below output:
Comparing a and B
before alteration a == b false
before alteration a.equals b false
Comparing B and C after interchanging references
after alteration b == c false
after alteration b.equals c false
Comparing A and C after interchanging references
after alteration a == c true
after alteration a.equals c true
- What actually happens in the method
compare
? - When I create a new reference
c
does it point to memory location ofa
? - What happens when I assigning
b
toa
?