According to what I have read, the only possible outputs for this program are "A"
or no printouts. But since the statement new MyString("A").concat("B");
is creating a new object with string "AB"
, couldn't this object also be garbage collected resulting in output "AB"
?
class MyString {
private String str;
MyString(String str) { this.str = str; }
public void finalize() throws Throwable {
System.out.print(str);
super.finalize();
}
public void concat(String str2) {
this.str.conc开发者_JAVA百科at(str2);
}
public static void main(String[] args) {
new MyString("A").concat("B");
System.gc();
}
}
Strings are immutable. Your line this.str.concat(str2);
does practically nothing, and should perhaps have read str = this.str.concat(str2);
, or simply str += str2
?
But since the statement new MyString("A").concat("B"); is creating a new object...
Yes. A temporary String
("AB"
) is created internally as return value and thrown away.
...with string "AB", couldn't this object also be garbage collected resulting in output "AB" ?
No, because it creates a String
, not a MyString
. Strings print nothing in their finalizer (or any other method for that matter).
'AB' will not be the output because concatenation doesn't change the contents of 'str' . Concatenation only produces a new String 'AB' which is not assigned to anything and hence lost.
To produce AB as print, you will need to write System.out in the finalize method of String (hypothetically)
Output can be A when the current object is garbage collected and the str has been initialized to "A"
精彩评论