Creating Objects Using the new Keyword in Java
Course: Core Java Training
Topic: Creating Objects Using the new Keyword
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Object Creation in Java
Java is an object-oriented programming language in which classes define the structure and behavior of objects. To work with an object, a program typically creates an instance of a class and accesses its members through a reference variable.
The new keyword is commonly used to create objects in Java. When an expression such as new Student() is evaluated, Java creates a new instance, initializes its fields, and invokes the appropriate constructor.
For example, a Student class can define information such as a student's name, age, and roll number. By creating multiple Student objects, a program can represent multiple students independently.
Basic Syntax
ClassName referenceName = new ClassName();
In this statement:
ClassName is the type of object being created.
referenceName is a variable that can hold a reference to the object.
new is the keyword used to create a new instance.
ClassName() invokes the class's no-argument constructor.
2. Understanding the new Keyword
The new keyword is used to create class instances and arrays. When creating an ordinary class object, the expression generally performs these operations:
- Requests creation of a new object instance.
- Initializes its instance fields to their default values, such as
0 for numeric fields, false for boolean fields, and null for reference fields.
- Executes the relevant instance initialization steps and constructor logic.
- Produces a reference to the created object if construction completes successfully.
If construction fails because the constructor throws an exception, the expression does not produce a usable reference to the newly created object.
Example
class Student {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "Aarav";
student.age = 20;
System.out.println(student.name);
System.out.println(student.age);
}
}
Output:
Aarav
20
In this example, new Student() creates a Student object. The reference variable student allows the program to access the object's fields.
3. Understanding Classes, Objects, and References
To understand object creation, it is important to distinguish a class, an object, and a reference variable.
| Concept |
Meaning |
Example |
| Class |
A blueprint that defines members and behavior |
class Student { } |
| Object |
An instance created from a class |
An instance created by new Student() |
| Reference variable |
A variable that can refer to an object |
Student student |
| Constructor |
A special member used to initialize a new instance |
Student() |
A reference variable is not the object itself. It stores a reference that can be used to access the object. Multiple reference variables can refer to the same object.
Example of a Reference Variable
class Car {
String brand;
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.brand = "Toyota";
System.out.println(car.brand);
}
}
Output:
Toyota
The variable car refers to the object created by new Car(). The expression car.brand accesses that object's brand field.
4. Step-by-Step Process of Creating an Object
Consider the following statement:
Student student = new Student();
The process can be understood in three main stages.
Step 1: Declare the Reference Variable
Student student;
This declares a local reference variable named student. Because it is a local variable, Java requires it to be assigned a value before it is read or used.
Step 2: Create the Object
new Student();
This expression creates a Student instance and invokes the appropriate constructor. If the constructor completes successfully, the expression produces a reference to the new object.
Step 3: Assign the Reference
student = new Student();
The reference to the new object is assigned to the variable student. The program can now use this reference to access accessible fields and methods.
Combined Example
class Student {
String name;
void display() {
System.out.println("Student name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student student;
student = new Student();
student.name = "Meera";
student.display();
}
}
Output:
Student name: Meera
5. Creating Objects with a No-Argument Constructor
A no-argument constructor is a constructor that takes no parameters. If a class does not declare any constructor, Java normally supplies a default no-argument constructor. If the class declares another constructor, Java does not automatically provide the default constructor.
Example
class Employee {
String name;
int employeeId;
Employee() {
name = "Unknown";
employeeId = 0;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Employee ID: " + employeeId);
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee();
employee.display();
}
}
Output:
Name: Unknown
Employee ID: 0
The constructor initializes the fields with application-specific values instead of leaving them at their default values.
6. Creating Objects with a Parameterized Constructor
A parameterized constructor accepts values that are used to initialize an object. This is useful when an object needs specific information at the time it is created.
Example
class Product {
String productName;
double price;
Product(String productName, double price) {
this.productName = productName;
this.price = price;
}
void display() {
System.out.println("Product: " + productName);
System.out.println("Price: " + price);
}
}
public class Main {
public static void main(String[] args) {
Product product = new Product("Laptop", 55000.0);
product.display();
}
}
Output:
Product: Laptop
Price: 55000.0
The expression new Product("Laptop", 55000.0) invokes the constructor that accepts a String and a double. The this keyword refers to the current object and distinguishes its fields from the constructor parameters.
7. Creating Multiple Objects from the Same Class
A class can be used to create many objects. Each object generally has its own set of instance fields, so the state of one object can differ from the state of another.
Example
class Mobile {
String brand;
double price;
void display() {
System.out.println(brand + " - " + price);
}
}
public class Main {
public static void main(String[] args) {
Mobile mobile1 = new Mobile();
mobile1.brand = "Samsung";
mobile1.price = 25000;
Mobile mobile2 = new Mobile();
mobile2.brand = "Apple";
mobile2.price = 70000;
mobile1.display();
mobile2.display();
}
}
Output:
Samsung - 25000.0
Apple - 70000.0
Both objects belong to the Mobile class, but each stores its own brand and price. Updating the fields of mobile1 does not automatically update mobile2.
8. Creating Objects and Calling Methods
Methods define the behavior of objects. After creating an object, a program can call its accessible instance methods through a reference variable.
Example
class Calculator {
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum = calculator.add(10, 5);
int product = calculator.multiply(10, 5);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
Output:
Sum: 15
Product: 50
The expression new Calculator() creates the object. The reference variable calculator is then used to call the add() and multiply() methods.
9. Understanding Object References
Java reference variables can refer to objects. Assigning one reference variable to another copies the reference value; it does not automatically create a copy of the object.
Example: Two References to One Object
class Box {
int size;
}
public class Main {
public static void main(String[] args) {
Box box1 = new Box();
box1.size = 10;
Box box2 = box1;
box2.size = 25;
System.out.println(box1.size);
System.out.println(box2.size);
}
}
Output:
25
25
Both box1 and box2 refer to the same Box object. Changing the object's size through box2 is therefore visible when reading it through box1.
Example: Two Separate Objects
Box box1 = new Box();
Box box2 = new Box();
box1.size = 10;
box2.size = 25;
System.out.println(box1.size);
System.out.println(box2.size);
Output:
10
25
In this example, each call to new Box() creates a separate object. The two objects maintain independent instance-field values.
10. The Role of null in Object References
The value null means that a reference variable does not currently refer to an object. A reference can be initialized to null and later assigned a reference to an object.
Example
class Student {
String name;
}
public class Main {
public static void main(String[] args) {
Student student = null;
student = new Student();
student.name = "Riya";
System.out.println(student.name);
}
}
Output:
Riya
The program first assigns null to the reference and later assigns a newly created Student object to it. Attempting to access an instance field or call an instance method through a null reference causes a NullPointerException.
Example of a NullPointerException
Student student = null;
System.out.println(student.name);
This code throws a NullPointerException because student does not refer to an object when the field is accessed.
11. Object Creation and Default Field Values
When an object is created, its instance fields are initially assigned default values before constructor initialization is completed. The defaults depend on the field type.
| Field Type |
Default Value |
| byte, short, int, long |
0 |
| float, double |
0.0 |
| char |
'\u0000' |
| boolean |
false |
| Reference types, including String |
null |
These defaults apply to instance fields and static fields. Local variables inside methods do not receive automatic default values that can be read; they must be definitely assigned before use.
Example
class Demo {
int number;
boolean active;
String message;
}
public class Main {
public static void main(String[] args) {
Demo demo = new Demo();
System.out.println(demo.number);
System.out.println(demo.active);
System.out.println(demo.message);
}
}
Output:
0
false
null
12. Creating Objects Using Different Reference Types
A reference variable's declared type determines which members can be accessed directly at compile time. The actual object created determines the runtime implementation used for overridden instance methods.
Example: Superclass Reference
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
void fetch() {
System.out.println("Dog fetches a ball");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}
Output:
Dog barks
The variable animal has the declared type Animal, but it refers to a Dog object. The overridden sound() method in Dog executes at runtime. The method fetch() cannot be called directly through animal without an appropriate type conversion because it is not declared in Animal.
13. Creating Objects Inside Methods
Objects can be created inside methods, constructors, and other valid execution contexts. A method may use a newly created object locally and return it or pass it to another method.
Example
class Message {
void show() {
System.out.println("Welcome to Java");
}
}
public class Main {
static void displayMessage() {
Message message = new Message();
message.show();
}
public static void main(String[] args) {
displayMessage();
}
}
Output:
Welcome to Java
The Message object is created inside displayMessage(). When the method finishes, its local reference variable goes out of scope. If no reachable references to the object remain, the object may later become eligible for garbage collection.
14. Creating Objects in Arrays
An array can store multiple object references of the same declared reference type. Creating an array of a class type does not automatically create an individual object for every element. Each element initially contains null unless assigned a reference.
Example
class Student {
String name;
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Aarav");
students[1] = new Student("Meera");
students[2] = new Student("Riya");
for (Student student : students) {
System.out.println(student.name);
}
}
}
Output:
Aarav
Meera
Riya
The expression new Student[3] creates an array that can hold three Student references. Each expression new Student(...) separately creates a Student object.
15. Creating Objects Using Factory Methods
Although the new keyword is the common way to create objects directly, Java programs can also obtain objects through factory methods. A factory method is a method that creates or returns an object and can hide construction details from the calling code.
Example
class User {
private String username;
private User(String username) {
this.username = username;
}
public static User createUser(String username) {
return new User(username);
}
public void display() {
System.out.println("Username: " + username);
}
}
public class Main {
public static void main(String[] args) {
User user = User.createUser("student01");
user.display();
}
}
Output:
Username: student01
The calling code uses createUser() rather than directly invoking the private constructor. The factory method itself uses new User(...) to create the instance.
16. Difference Between Object Creation and Reference Assignment
| Statement |
Effect |
Student s = new Student(); |
Creates a Student object and assigns its reference to s. |
Student s; |
Declares a local reference variable but does not create an object. |
s = null; |
Assigns null to s; it does not create an object. |
Student s2 = s1; |
Copies the reference stored in s1; it does not create a new Student object. |
new Student[5] |
Creates an array of five Student references, not five Student objects. |
new Student("Aarav") |
Creates a Student object using the matching constructor. |
17. Common Errors When Using the new Keyword
| Error |
Cause |
Solution |
| Cannot find symbol |
The class name is misspelled or unavailable in the current scope. |
Check the class name, declaration, imports, and package. |
| Constructor cannot be applied |
No accessible constructor matches the supplied arguments. |
Use the correct constructor signature or define an appropriate constructor. |
| NullPointerException |
A member is accessed through a null reference. |
Ensure the reference points to a valid object before accessing members. |
| Non-static method referenced from a static context |
An instance method is called without an object reference from a static context. |
Create an object and call the method through that object, or redesign the method if it genuinely belongs at class level. |
| Local variable might not have been initialized |
A local reference variable is used before it has been assigned. |
Assign a valid reference or null before using the variable, as appropriate. |
| Cannot instantiate abstract class |
An attempt is made to create an instance directly from an abstract class. |
Create an instance of a concrete subclass instead. |
| Cannot instantiate interface |
An attempt is made to instantiate an interface directly. |
Create an instance of a class that implements the interface. |
18. Best Practices for Object Creation
- Initialize objects into a valid state by using suitable constructors.
- Prefer meaningful variable names such as student, employee, or account instead of generic names.
- Use private fields when direct external modification is not intended.
- Validate constructor arguments where invalid values could break the object's rules.
- Avoid creating unnecessary objects repeatedly when an existing object can be reused safely.
- Use factory methods when they improve clarity, encapsulate creation logic, or control which implementation is returned.
- Check for null when a reference may legitimately be absent.
- Remember that assigning one reference to another does not copy the underlying object.
- Do not rely on garbage collection to run at a particular time.
- Use interfaces or abstract types for references when doing so improves flexibility and reduces coupling.
19. Practice Exercises
- Create a Book class with title, author, and price fields. Create an object using the new keyword and display its details.
- Create an Employee class with a parameterized constructor that initializes employee ID, name, and salary.
- Create two Car objects and assign different brands and prices to each object.
- Create a Calculator object and call methods for addition, subtraction, multiplication, and division.
- Declare a reference variable and initialize it to null. Then create an object and assign its reference to the variable.
- Create two reference variables that point to the same object and demonstrate how a change through one reference is visible through the other.
- Create an array of three Student references and initialize each element with a separate Student object.
- Create an abstract class and demonstrate why it cannot be instantiated directly.
- Write a factory method that returns a configured object of a class.
- Explain the difference between creating an object and creating an array of object references.
20. Interview Questions and Answers
Q1. What is the purpose of the new keyword in Java?
Answer: The new keyword is commonly used to create class instances and arrays. For class instances, it invokes a constructor and produces a reference to the newly created object when construction completes successfully.
Q2. What is the syntax for creating an object?
Answer: A common syntax is ClassName referenceName = new ClassName();. The expression creates the object, and the reference variable holds the resulting reference.
Q3. Does declaring a reference variable create an object?
Answer: No. A declaration such as Student student; declares a reference variable. An object is created separately, for example, by using new Student().
Q4. Can multiple reference variables point to the same object?
Answer: Yes. Assigning one reference variable to another copies the reference. Both variables can then refer to the same object.
Q5. Does new Student[5] create five Student objects?
Answer: No. It creates an array that can store five Student references. Each Student object must be created separately if needed.
Q6. What happens when an object is created?
Answer: Java creates the instance, initializes its fields to default values, performs the applicable initialization steps, and invokes the selected constructor. If construction completes successfully, the expression produces a reference to the object.
Q7. What is the difference between a default and a parameterized constructor?
Answer: A no-argument constructor takes no parameters. A parameterized constructor accepts arguments to initialize an object with specific values. Java supplies a default no-argument constructor only when no constructor is declared.
Q8. Can we create an object of an abstract class?
Answer: No. An abstract class cannot be instantiated directly. A concrete subclass can be instantiated instead.
Q9. Can we create an object of an interface using new?
Answer: An interface cannot be instantiated directly. A concrete class that implements the interface can be instantiated and assigned to an interface reference.
Q10. What is a NullPointerException?
Answer: It is a runtime exception that occurs when code performs an operation requiring an object through a null reference, such as accessing an instance field or calling an instance method.
Q11. What does this do: Student s2 = s1?
Answer: It copies the reference stored in s1 into s2. It does not create a new Student object or automatically copy the object's fields.
Q12. Can object creation fail?
Answer: Yes. For example, a constructor can throw an exception, or the runtime may be unable to allocate the required memory. A failed construction does not produce a usable reference to the new instance.
21. Quick Revision Checklist
- The new keyword is commonly used to create class objects and arrays.
- A class defines the structure and behavior of its instances.
- A reference variable stores a reference to an object, not the object itself.
- Constructors initialize new instances.
- Fields receive default values before constructor initialization.
- Multiple objects from the same class can maintain different instance-field values.
- Multiple references can point to the same object.
- Assigning one reference to another does not clone the object.
- An array of object references does not automatically create an object for every element.
- Interfaces and abstract classes cannot be instantiated directly.
- Accessing instance members through null can cause a NullPointerException.
- Good constructors and validation help keep objects in valid states.
22. Conclusion
The new keyword is a fundamental part of Java object creation. It allows programs to create class instances, invoke constructors, and obtain references that can be used to access object behavior and state. Understanding the difference between classes, objects, references, constructors, and arrays is essential for writing reliable object-oriented Java programs.
Practice creating objects with no-argument and parameterized constructors, creating multiple instances, assigning references, and calling methods. These skills provide a strong foundation for more advanced Core Java topics such as inheritance, polymorphism, interfaces, collections, and object-oriented application design.
23. Further Learning Resources
Core Java Training Course: Explore Core Java Training
Course Demo Registration: Register for a Course Demo
JustAcademy Website: Visit JustAcademy