-1

In java if Objects are pass by reference than in following code,

String str1 = new String("abc");
String str2 = str1;
str1 = str1+"def";
System.out.println("str2 : "+str2);

Even after modifying string str1 after assigning it to string str2 I get output as str2 : "abc" instead of "abcdef" so pass by reference does not work in case of string??

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
Zues
  • 9
  • 3
  • Java doesn't pass by reference http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Guy May 18 '17 at 10:12
  • 1
    'Does pass by reference work': no. There is no pass by reference in Java. 'In case of String': irrelevant. – user207421 May 18 '17 at 10:19
  • Technically speaking, the code in the question does not "pass" at all (by reference or otherwise), since there is no function call involved. – Mr Lister May 18 '17 at 11:24

1 Answers1

1

Instances of String in Java are immutable. When you think you're modifying a String actually what you're doing is to create a new one.

Andres
  • 10,561
  • 4
  • 45
  • 63