In Java, objects are created using the new keyword. First, we define a class, which serves as a blueprint for creating objects. When using the new keyword to instantiate a class, the Java Virtual Machine (JVM) allocates heap memory for the object and invokes the constructor to initialize it.
For example, consider a class named Person:
javapublic class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } }
We can create an instance of the Person class as follows:
javaPerson person = new Person("John Doe", 30);
In this case, the new Person("John Doe", 30) expression first allocates heap memory for the Person object, then invokes the constructor of the Person class, passing "John Doe" and 30 as arguments to initialize the object.