0
0
JavaHow-ToBeginner · 3 min read

How to Create Object in Java: Syntax and Examples

In Java, you create an object by using the new keyword followed by a class constructor, like ClassName obj = new ClassName();. This allocates memory and initializes the object so you can use it in your program.
📐

Syntax

To create an object in Java, you use the new keyword followed by the class name and parentheses. This calls the class constructor to make a new instance.

  • ClassName: The name of the class you want to create an object from.
  • obj: The variable that will hold the reference to the new object.
  • new: Keyword that creates the object in memory.
  • (): Parentheses call the constructor method.
java
ClassName obj = new ClassName();
💻

Example

This example shows how to create an object of a simple Car class and use it to call a method.

java
public class Car {
    String color;

    // Constructor
    public Car(String color) {
        this.color = color;
    }

    // Method to display car color
    public void displayColor() {
        System.out.println("Car color is: " + color);
    }

    public static void main(String[] args) {
        // Create a Car object
        Car myCar = new Car("red");

        // Use the object
        myCar.displayColor();
    }
}
Output
Car color is: red
⚠️

Common Pitfalls

Beginners often forget to use the new keyword or confuse the class name with the object name. Another mistake is not calling a constructor properly or missing parentheses.

Wrong: Car myCar = Car(); (missing new)
Right: Car myCar = new Car();

Also, trying to use an object before creating it causes errors.

java
/* Wrong way - missing 'new' keyword */
// Car myCar = Car(); // This will cause a compile error

/* Right way */
Car myCar = new Car();
📊

Quick Reference

StepDescriptionExample
1Declare a variable of the class typeCar myCar;
2Use 'new' keyword to create the objectmyCar = new Car();
3Call constructor with parameters if needednew Car("blue");
4Use the object to access methods or fieldsmyCar.displayColor();

Key Takeaways

Use the 'new' keyword with a class constructor to create an object in Java.
The object variable holds a reference to the created object in memory.
Always include parentheses after the class name to call the constructor.
Forgetting 'new' or parentheses causes compile-time errors.
Create the object before using its methods or fields.