Java Interview Question

Use this advanced question and answer to prepare for your next Java interview.

Analyze the following code and explain what parts of the code will be stored in the Heap and what parts will be stored in the Stack at each line:

public static void main(String...args) {
  int x = 5;
  MyObject my = new MyObject();
  System.out.println(“Value of x: ” + x);

private void print(final MyObject my) {

Before the main method is called, the program allocates Heap space and puts all the runtime classes and class-level objects into the Heap.

Line 1 - Creates stack space for the main method. The String arguments are in the Heap in the PermGen area, while references to the strings are stored in the Stack.

Line 2 - Puts the primitive x on the Stack.

Line 3 - Creates MyObject on the Heap and stores reference my on the Stack.

Line 4 - Creates a String in PermGen.

Line 6 - Allocates a new block on the top of the Stack for method print and stores the reference for MyObject my in the new Stack again. This is because Java is Pass-by-Value.

Line 7 - Creates a new String in Permgen.

Looking for developers?