• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string append

 
Suhita Reddy
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

this is example in the k&b book.


String d="bookkeeper";
d.subString(1,7);
d="w"+d;
d.append("Woo");
System.out.println(d);

in this program first substring returns ookkeep,but we can't give reference.so it will destroyed.in the next line we are concatnating W to the string.then the result is Wbookkeeper.in the next line line we are appending "woo" to the string.but we can't gave reference.so answer will be Wbookkeeper.but the answer is WbookkeeperWoo.How it possible?
 
Saumya Tangeda
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I solved this same question recently and did the same mistake.The code you presented here is partial.look at the rest of the code, may be the calling method is printing Woo again
 
Suhita Reddy
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is the total code they given?
 
Jacob Thomas
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMHO, the above code snippet won't compile as there is no append() method defined for String class. A method of similar functionality available in the String class is the concat method(). But remember that any changes made to any objects of String class won't be reflected on the same object as String objects are immutable. The append() method is defined in StringBuffer class. It appends the argument to the end of the string.
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Suhita Reddy:
hi,

this is example in the k&b book.


String d="bookkeeper";
d.subString(1,7);
d="w"+d;
d.append("Woo");
System.out.println(d);

in this program first substring returns ookkeep,but we can't give reference.so it will destroyed.in the next line we are concatnating W to the string.then the result is Wbookkeeper.in the next line line we are appending "woo" to the string.but we can't gave reference.so answer will be Wbookkeeper.but the answer is WbookkeeperWoo.How it possible?


Well this programs contains so many errors:
1. there is no method named as String.subString(int , int);
there is a typo the correct version is String.substring(int , int)

2. You are not collecting the substring and even what substring you reported as "ookkeep". It's wrong it cann't return "ookkeep". The retruned string is "ookkee".

3. There is no method named as String.append(String).


Please check the whole code and come up again with compiled code and try to run it. Also try to run it ownself and then ask any specific query.

Hope it helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic