How to Create an Object in Java: 5 Ways with Syntax

Object creation in Java means instantiating a class to get a usable object in memory. The standard syntax is ClassName obj = new ClassName();, which allocates heap memory and calls the constructor. Java provides five ways to create objects: new keyword, reflection, clone(), deserialisation, and factory methods. Knowing all five is essential for interviews and framework work.

  • Java ranked 5th among all programming languages in the Stack Overflow Developer Survey 2024.
  • According to the TIOBE Index (April 2025), Java holds the fourth position among the most popular programming languages worldwide.
  • According to the 2024 JetBrains Developer Ecosystem Survey, 62% of Java developers use object-oriented design patterns daily in production code.
  • Every object in Java is an instance of a class, stored on the heap and referenced by a variable on the stack.
  • Getting object creation in Java right prevents the most common runtime errors, including NullPointerException and ClassCastException.

Creating a Class in Java

A class is the blueprint for object creation in Java. Before you can instantiate any object, you need a class that defines what data it holds and what it can do. If you have already learned how to write and compile a C program, you will find Java’s class structure more organised but equally readable.

Basic Class Syntax

Here is the minimal syntax for a Java class:

Part Syntax Purpose
Access modifier public Controls visibility of the class
Class keyword class Tells the compiler this is a class definition
Class name Student Identifier; must start with a capital letter by convention
Body { fields, constructors, methods } Contains all the class members

A concrete example: imagine you are building a student management system for a university like IIT Bombay or VIT Vellore. You would create a Student class with fields for roll number, name and branch. Java OOP is a core subject in BTech CSE and MCA programmes across India, and this kind of example appears in GATE CS preparation as well.

public class Student {
    int rollNumber;
    String name;
    String branch;

    // Constructor
    public Student(int rollNumber, String name, String branch) {
        this.rollNumber = rollNumber;
        this.name = name;
        this.branch = branch;
    }
}

The this keyword refers to the current instance during object instantiation in Java. It distinguishes between a field and a constructor parameter that share the same name. Forgetting this is one of the most common beginner mistakes, and the compiler will not always warn you.

How to Make a Class in Java: Practical Tips

Keep each class focused on one responsibility. A Student class should not also handle database connections. This single-responsibility habit makes your code easier to test and maintain, which matters the moment you join a real dev team at companies like TCS, Infosys or Wipro, where Java remains the dominant backend language.

According to Oracle’s official Java documentation, a class declaration can include modifiers, the class name, any superclass, any interfaces and the class body. Understanding each part stops you from writing classes that compile but behave unexpectedly at runtime.

Declaring and Creating Objects in Java

Object declaration in Java is a two-step process: you first declare a reference variable, then you instantiate the object and assign it. Many beginners write both steps on one line, which is fine, but knowing they are separate helps you understand NullPointerException when it hits.

What Is the Difference Between Object Declaration and Instantiation in Java?

Declaration creates a reference variable: Student s1; points to null and occupies no heap memory yet. Instantiation is the act of calling new, which triggers JVM heap memory allocation, runs the constructor, and returns a reference. Assigning that reference to s1 completes the object creation in Java.

Step 1 – Declare: Student s1;

Step 2 – Instantiate and assign: s1 = new Student(101, "Priya Sharma", "CSE");

Or on one line: Student s1 = new Student(101, "Priya Sharma", "CSE");

If you try to call a method on a declared-but-not-instantiated reference variable, Java throws a NullPointerException. Our guide to Java exceptions and common runtime errors covers exactly how to handle that.

What Happens in JVM Heap Memory When You Create an Object in Java?

When the JVM executes new Student(...), it performs three operations: it allocates a contiguous block of heap memory sized to hold all the object’s fields, it runs the constructor to initialise those fields, and it returns a memory address (the reference) that gets stored in your stack variable. The garbage collector tracks all heap-allocated objects and reclaims memory when no references remain. Understanding this JVM memory model is essential for writing performant Java code and for debugging memory leaks in large applications.

Accessing Object Fields and Methods

Once your object exists, you access its members using the dot operator:

  • s1.name reads the name field.
  • s1.display() calls the display method.
  • s1.rollNumber = 102; sets a field value directly (only works if the field is not private).

In production code, fields are almost always private and accessed through getter and setter methods. That is encapsulation, one of the four pillars of OOP and a guaranteed interview topic for BTech and MCA placements in India.

Five Ways to Create an Object in Java

Most tutorials stop at new. But Java gives you five distinct mechanisms for object creation in Java, each with a specific use case. Knowing all five is the difference between a junior who can write basic code and a developer who understands the frameworks they are using.

1. Using the new Keyword: Standard Object Instantiation in Java

This is the standard approach and covers 95% of everyday object creation in Java. Student s = new Student(101, "Arjun", "IT"); is all it takes. The constructor runs, JVM heap memory is allocated, and you are ready.

2. Using Reflection for Dynamic Object Creation in Java

Reflection lets you create objects at runtime without knowing the class name at compile time. Frameworks like Spring and Hibernate use this extensively.

Class<?> cls = Class.forName("Student");
Student s = (Student) cls.getDeclaredConstructor().newInstance();

This calls the no-argument constructor via newInstance(). Reflection is powerful but slower than new, so use it only when dynamic class loading is genuinely needed.

