DEV Community

JEGADESHWARAN B
JEGADESHWARAN B

Posted on

Constructor in Java

What is constructor and its Purpose?

A constructor is a special method used to initialize an object.
It has the same name as the class.
It runs automatically when an object is created using the new keyword.

How it works internally?

When we use new, memory is allocated in the heap.
Instance variables first get default values (0, null, false).
Then the constructor executes and assigns the given values.

Real-World Usage

Constructors are used to ensure objects are properly initialized, for example setting user details or establishing database connections.

Method vs constructor

A constructor initializes an object, whereas a method performs operations.

Top comments (0)