-3

I know that there is memory allocation when we create an object of a class as follows:

Test t = new Test(); t.method1();

But I can call mehtod1 as follows too:

new Test().method1();

So, in the second of way calling the method1, is there memory allocated. because apparently I am not creating an object here.

Thanks

  • 5
    Apparently you **are** creating an object. You're just not assigning it to a variable, but an object is created by the new call on the constructor just the same. – Hovercraft Full Of Eels Dec 02 '17 at 23:38
  • 1
    The `new` operator allocates memory, and you're still using `new`. If it didn't allocate memory, what do you think `this` references inside the `method1` method? – Andreas Dec 02 '17 at 23:40
  • You're not calling classes but methods of classes. The only methods you can call without creating objects are static methods. – Lothar Dec 02 '17 at 23:45

1 Answers1

2

The answer to your question is yes. The code new Test() creates an object, which happens to be an instance of the Test class. Memory is allocated on the heap for every object that you create, whether you assign it to a variable or not.

Of course, like all memory on the heap, that memory is available for garbage collection as soon as there's no reference to that object anywhere in scope. If you don't assign it to a variable, then the reference created by the expression new Test() goes out of scope as soon as it's used. This means the memory might get garbage collected quite quickly. But it's certainly allocated.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110