views:

56

answers:

2

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.concat(str2);
    }
    public static void main(String[] args) {
        new MyString("A").concat("B");
        System.gc();
    }
}
+7  A: 

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

aioobe
+2  A: 

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

Gaurav Saxena
Ok, since this.str.concat(str2) will create a seperate string in the memory "AB" its not the str in object MyString that refers to it. But if we had instead the statement this.str += str2; then the possibility of "AB" being printed in the finalize method will exist?
Yes, then the possibility exists
Gaurav Saxena