Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine number of objects created in Java [duplicate]

Tags:

java

Are objects created only when the new keyword is used? How many objects have been created once this code reaches the comments? I am saying 4 new objects because the constructor calls new Exception() each time a Car is initialized. How do I verify the number of objects created?

class Car {
    Car() {
        try {
            throw new Exception();
        } catch (Exception ex) {
            System.out.println("Do Nothing");
        }
    }
}

class Test {
    public static void main(String[] args) {
        Car carOne = new Car();
        Car carTwo = new Car();
        Car carThree = carTwo;
        // how many objects have been created? 4?
    }
}
like image 317
Jonathan Kittell Avatar asked Dec 18 '15 23:12

Jonathan Kittell


People also ask

How many objects are created in Java?

So, only 1 object is ever created because Java is pass-by-reference.

Which variable are usually used to keep a count of number of objects created from a class?

We can keep track of the number of objects that have been created in a class using a static variable. Because a static variable is linked to a class and not to an object, it is perfect to create a static variable to keep track of the number of objects created.


1 Answers

There is no (at least not to my knowledge) automatized way of counting how many objects were created in java. In your example, however, there are 4 objects being created, 2 Exceptions and two Cars.

If you wish to count how many objects are for a given class, you can have a static counter that is incremented each time an object is created.

Edit: you can count created objects using jmap, as pointed out by Andreas, although it is a not very practical solution

like image 187
Gabriel Ilharco Avatar answered Nov 15 '22 07:11

Gabriel Ilharco