0

I have this piece of code, and I would like to know why the reference of my variable x is not modified ? It still points to the first object assigned:

public class HelloWorld{

 public static void main(String []args){
    Object x = new Object();
    Object y = x;
    mutate(x);
    System.out.println(Integer.toHexString(x.hashCode()));
    System.out.println(Integer.toHexString(y.hashCode()));
    System.out.println(x == x); // true
    System.out.println(x == y); // true
 }

 public static void mutate(Object x) {
     x = new String();
 }

}

darthfather
  • 377
  • 3
  • 12
  • Because Java is pass by value. The other important part here: please do prior research the next time. This is basic, elemental stuff; documented a zillion times out there; and probably asked and answered here even more often. – GhostCat Jul 25 '16 at 12:25
  • Because Java is pass-by-value (and references are passed by value); see the question of which this is considered a duplicate for a detailed explanation. – Jesper Jul 25 '16 at 12:25
  • So what is the difference with adding a final modifier to the method ? – darthfather Jul 25 '16 at 12:27

0 Answers0