• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

How many String objects will be created???

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me how many String objects will be created after the execution of the below method.


public String makinStrings() {
String s = "Fred";
s = s + "47";
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
}

As per my view the answer should be 5 String Objects.

String s = "Fred"; // 1 object
s = s + "47"; // 2 ("47" & "Fred47") object
s = s.substring(2, 5); // 1 object
s = s.toUpperCase(); // 1 object

So total 5 objects ar created.
Am i right ???
Please explain.
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question wa asked many times in this forum. You can search them. Accordning to me i would say answer as 5 when the class is first loaded and there after 3 objects are created.

In order to under stand how string literals are treatd you can refer this link: http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
[ December 14, 2007: Message edited by: kesava narayana ]
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.. i think you are right..
the toString() method does not create a new string in this case..
it just returns the same string object form which it was invoked..
 
Hamraj Kulshreshtha
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Keasva,

Please explain this "Accordning to me i would say answer as 5 when the class is first loaded and there after 3 objects are created."

SO what will be the correct answer 3 or 5.
If 3 then why?
If 5 then why ?

Thanks,
Hamraj
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the link which i have posted in my previous post. Then you can understand it.
[ December 14, 2007: Message edited by: kesava narayana ]
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic