This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Strings? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about Strings?" Watch "Question about Strings?" New topic
Author

Question about Strings?

Ira Jain
Ranch Hand

Joined: Sep 06, 2000
Posts: 70
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

Joined: Nov 27, 2000
Posts: 73
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

Joined: Jun 30, 2000
Posts: 1070
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

Joined: Nov 22, 2000
Posts: 10

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

Joined: Sep 06, 2000
Posts: 70
Thanks guys !! You really cleared up the concept for me.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about Strings?
 
Similar Threads
Please help and explain the output of following code.
More Code Concepts...
String literal objects in String pool
equals ?????
String literal and String object comparison