• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strings

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
This is a question i found in Khalid Mughal book .
public class q{
public static void main(String args[]{
String space=""; //1
String composite=space + "hello"+space+space;//2
composite.concat("world");//3
String trimmed=composite.trim();//4
System.out.println(trimmed.length());//5
}
}
options are
5
6
7
12
13
ans is given as 5
but according to me ans shud be 12 .Can anyone plz explain me the reason .
the reason is given in the Khalid Mughal book as strings are immutable but according to me after line 3 composite should point to space hello space space world and the previous string should be available for garbage collection ..
thanks ..
 
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Vidya
This happens because the string at line 3 is not assigned to anything so the string is lost as soon as it is created. So actually there is no change being made to the string on line 3.
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Again Vidya,
After line 2
composite.length() == 5
For the concat method the docs say the following -
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
So composite.concat("world") on line 3 results in a new String object being returned while the reference to composite stays the same & thats why the answer is 5.
HTH
Ashish Hareet
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic