-2

Code blocks number 1.

public class SomeClass {
    public static void main(String [] args) {
        SomeClass foo = new SomeClass();
        foo.SomeMethod();
    }
    public void SomeMethod() {

    }
}

Code blocks number 2.

public class SomeClass {
    public static void main(String [] args) {
       new SomeClass().SomeMethod();
    }
    public void SomeMethod() {

    }
}

Are this two code blocks(number 1 and 2) the same? I'm confused over the different syntax during calling the method. I appreciate if someone could explain it for me.

Adam
  • 856
  • 2
  • 9
  • 18

2 Answers2

5

Yes, they are functionally the same. With code block 2, however, you have no way of accessing the SomeClass object you created in the future lifespan of the program.

Matthew Diana
  • 1,106
  • 7
  • 14
1

Yes they are same. In first case the object reference is just stored in a reference variable for future usage .
In second case the reference is not stored.

Sumit Kumar
  • 375
  • 1
  • 11