For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
In Java, object creation is one of the most fundamental concepts that powers the language's object-oriented nature. Every time you create an instance of a class, you're creating an object. Understanding how objects are created helps you write efficient, maintainable, and dynamic code.
In this blog, we will explore all the ways of object creation in Java programming, break down what happens behind the scenes, and provide code examples to make it easy for beginners and intermediate learners.
Want to master Java and build real-world applications? Explore upGrad's Software Engineering course and level up your coding career.
An object is a class instance that contains state (fields/variables) and behavior (methods). While a class is just a blueprint, an object is a real entity created in memory using that blueprint.
For example:
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving...");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // 'myCar' is an object
myCar.drive();
}
}
Output:
Car is driving...
Explanation:
In the example, myCar is an object of the Car class created using the new keyword. It has access to the class members, so calling myCar.drive() prints "Car is driving..." to the console.
Looking to combine your Java skills with data science? Enroll in the Executive Diploma in Data Science & AI by IIIT-B and upGrad to future-proof your career.
When creating an object using the new keyword, Java follows three essential steps:
This step creates a reference variable that can point to an object of a specific class type.
Car myCar;
Here, myCar is declared as a reference variable of type Car. At this point, it doesn’t point to any object in memory—just the name and type are known to the compiler.
This step uses the new keyword to create a new object in heap memory.
new Car();
The new keyword allocates memory for a new Car object. However, this object isn’t yet connected to a variable, so it’s not usable unless assigned to a reference.
This step calls the class constructor to initialize the object’s fields.
Car();
This is a call to the class constructor, which sets up the object with its initial state. It is executed automatically when new Car() is used.
Putting it all together
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving...");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Declaration + Instantiation + Initialization
myCar.drive();
}
}
All three steps are commonly combined in a single line:
Car myCar = new Car();
This sequence is the foundation of object-oriented programming in Java.
Want to integrate your Java skills with cloud and DevOps? Explore the Professional Certificate Program in Cloud Computing and DevOps to boost your backend and deployment expertise.
Java offers multiple approaches for creating objects, each suited to different scenarios and use cases. Understanding the various ways of object creation in Java is essential for writing flexible and efficient code, especially in advanced applications like frameworks or serialization.
This is the most direct and widely used way to create objects in Java. It involves using the new keyword, which handles instantiation and calls the constructor to initialize the object.
class Car {
void drive() {
System.out.println("Car is driving...");
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.drive();
}
}
Output:
Car is driving...
Explanation:
Here, car1 is created by combining declaration, instantiation, and initialization in a single line. The new keyword creates the object in memory, and the constructor sets it up for use.
This method creates a copy of an existing object in memory. The class must implement the Cloneable interface and override the clone() method. It’s useful when you need object duplication.
class Car implements Cloneable {
String color = "Blue";
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws Exception {
Car car1 = new Car();
Car car2 = (Car) car1.clone();
System.out.println(car2.color);
}
}
Output:
Blue
Explanation:
car2 is a cloned copy of car1. Both are separate objects in memory but have the same data. Without implementing Cloneable, this will throw CloneNotSupportedException.
Deserialization creates an object by reading its state from a file or byte stream. The class must implement Serializable and the object should be serialized before deserialization.
import java.io.*;
class Car implements Serializable {
String model = "Sedan";
}
public class Main {
public static void main(String[] args) throws Exception {
// Serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("car.ser"));
Car car1 = new Car();
out.writeObject(car1);
out.close();
// Deserialize
ObjectInputStream in = new ObjectInputStream(new FileInputStream("car.ser"));
Car car2 = (Car) in.readObject();
in.close();
System.out.println(car2.model);
}
}
Output:
Sedan
Explanation:
The object car1 is written to a file and then restored using deserialization. This technique is useful in saving and retrieving object states across sessions or systems.
This method dynamically loads the class by its name and creates an instance. It's part of the Reflection API but deprecated due to better alternatives. Suitable for frameworks or plugins.
class Car {
void start() {
System.out.println("Car started");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("Car");
Car car = (Car) cls.newInstance();
car.start();
}
}
Output:
Car started
Explanation:
This approach uses the fully qualified class name to create an object at runtime. However, newInstance() is deprecated and replaced by safer, more flexible alternatives like Constructor.newInstance().
This is a more flexible and preferred method in Reflection. It allows invoking any constructor (even parameterized ones) and provides better exception handling than Class.newInstance().
import java.lang.reflect.Constructor;
class Car {
public Car() {
System.out.println("Car object created using Constructor.newInstance()");
}
void display() {
System.out.println("Display method called");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Constructor<Car> constructor = Car.class.getConstructor(); // No-arg constructor
Car car = constructor.newInstance(); // Create object using reflection
car.display();
}
}
Output:
Car object created using Constructor.newInstance()
Display method called
Explanation:
This method uses Java Reflection to access the no-argument constructor of the Car class. The constructor must be explicitly declared as public. This method is flexible and widely used in frameworks for runtime object creation.
Method | Simplicity | Use Case | Reflection Needed | Common Usage |
new Keyword | High | General-purpose programming | No | Very common |
clone() | Medium | Duplicating existing objects | No | Limited |
Deserialization | Low | Restoring from file/stream | No | Niche (e.g., I/O) |
Class.forName().newInstance() | Medium | Dynamic class loading | Yes | Deprecated |
Constructor.newInstance() | Medium | Frameworks, tools | Yes | Common in frameworks |
Java offers various ways to create objects, each with its own use case. While the new keyword is the most straightforward and commonly used method, others like cloning, deserialization, and reflection are useful in specialized scenarios. Understanding these methods can help you write more dynamic and flexible Java code.
Object creation in Java is the process of instantiating a class to form a usable object in memory. It involves declaring a reference, allocating memory using the new keyword, and initializing it through a constructor, allowing access to class properties and methods.
Java provides five main ways to create objects: using the new keyword, clone() method, deserialization, Class.forName().newInstance() (deprecated), and Constructor.newInstance() via Reflection. Each method serves specific use cases, ranging from basic instantiation to advanced dynamic object creation.
Object creation in Java typically involves three steps: Declaration (declaring a reference variable), Instantiation (allocating memory with new), and Initialization (calling the constructor to set initial values). These steps together create a usable object instance in memory.
The most commonly used and recommended method is using the new keyword. It clearly shows intent, directly calls the class constructor, and is widely supported, making it suitable for most object creation scenarios in Java applications.
Yes, Java allows object creation without the new keyword using methods like clone(), deserialization, and reflection-based approaches such as Class.forName() and Constructor.newInstance(). These are often used in advanced scenarios like frameworks and object restoration.
Cloning creates a copy of an existing object in memory. It requires the class to implement the Cloneable interface and override the clone() method. This is useful for duplicating objects without creating new instances from scratch.
Class.newInstance() is deprecated because it lacks proper exception handling, supports only no-argument constructors, and provides limited flexibility. It has been replaced by Constructor.newInstance() which offers more robust object creation through reflection and better exception management.
Constructor.newInstance() allows creating objects at runtime using reflection. It supports both default and parameterized constructors, making it a powerful tool for dynamic object creation in frameworks, tools, or dependency injection mechanisms.
Deserialization recreates an object from a byte stream, typically read from a file or network. It restores the object’s state exactly as it was during serialization, without calling constructors. It’s useful for saving and retrieving object data.
Deserialization can pose serious security risks, especially if the byte stream comes from an untrusted source. It can lead to unauthorized object manipulation or remote code execution if not properly validated and secured in enterprise applications.
Use the new keyword for most scenarios as it’s safe and simple. Choose cloning for duplicating existing objects, deserialization for restoring object state, and reflection-based methods when dynamic instantiation is necessary, such as in frameworks or libraries.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.