0

In Java if i use String str = new String("test); 10 times, will it create an object 10 times in heap memory?

Or a reference is returned every time? Till now i have studied that new always creates a new object.

Curio
  • 1,331
  • 2
  • 14
  • 34
  • 2
    `new` creates an object. Always. – JB Nizet Jun 02 '17 at 16:46
  • From documentation : **Instantiating a Class** The `new` operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. – Youcef LAIDANI Jun 02 '17 at 16:50

2 Answers2

1

It will create 10 objects in memory.

Each time you call new operator, it gives you a pointer to object in heap. When you let go of that reference, it's garbage-collected.

ricardofagodoy
  • 146
  • 1
  • 10
0

I believe you'll get 10 different references to different objects.

Ryan D
  • 1,023
  • 11
  • 16