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?
}
}
So, only 1 object is ever created because Java is pass-by-reference.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With