• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when a String is mutable

 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
------------------------------------------------
Question: Given the following sequence of Java statements
1. StringBuffer sb = new StringBuffer("abc");
2. String s = new String("abc");
3. sb.append("def");
4. s.append("def");
5. sb.insert(1, "zzz");
6. s.concat(sb);
7. s.trim();
Which of the following statements are true:
A. The compiler would generate an error for line 1.
B. The compiler would generate an error for line 2.
C. The compiler would generate an error for line 3.
D. The compiler would generate an error for line 4.
E. The compiler would generate an error for line 5.
F. The compiler would generate an error for line 6.
G. The compiler would generate an error for line 7.
-----------------------------------------------
The answer is D F.
I understand that a String as an object is immutable. It is not right to apply append() and concat() to the String. Then I am confused, why the trim() method can be used to the String without generating an error, which is answer G?
Since the String class have several methods (such as concat(string), substring(int), trim), under what conditions can those methods be used to modify the String?
Please help! :roll: Thank you in advance.
--Moya
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason line 4 generates an error is because append() is not a method of the String class, likewise the String.concat() take as argument of type String not type StringBuffer().
Note: that the String.trim() method does not alter the original string, hence the immutibility of strings
What String.trim() does is return a new String object back if and on if the original string had leading or trailing spaces, otherwise a reference to the original string is returned.
 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, Rajinder!
---------------------------------------
"The reason line 4 generates an error is because append() is not a method of the String class, likewise the String.concat() take as argument of type String not type StringBuffer()."
---------------------------------------
So it is summarized as:
1) append() is a method of StringBuffer class, not String class.
2) String.concat(String) is right; String.concat(StringBuffer) is wrong;
Pls correct me if I am wrong.

Can someone give me a pointer to a line in the JLS, where the methods of String/StringBuffer class are explained, please :roll: ? Thank you!
 
chafule razgul
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would actually go to the API for this question
hope this helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic