-2

I have two string arrays, and one is assign by the other. Why I assign one of them to null won't affect the other? As the console output , they both have the same address. Is't not the same with c++? here is my code:

String []  bikes = new String[5];
String [] largerBikes = new String[bikes.length + 5];
bikes = largerBikes;
System.out.println(bikes);
System.out.println(largerBikes);
largerBikes = null;
System.out.println(bikes);
System.out.println(largerBikes);

enter image description here

Jswq
  • 758
  • 1
  • 7
  • 23
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Jeroen Steenbeeke Apr 10 '18 at 14:06
  • " Is't not the same with c++? " No. But this wouldn't happen in C++ either. – Andy Turner Apr 10 '18 at 14:06
  • Unlike in C++, a variable in Java is a **reference** to an object, it's not the value of the object itself. – Jesper Apr 10 '18 at 14:17

1 Answers1

2

they both have the same address

No, they both point to the same address.

When you assign null to largerBikes you have merely set that variable (reference to actual array content) to null, not the content it points to.

bikes and largerBikes are separated from each other. bikes variable itself is stored separately from the largerBikes variable.

When you write bikes = largerBikes you have following situation:

enter image description here

But then when you write largerBikes = null you will just clear that single reference to the array:

enter image description here

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159