2
class BooleanWrap{
    boolean b = new Boolean("true").booleanValue(); 
}

When I try to do the same with the code below, it doesn't work:

class TestCode  {
    public static void main(String[] ar)  {
        TestCode tc = new TestCode().go();
    }

    void go() {
        //some code
    }
}

Compile error:

TestBox.java:6: error: incompatible types TestBox t = new TestBox().go();

When I change the return type of method go() from void to class type, then I do not get the error anymore.

class TestCode2 {
    public static void main(String[] ar) {
        TestCode2 tc2 = new TestCode2().go();
    }

    TestCode2 go() {
        //some code
    }
}

What happens to the object I just created in above code (referenced by tc2)? Will it get abandoned?

Tom
  • 16,842
  • 17
  • 45
  • 54
Nandan747
  • 61
  • 2
  • 5

3 Answers3

3

TestCode tc = new TestCode().go() would only work if the go() method returns a TestCode, since you are assigning it to a variable of TestCode type.

In the case of TestCode2 tc2 = new TestCode2().go();, if the go() method returns a reference to a different instance of TestCode2 (i.e. not the one for which you called go()), the original instance won't be referenced anywhere and would be eligible for garbage collection. In other words, tc2 would refer to the instance returned by go(), which doesn't have to be the same instance as the one created in the main method with new TestCode2().

Eran
  • 387,369
  • 54
  • 702
  • 768
  • yeah, and what about the object? since the only reference variable it was referenced by, now refers some other object. – Nandan747 Jan 31 '15 at 08:17
  • @user1851607 the variable tc2 never referred to the instance created by `new TestCode2()`. It referred only to the instance returned by `go()`. – Eran Jan 31 '15 at 08:18
3

This should work just fine:

class TestCode{
    public static void main(String[] ar){
        new TestCode().go();
    }

    void go() {
        System.out.println("Hello World");
    }
 }

Edit: Additional info

This way you can't save the created instance. It will get destroyed right away in the next garbage collection. So normally, to avoid this unneccessary creation and destruction a static method would be used if the instance itself is not needed.

class TestCode{
    public static void main(String[] ar){
        TestCode.go();
    }

    static void go() {
        System.out.println("Hello World");
    }
 }
Torge
  • 2,174
  • 1
  • 23
  • 33
1

As Eran said, the method go() returns nothing, and you're trying to assing that nothing to a variable, your method needs to return something, a TestCode object in this case