3. Using clone() to Copy an Existing Object

The clone() method creates a copy of an existing object. The class must implement the Cloneable interface, otherwise Java throws a CloneNotSupportedException.

Student s2 = (Student) s1.clone();

Be careful with shallow vs deep copy. If your object contains references to other objects, clone() copies the references, not the objects themselves. That is a common source of hard-to-find bugs.

4. Using Deserialisation for Object Creation in Java

Deserialisation reconstructs an object from a byte stream, typically one saved to a file or received over a network. The class must implement Serializable. This is how many Java-based APIs and distributed systems pass objects between services. It is also a known attack vector in cybersecurity, which is why secure coding practices matter. The CEH v13 AI online course covers insecure deserialisation as part of ethical hacking methodology.

5. Using Factory Methods to Encapsulate Object Creation

A factory method is a static method that returns an object of the class. You have already used this without realising it: String s = String.valueOf(42); is a factory method call. Factory methods hide the instantiation logic and are useful when creation is complex or when you want to return a subclass depending on the input. The getInstance() pattern in the Singleton design pattern is another example.

Comparison of All Five Object Creation Methods in Java

Method Calls Constructor? Relative Speed (vs new = 1x) Primary Use Case Interface Required?
new keyword Yes 1x (baseline) General object creation in Java No
Reflection Yes 3-5x slower (JMH benchmarks) Frameworks, dynamic class loading No
clone() No ~1.2x slower Copying existing objects Cloneable
Deserialisation No 10-50x slower (object-graph dependent) Restoring objects from byte streams Serializable
Factory method Yes (internally) ~1x (same as new) Encapsulated or conditional creation No

Declaring Methods in Your Class

A method declaration in Java follows this structure: accessModifier returnType methodName(parameters) { body }. For example: public void display() { System.out.println(name); }.

The return type tells the compiler what the method sends back. Use void when nothing is returned. The method name should be a verb or verb phrase: getMarks(), updateBranch(), calculateGPA(). Parameters are the inputs the method needs. Always validate inputs inside the method rather than trusting the caller to pass correct values.

If you are exploring the broader software development toolkit alongside Java, our guide to software development tools to learn first is a good companion read. And if you are weighing career paths after mastering Java fundamentals, check out the breakdown of full stack developer vs software developer roles to see where object-oriented skills fit.

Students in BSc Computer Science programmes typically encounter Java OOP and object creation in Java in their second semester. MCA students often revisit it during placement prep. Java is the dominant backend language at Indian IT services firms including TCS, Infosys and Wipro, and Naukri.com consistently lists Java developer as one of the top five most-posted tech roles in India. If you are curious about career outcomes, our article on jobs and salary after MCA shows how Java skills map to real roles and pay packages in India.

Frequently Asked Questions

How do I create an object in Java?

You create an object using the new keyword followed by the class constructor: ClassName obj = new ClassName();. This allocates memory on the JVM heap, runs the constructor, and returns a reference stored in your variable. It is the most common form of object creation in Java and works for any class you have defined or imported.

How many ways are there to create an object in Java?

There are five ways to create an object in Java: using the new keyword, using reflection via Class.forName() and newInstance(), using clone() to copy an existing object, using deserialisation to reconstruct an object from a byte stream, and using a factory method that encapsulates the creation logic. Each serves a different purpose in real-world Java development.

What is the syntax for object creation in Java?

The standard object creation syntax in Java is: ClassName variableName = new ClassName(arguments);. The left side declares a reference variable of the class type. The right side uses new to allocate heap memory and call the constructor with any required arguments. If the constructor takes no parameters, the parentheses are still required: new ClassName().

How do I create an object in Java without the new keyword?

You can create an object in Java without the new keyword using three methods: reflection (cls.getDeclaredConstructor().newInstance()), cloning (existingObj.clone()), or deserialisation (reading an object from an ObjectInputStream). Factory methods internally use new but hide it from the caller. Reflection and deserialisation are the most common approaches in frameworks that need to avoid direct constructor calls.

How do I declare a method in Java?

A method declaration follows this pattern: accessModifier returnType methodName(parameterList) { body }. For example, public int getMarks(String subject) is a public method that accepts a String and returns an int. The access modifier controls who can call the method, and the return type must match what the method actually returns, or the compiler will reject it.

How do I make a class in Java?

Use the class keyword followed by the class name and a pair of curly braces: public class Student { }. Inside the braces, you add fields (data), a constructor (initialisation logic) and methods (behaviour). By convention, class names start with a capital letter and the file name must match the public class name exactly, or Java will not compile it.

Where to go from here: you now have a complete picture of object creation in Java, from class design through all five instantiation methods. Take these three steps this week to solidify what you have learned.

  1. Write a Product class with at least three fields and a constructor, then instantiate it using all five object creation methods described above. Compile and run each version.
  2. Read the Oracle Java OOP tutorial section on classes and objects to see the official specification alongside your practice code.
  3. Explore 3.0 University’s online certification courses in Cybersecurity, Ethical Hacking, AI, Blockchain and Web3. Strong Java and OOP fundamentals are the foundation for secure coding, AI application development and blockchain smart contract logic. The CEH v13 AI online course is a practical next step if you want to apply your programming knowledge to ethical hacking and cybersecurity.

Last updated: May 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles