| No. | Answer | Remark | |
|---|---|---|---|
| 1 | f | Prints: ABABCABC | Instances of type StringBuffer are not immutable. In method m1, the method invocation expression s1.append("B") appends the String literal "B" to the StringBuffer instance referenced by variable s1. The append method returns a reference to the same StringBuffer instance on which it is invoked; so the assignment expression s1 = s1.append("B") does not assign a different reference value to variable s1. The new value, AB, is printed in method m1. In method m2, the method invocation expression s1.append("C") appends the String literal "C" to the StringBuffer instance referenced by variable s1. The new value, ABC, is printed in method m2. In the main method, a copy of the reference value contained by the reference variable s1 is passed as an argument to methods m1 and m2. Since StringBuffer instances are not immutable, methods m1 and m2 are able to change the original StringBuffer instance that is declared in the main method. The new value, ABC, is printed in the main method. |
| 2 | c | Prints: ABCAB | Instances of type StringBuffer are not immutable. In method m1, the method invocation expression s1.append("B") appends the String literal "B" to the StringBuffer instance referenced by the parameter variable s1. The new value, AB, is printed in method m1. The reference variable s1 declared in the main method refers to the same modified StringBuffer instance. In method m2, the class instance creation expression new StringBuffer("C") creates a new instance of type StringBuffer containing the value C. The assignment expression s1 = new StringBuffer("C") assigns a reference to the new StringBuffer instance to the method parameter variable s1. The value C is printed in method m1. The method local reference variable s1 in the main method remains unchanged by the assignment expression contained in method m2. In the main method, a copy of the reference value contained by the reference variable s1 is passed as an argument to methods m1 and m2. Since StringBuffer instances are not immutable, method m1 is able to change the original instance of the StringBuffer declared in the main method. Since references are passed by value, method m2 can not change the reference variable declared in the main method. Regardless of anything that happens in method m2, the reference variable s1 that is declared in the main method will continue to reference the original StringBuffer instance. Since the content of the original instance was modified by method m1, the new value, AB, is printed in the main method. |
| 3 | a | Prints: false,false |
|
| 4 | c | Prints: true,false |
|
| 5 | a | Prints: false,false |
|
| 6 | c | Prints: true,false |
The
StringBuffer
class does not override the
equals
and
hashCode
methods of the
Object
class.
The
|