• Post Reply Bookmark Topic Watch Topic
  • New Topic

strings are immutable!!  RSS feed

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We say Strings are immutable but the following code is working fine, pls justify
String s="Java";
s=s+"Technology";
System.out.pritnln(s);
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
just go through this url, this may help u
http://www.churchillobjects.com/c/11027.html
bhramaresh
 
Greenhorn
Posts: 15
Chrome IntelliJ IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

s is a reference to the String "Java" at first, and becomes a reference to a brand new String "JavaTechnology". The first String will become garbage (provided no other references to it exist), but remains unchanged, hence the immutable.
 
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Harsha Vardhan Madiraju:
We say Strings are immutable but the following code is working fine, pls justify
String s="Java";
s=s+"Technology";
System.out.pritnln(s);

String s="Java";
is internally converted to,
String s = new String("Java");

So here new object of String class is being created and reference is
assigned to variable 's';
s=s+"Technology";
Here new object is being created and reference is being assigned to
variable 's' and thus reference to Object 'Java' is overwritten.
Immutable means we can not change content of object but can change
reference assigned to it.
For more info, check this link.
http://www.csc.calpoly.edu/~csc101/studynotes/Strings.htm
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!