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)