Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Are String objects created in System.out.println Statement

 
Hrishikesh Maluskar
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know whether String objects created in System.out.println Statement or not.

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println("Ans="+s1 + " " + s2);

Uptil now whatever discussions we had on this topic were prior to the System.out.println Statement.
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thumb rule - Whenever concantination of strings are done , a new object is created.
So answer for your questions is Yes
 
Hrishikesh Maluskar
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println("Ans="+s1 + " " + s2);

But in the above Statement how many Objects will be created.
According to me 3->
1. Ans=
2. " "
3. Entire Statement inside System.out.println.

I am not sure whether this is right or wrong..just want to confirm.
 
AKINLEYE ADEDAMOLA
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if a new object are created at every System.out.println() method does it mean that it does not check the string pool to see if the literal already exist
 
Sagar Rohankar
Ranch Hand
Posts: 2905
1
Java Spring Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hrishikesh Maluskar:
I want to know whether String objects created in System.out.println Statement or not.



I think , Yes, Strings are created inside The System.out.print() statements ! You may have confusion , because , people thinks , whatever we write in side System.out.println(), flushes out !, It may flush out , but not Garbage Collected !
 
Ronald Schild
Ranch Hand
Posts: 117
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hrishikesh Maluskar:
System.out.println("Ans="+s1 + " " + s2);

But in the above Statement how many Objects will be created.
According to me 3->
1. Ans=
2. " "
3. Entire Statement inside System.out.println.

I am not sure whether this is right or wrong..just want to confirm.


2 String objects will be created when the class is loaded that contains this line, with content "Ans=" and " ".

3 String objects will be created in the process to build the printed String.
str1 > "Ans=" + s1
str2 > str1 + " "
str3 > str2 + s2
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic