when a String is mutable

------------------------------------------------ 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

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.

<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes

Moya Green
Ranch Hand

Joined: Jan 24, 2002
Posts: 49

posted Feb 19, 2002 20:17:00

0

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!