• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help me with the Strings

 
manasa teja
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please tell me the output the follwoing program and reason behind it. A brief explanation is greatly appreciated.
===
public class immut {
public static void main(String[] args) {
String s = "good day";
Changeit(s);
System.out.println(s);
s = "not a " + s;
System.out.println(s);
}
static void Changeit(String s) {
s = "not a " + s;
System.out.println(s);
}}
 
Karen Leoh
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there..
The output of the program is
not a good day
good day
not a good day
When you call Changeit() it passes a copy of the reference not the actual string itself. Thus, in Changeit() it prints not a good day.. but when it returns to the main() it prints good day.
In my opinion, it would be better if you can tell which part you do not understand. So, a better explanation can be given.
However, hope that helps.
 
manasa teja
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen,
thanks for your explanation.
String s = new String ("good day");
s = "not a " + s;
System.out.println(s);
But,this is giving me "not a good day".
Is this not against Strings immutability. Please explain.

===============
When you call Changeit() it passes a copy of the reference not the actual string itself. Thus, in Changeit() it prints not a good day.. but when it returns to the main() it prints good day.
=========
[ June 04, 2002: Message edited by: Murthy Kompella ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Murthy Kompella:
Is this not against Strings immutability. Please explain.

No. When you use the String concatenation operator, you don't actually change the String. Rather that operator returns a brand new String.
Look at this example:

Obviously, the original String hadn't changed, even after the concatenation operator. If it had, printing the String object referenced by t would have also indicated that change. The concatenation operator creates a new String object, in which both the original contents of the String "Test" and the new String "1" are combined. A reference to that new object is then assigned to s.
I hope that helps,
Corey
 
manasa teja
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats a nice explanation. Now, I will never dare to say "Strings are mutable"
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Murthy Kompella:
thats a nice explanation. Now, I will never dare to say "Strings are mutable"

Try it and we will crush you!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic