A stack frame that holds the local variables and parameters of a method invocation is the same as an object that holds the instance variables.


A stack frame is the same as an instance of a class


Here is what's right.

A stack frame indeed holds the local variables and parameters of a method. And an object indeed holds the instance variables of a class. However, those two things are not the same.

A stack frame exists only while its method executes. It is allocated when the method is called, and it is freed when the method returns. The purpose of the stack frame is to hold “temporary” data (data that is needed for the method to work).

An object can exist for a much longer time. The lifetime of an object is not connected to the lifetime of a method call. An object can be allocated (with new) at any time, and it will continue existing as long as it is still somehow reachable (as long as someone has a reference to it).

Take this example:

public class Pacman {
  int energy;
  int x;
  int y;

  public void move(int dx, int dy) {
    x += dx;
    y += dy;

The fields of an object hold the information that is relevant for that object. For example, for a Pacman, the fields might hold the pacman’s energy level, and its x and y position. The variables of a method, on the other hand, hold the temporary information the method needs to do its job. So, for the move(...) method, the stack frame might contain the x and y distance by which to move.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.