CodeBlanks Logo Icon CodeBlanks

new

Learn to create objects with new.

Instantiation with new

Creating an object from a class is called instantiation. In Java the new keyword is used together with the class name and ends with parentheses. The operation creates a new instance in memory and returns a reference to it.

Example: Book b = new Book();. Here new Book() creates a new Book instance; the variable b holds a reference to it. You can create as many instances as you want from the same class; each one is independent and carries its own field values. Two instances' fields do not affect each other.

Multiple instances

You can create more than one instance from the same class. Each instance is independent; changing one's fields does not affect the other. Instances are held in separate variables.

Example: Book a = new Book(); Book b = new Book(); a.title = "Java"; b.title = "Python";. Here a and b are two separate Book instances. a.title and b.title hold different values. Even though both variables come from the same class, they occupy different memory locations and are independent.

Practice Create two book instances

Define a class named Book with a String title field. In main create two Book instances. Assign "Java" to the first one's title and "Python" to the second one's. Print both title fields on separate lines.

Starter code

Main.java
// Define the Book class
// Create two instances and print

Sample solution

Main.java
class Book {
    String title;
    public static void main(String[] args) {
        Book a = new Book();
        Book b = new Book();
        a.title = "Java";
        b.title = "Python";
        System.out.println(a.title);
        System.out.println(b.title);
    }
}

Expected output

Java
Python

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the instantiation expression

Question
Book b = ____;
Answer
Book b = new Book();

Explanation: new Book() creates a new instance.

2 Match the instantiation parts

Term Meaning
new Keyword
Book Class name
() Instantiation call
b Reference variable

3 Two Book instances are created. When a.title is changed, what happens to b.title?

  • b.title also changes
  • b.title stays the same Correct answer
  • b is deleted
  • A compile error occurs

Explanation: B.title stays the same — each instance is independent.

All lessons in Intermediate