0

I am beginner at java, so I found something has made me confused: Why when we create something like below:

String name = "Abdelillah";
String editName = name;
editName = "Mohammed";

My question is why the editName doesn't change name object? But when we use arrays, if we create a reference to the first array, the second affect the first I need to know why please and thank you

Abdelillah
  • 79
  • 1
  • 14
  • 1
    Because there's no link whatsoever between the variables `editName` and `name`, even when they happen to contain the same value (in this case, a reference to an object). `editName = name` just copies the value (an object reference, not the object itself) in `name` into `editName`. It's exactly the same reason that this doesn't change `a`: `int a = 42; int b = a; b = 67; System.out.println(a); // 42` – T.J. Crowder Oct 28 '19 at 16:44

1 Answers1

3

In the second line, editName is made to point to the same object as name. Both name and editName point to the string "Abdelillah".

Your mistake may be in thinking that the third line changes the contents of the object that editName points to ("Abdelillah"). Rather, in the third line, editName is made to point to a different object, the string "Mohammed".

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147