You can use jmap and jhat to get a JVM memory dump.
Adding a Thread.sleep(20000) comment to the comment will cause the program to wait 20 seconds to execute the following commands. If necessary, increase the waiting time.
On one command line, run your program:
java -cp . Car
On another command line, within 20 seconds of waiting, run
jps jmap -dump:file=C:/temp/x.dmp 99999 jhat C:/temp/x.dmp
Where 99999 is the process identifier specified in the jps output.
The jhat program starts the web server on port 7000 , so go to:
http://localhost:7000/
Click "Show instance instances for all classes (excluding platform)" and you will see only 2 objects:
2 instances of class Car
This is because you excluded the Exception class from the mapping.
If you click the link "... (including the platform)", you will see many objects with something like this:
Total of 6214 instances occupying 8071681 bytes.
If you implement your own exception, eq CarException and throw it instead, you will see 4 "user" objects:
2 instances of class Car 2 instances of class CarException
So what is the correct answer? 2, 4 or 6214?
The expected answer is probably 4, as in the section "How many objects did your program create?"
Regarding the question of whether objects were created only when using the new keyword, the answer would be No. There are many other ways (for example, listed in this answer: fooobar.com/questions/44483 / ... ), but here are a few, with a comment on the 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)