6

To create a new object from a class Student in Java we use normally the following statement

Student std = new Student();

I've read that the new operator creates the new object by allocating memory space in the heap, however I read also that the calling constructor Student() creates it. So, its kind of confusing. Which one is creating the object std? Is it the new operator or the default constructor?

4
  • 1
    new just tells the compiler to create instructions for instantiating an object, not really an operator. Commented Dec 10, 2014 at 17:39
  • How about some JLS? Commented Dec 10, 2014 at 17:40
  • 8
    new Student() invokes the constructor. The two things you're asking about are actually the same thing. Commented Dec 10, 2014 at 17:42
  • More or less, new allocates the memory; the constructor initializes the object. Commented Dec 10, 2014 at 18:50

1 Answer 1

6

It's legal (though confusing) to have a method with the same name as the class, new removes any ambiguity. new indicates that the JVM should invoke the instance initialization method for the given class and argument list, and return the initialized object (referenced in the first (hidden) parameter of the initialization method).

The designers of Java could probably have found an alternative syntax, but they had a design goal that any time memory was allocated on the heap it should be called out explicitly by requiring the keyword new. This probably seems weird now but most of Java's target audience was C and C++ programmers who were suspicious of garbage collection, this was meant to make sure developers didn't have memory allocated without their knowledge.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.