Demo class

public class Demo
{
    public static void main(String[] args)
    {
        /* code not yet run */ = new Coordinate2D(5, 6);
        /* more code not yet run */
    }
}

Java executes the code to the right of the assignment operator (=) first.

The code new Coordinate2D(5, 6) instantiates (constructs a new object/instance of) the Coordinate2D class.

Instantiating a class automatically calls one of the class’s constructors. In this case, the constructor with 2 parameters (shown below) is called. The values 5 and 6 are passed as arguments (sometimes called actual parameters).

All arguments in Java are passed by value. See Primitive types vs references exercises with method calls for more details.

Coordinate2D class

public class Coordinate2D
{
    private int x, y;

    // Other constructor not shown

    public Coordinate2D(int initX, int initY)
    {
        /* paused here */
        /* code not yet run */
    }

    // Additional methods not shown
}

The Coordinate2D constructor shown has 2 formal parameters initX and initY, both of type int. The values of the formal parameters are set to the values passed as arguments (5 and 6).

At the position labeled /* paused here */, the values of the instance variables x and y are both 0. Instance variables of type int default to 0.

Memory diagram

initX with value 5 and initY with value 6. Box containing x and y, each with value 0.

The diagram represents the object/instance of Coordinate2D as a box. Each object/instance of type Coordinate2D has its own copy of the instance variables x and y, shown inside the box.

The variables initX and initY are parameters. The scope of parameters (where they exist) is the method in which they are declared (in this case, a constructor).

Forward to Step 2
Back to main example