7

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?
    }
}
Jonathan Kittell
  • 7,163
  • 15
  • 50
  • 93
  • 2
    Is this homework? I've seen this on exams before... – Willem Van Onsem Dec 18 '15 at 23:07
  • 3
    `new` isn't the only way to create objects and therefore isn't a reliable counter: http://stackoverflow.com/questions/95419/what-are-all-the-different-ways-to-create-an-object-in-java In your case it works though, yes 4 objects are created here. – MC10 Dec 18 '15 at 23:13
  • The exception will probably create a stack trace internally, which may create an arbitrary number of stack trace elements... – Louis Wasserman Dec 19 '15 at 00:00

2 Answers2

8

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

Gabriel Ilharco
  • 1,649
  • 1
  • 21
  • 34
8

You can use jmap and jhat to get a memory dump of the JVM.

Adding a Thread.sleep(20000) at the comment will make the program wait 20 seconds for you to execute the following commands. Increase wait time if needed.

In one command prompt, run your program:

java -cp . Car

In a different command prompt, during the the 20 second wait, run

jps
jmap -dump:file=C:/temp/x.dmp 99999
jhat C:/temp/x.dmp

Where 99999 is the process id listed in the output from jps.

The jhat program starts a web server on port 7000, so go to:

http://localhost:7000/

Click on "Show instance counts for all classes (excluding platform)", and you'll see 2 objects only:

2 instances of class Car

That is because you excluded the Exception class from display.

If you clicked on the "... (including platform)" link, you'd see a lot of objects, with something like this:

Total of 6214 instances occupying 8071681 bytes.

If you implement your own exception, e.q. CarException and throw that instead, you'll see 4 "user" objects created:

2 instances of class Car
2 instances of class CarException

So, which answer is correct? 2, 4, or 6214?
Likely the expected answer is 4, as in "How many object did your program create?".


As for question of whether objects are only created when the new keyword is used, the answer is No. There are many other ways (e.g. listed in this answer: https://stackoverflow.com/a/2103578/5221149), and here are a few, with comment for number of objects created by the construct:

// Using "new"
new MyObject()      // 1 + number of objects created by constructor
new int[0]          // 1
new int[10]         // 1
new int[] {1,2,3,4} // 1
new int[10][]       // 1
new int[10][20]     // 11 (1 outer array + 10 inner arrays)

// Not using "new"
int[] x = {1,2,3,4} // 1
Integer x = 1       // 1  <-- autoboxing
printf("", i, j)    // 3 (autobox of i + autobox of j + varargs array)
String x = "a" + i  // 3 (StringBuilder + String + array backing String)
Integer[][] x = {{1111},{2222},{3333,4444},{},{}} // 10 (1 outer array + 5 inner arrays + 4 Integers)
Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247