Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Strings?

 
Ira Jain
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class string
{
public static void main(String[] args) {
String str1="str";
str1.concat("str1"); //Line 0
System.out.println(str1); // Line 1
System.out.println(str1.concat("str1"));//Line 2
}
}
Output -
str
strstr1
Please explain me the output. I know that Strings are immutable and will create a new String at Line0 but wouldn't the same thing happen at Line2.
Will be really obliged if somebody could explain it.
Thanks in Advance,
Ira
 
rajani peddi
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ira Jain,
String str1="str";
str1.concat("str1"); //Line 0
System.out.println(str1); // Line 1
System.out.println(str1.concat("str1"));//Line 2
In Line 0 an anonymous string is created ("strstr1") but str1 is not changed.
That is why when you print in Line 1 str is getting printed.
With that reason again in Line 2 the anonymous string strstr1 is printed.
Hope this helps.
rajani

[This message has been edited by rajani peddi (edited December 21, 2000).]
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True a new string is created, but you didn't assign that new String to anything, so str1 reamained unchanged. If you said:
str1 = str1.concat("str1");
You would get what you expected when you printed out str1.
Bill
 
Nadeem Malik
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

hi,
String str1="str";
this line creates a string object "str" in string pool and its reference is in str1.
str1.concat("str1");
here u create an anonymous new string in a pool "strstr1"
but u did'nt print that.
If u use System.out.println here u will see tha same result at line 2.
System.out.println(str1);
this line is ok, it prints str.

System.out.println(str1.concat("str1"))
now u use this, therefore it prints strstr1.
so at line 0, u create a string but not print it.
at line 2 u again do the same thing but print it.
hope it helps.
 
Ira Jain
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys !! You really cleared up the concept for me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic