Object-Oriented Programming with Java · Lecture Notes

Chapter 4.1: Objects and Classes

The programs so far consisted of static methods and the variables passed to them. The data lived in one place and the code that processed it in another. Object-oriented programming brings the two together: a student's name, number and grade average live in the same unit as the methods that work on them. The blueprint for such a unit is a class; each concrete instance produced from the blueprint is an object. These notes show step by step how a class is written, what happens in memory when an object is created with new, and why a variable holds a reference to an object rather than the object itself. Instance and static members, initialization order, this and constructor chaining, the difference between == and equals, wrapper classes, records, enum and inner classes are also covered. The notes end by designing a fraction class from scratch. All programs were compiled and run with JDK 21; the outputs, the final values in the trace tables and the compiler messages come from those runs.

Learning outcomes

Class and object
Explain a class as a blueprint and an object as a concrete instance made from it; write a class with fields and methods.
Creating objects
Use the new operator and constructors; know the default values of fields and the default constructor the compiler adds.
Instance and class members
Distinguish instance members from static members; trace the order in which initializer blocks and constructors run.
References
Show with a memory diagram that a variable holds a reference, not the object; explain the difference between this, == and equals.
Constructor chaining and access
Chain constructors with this(...); explain the purpose of access modifiers and data hiding.
Special kinds of classes
Recognize wrapper classes, records, the enum type and inner classes; design a class from scratch with the Rational example.

4.1.1Object-oriented programming

Imagine writing a student information system with static methods. Each student's name is kept in one array, the number in a second array and the grade average in a third. Methods such as computeAverage, registerCourse and printTranscript take these arrays as parameters. As the program grows, problems appear. Because the arrays are separate, only the index links the name of student 5 to the average of student 5. If one array is sorted and the other forgotten, names end up paired with other students' grades. Adding a new piece of information to a student, say the department, means a fourth array and new parameters to carry it. Every method that touches these arrays has to change.

Object-oriented programming answers this scattering with a different organization. All the information about a student is gathered in a single unit. The code that works on this information is written inside the same unit. The program is built from such units asking one another to do work.

Definition 4.1.1

Object-oriented programming (OOP) is a programming approach that builds a program from interacting objects. Each object carries its own data and offers operations that work on that data. Objects cooperate by calling one another's methods.

4.1.1.1Object: state and behavior

Every clearly distinguishable entity in the real world can be modeled as an object. A student, a desk, a circle, a button on the screen, even a loan taken from a bank is an object. Each of these objects has two things. The first is the object's state: the data it holds at that moment. A student's name, number and department make up the student's state. The second is the object's behavior: the things the object can do. A student can enroll in a course and view the grades. Table 4.1.1 puts the state and behavior of five objects side by side.

Table 4.1.1: Objects from the real world. State is represented by fields, behavior by methods.
ObjectFields (state)Behaviors
Studentname, id, departmentenroll(), viewGrades()
Desklength, width, materialmove()
Circlecenter, radiusarea(), perimeter()
Buttonlabel, color, enabledclick()
Loanamount, interest, termcomputeInstallment()

In a programming language the counterparts of state and behavior are clear. The pieces of data an object stores are called fields, and the things it can do are called methods. Objects get work done by calling one another's methods. In a school program, student, teacher and course objects "send messages" to one another in this way. A teacher object calls the enterGrade method of a course object; the course object then updates the student's record. Sending a message means calling an object's method in Java.

student1 : Studentname = "Ali"id = 2012dept = "EEE"greet()addCourse(name, grade)average()← fields← behavior (methods)
Figure 4.1.1: The student1 object. The upper part holds the fields and their current values, the lower part the object's methods. The data and the code that uses it are inside the same box.

Figure 4.1.1 draws the object student1 of type Student. The upper part of the box contains the fields name, id and dept with their values, and the lower part contains the methods greet(), addCourse(name, grade) and average(). The average() method takes no array parameter; the grades it needs are already inside the object. This togetherness of data and code makes the program better organized. The code becomes reusable, and because it resembles its real-world counterpart it is easier to understand.

4.1.1.2Procedural and object-oriented approaches

The programs so far were written in the procedural style. In this style the basic unit is the function. Data sits in separate variables and is passed as a parameter to every function that wants it. In the object-oriented style the basic unit is the object; data is stored inside the object and is exposed to the outside only through the paths the object allows. Table 4.1.2 compares the two approaches from five angles.

Table 4.1.2: Comparison of the procedural and object-oriented approaches.
Procedural approachObject-oriented approach
Basic unitFunction (method)Object (data + methods)
DataIn separate variables; every function can reach itInside the object; exposed to the outside in a controlled way
Examplearea(length, width)rect.area()
Large programsA change affects many functionsA change mostly stays inside one class
ReuseBy copying functionsBy using classes and inheritance

The "Example" row of the table shows the difference in the shortest way. In the procedural call the area method expects the length and width of the rectangle as parameters. The caller has to store these two numbers somewhere and pass them in the right order. In the object-oriented call the length and width are inside the rectangle object. The caller only says whose area it wants: rect.area().

Proceduralarea()perimeter()draw()width, height (data)Object-orientedrectw=5, h=3area() …squarew=4, h=4area() …
Figure 4.1.2: Left, the procedural layout: three functions reach the same shared data from outside. Right, the object-oriented layout: each object carries its own data (length, width) together with the methods that work on it.

The "Large programs" row states the real gain. On the left of Figure 4.1.2 three functions depend on the same data. If the form of the data changes, say corner coordinates are stored instead of length and width, all three functions must change. In the layout on the right the data is closed inside a class. A change of form affects the methods of that class; the code that uses the class goes on writing the area() call unchanged.

In Java all code is written inside a class. So the programs so far did have a class, but those classes were only containers holding static methods together; no object was ever made from them. In object-oriented programming classes do their real job: they produce objects.

4.1.1.3Three basic features

Three features set object-oriented languages apart from procedural ones. The subject of these notes is the class and the object themselves. Still, knowing from the start what the three features are for makes it easier to understand the decisions made when writing a class.

  • Encapsulation. An object can hide the details of its fields and behavior from other objects. To the outside it is like a closed box, used only through the methods it permits. The circuits inside a television are in a closed case; the user reaches only the buttons of the remote control.
  • Inheritance. A class can take over the fields and methods of another class. In this way common code is written once and classes are organized in a hierarchy.
  • Polymorphism. An object can be seen as more than one type. The same call produces different behavior on different objects. The call shape.area() computes πr² for a circle and a² for a square.

A fourth feature, abstraction, is often added to this trio. Abstraction means hiding unnecessary detail and showing only the important features. A BankAccount class models not all the properties of a real account but those useful to the program, for example the owner's name and the balance. The color of the door of the branch where the account was opened does not enter the model.

4.1.2Class and object

A factory produces thousands of cars of the same model. Every car has a color, a chassis number and an odometer, and these values vary from car to car. But all of them come from the same drawing: the drawing determines which parts there will be and how the engine will work. In Java the counterpart of this drawing is the class, and the counterpart of each car produced is the object.

4.1.2.1Class: the blueprint of an object

Definition 4.1.2

A class is the blueprint of an object. It defines the data (fields) the objects will carry and the operations (methods) they can perform. Any number of objects carrying different data can be produced from one class.

Definition 4.1.3

An object is an instance of a class: the concrete form, created in memory, of the structure the class describes. Each object carries its own copy of the fields the class defines.

The relationship between class and object is well explained by a cookie cutter. The cutter is made once and determines the shape of the cookie. Each cookie cut with it is a separate cookie: one may get chocolate, another hazelnut. The cutter itself is not eaten. A class likewise carries no data by itself; the objects produced from it carry the data.

Class (blueprint)Carbrandmodelyearcolordrive()stop()signal()newcar1 : CarToyota Corollacar2 : CarFord Mustangcar3 : CarFiat EgeaObjects (instances)
Figure 4.1.3: The Car class and three objects produced from it with new. The class defines the field names and methods; each object puts its own values in these fields.

On the left of Figure 4.1.3 the dashed box is the Car class. The class defines the fields brand, model, year and color and the methods drive(), stop() and signal(). The three objects on the right are produced from the same class: a Toyota Corolla, a Ford Mustang and a Fiat Egea. All three have the same field names, but the values differ. Two objects produced from the same class carry the same field names; the field values of each belong to itself. Changing the color of one does not change the color of the other.

Classes are usually drawn with a UML class diagram (Unified Modeling Language). In the diagram a class is a box with three compartments: the name of the class at the top, the fields in the middle, the methods at the bottom. The sign before each member shows its access level: - means private and + means public. Types are written next to fields and return types next to methods. Objects are drawn with a similar box, but the header holds the object's name and class in the form car1 : Car, and the header is underlined.

Car- brand : String- model : String- year : int- color : String+ drive() : void+ stop() : void+ signal() : voidcar1 : Carbrand = "Toyota"model = "Corolla"year = 2022color = "Gray"car2 : Carbrand = "Ford"model = "Mustang"year = 2023color = "Blue"instance of
Figure 4.1.4: UML notation. On the left the Car class (name / fields / methods), on the right two objects of this class. The object boxes show the current values of the fields; the dashed arrows show the "instance of" relation.

4.1.2.2Defining a class

The code below is the first Java version of the Car class in Figure 4.1.4. In the diagram the fields are marked private; in this first version no access modifier is written. The fields therefore have package access, and another class in the same folder can assign values to them directly.

public class Car {
  // Fields
  String brand;
  String model;
  int year;
  String color;

  // Methods
  void drive() {
    System.out.println(brand + " is moving.");
  }

  void stop() {
    System.out.println(brand + " stopped.");
  }

  void signal() {
    System.out.println(brand + " is signaling.");
  }
}

A class definition begins with the class keyword and the name of the class. The body of the class is between curly braces. The name starts with a capital letter, and if it consists of several words the first letter of each word is capitalized: Car, BankAccount, Rational. A public class must be in a file with the same name as the class. The definition public class Car is written in the file Car.java. A file may contain several classes, but at most one of them can be public.

Fields are declared in the body of the class, outside the methods. The declaration resembles a local variable declaration: a type and a name. The line String brand; says that every Car object will have a String field called brand. Fields can be used directly from every method of the class. The drive() method does not take brand as a parameter; it recognizes it as a field of the class.

There is no static in the headers of the methods. All the methods so far were static and were called with the class name, without an object. The methods here, in contrast, are methods of a particular car. When drive() is called, the object through which the method is called determines whose brand is printed. Such methods are called instance methods.

The class has no main method. So Car cannot be run on its own; it is a building block that another class uses. Most classes in real programs are like this: only one class carries main, and the others define the types it uses.

4.1.2.3Using a class

The CarTest class creates two Car objects, gives values to their fields and calls their methods. If the two files are in the same folder, they are compiled with javac Car.java CarTest.java and run with java CarTest.

public class CarTest {
  public static void main(String[] args) {
    Car car1 = new Car();
    car1.brand = "Toyota";
    car1.model = "Corolla";
    car1.year = 2022;
    car1.color = "Gray";

    Car car2 = new Car();
    car2.brand = "Ford";
    car2.model = "Mustang";
    car2.year = 2023;
    car2.color = "Blue";

    car1.drive();
    car2.signal();
    car1.stop();
  }
}
Toyota is moving.
Ford is signaling.
Toyota stopped.

The new Car() in the first line creates a new Car object in memory. The declaration Car car1 opens a variable of type Car. After the assignment car1 points to the newly created object. The type of the variable is a class name; in Java every class is also a new type.

The next four lines assign values to the fields of the object. The dot in car1.brand = "Toyota"; means "the brand field of the object that car1 points to". This sign is called the dot operator. For the second object other values are given to the same fields. Now there are two separate brand fields in memory: one holds "Toyota" and the other "Ford".

The last three lines call methods. In the call car1.drive(), the brand in the body of the method is the brand of car1: Toyota is moving. is printed. In the call car2.signal() the same name denotes the brand of car2: Ford is signaling. The method code is written once; the object to the left of the dot decides whose data it works with.

Assigning values to fields directly from outside like this is not a good habit. The line car1.year = -5; also compiles and puts the object in a meaningless state. The right way to give the fields their initial values is constructors; the right way to change values later is methods that perform checks. The style here is only to introduce the dot operator.

4.1.2.4Members of a class

Everything defined in the body of a class is called a member of the class. There are two basic kinds of members:

  • Fields represent the data objects can carry. In a Student class, name and surname are fields.
  • Methods define the operations objects can perform. In a Dog class, bark() and run() are methods.

Every member has two further properties. The first is the access level: a member can be private, protected, public, or, when none of these is written, package-private. The access level determines who may use the member. The second is ownership: a member either exists separately in every object (instance member, the default) or is declared static and belongs to the class itself.

Two more kinds of constructs can appear in the body of a class. Constructors are written inside the class and resemble methods, but they run only when an object is created. The Java language specification counts them not as methods but as a separate kind of member. Other classes can also be defined inside a class; these are called inner classes.

4.1.2.5Access modifiers and data hiding

Definition 4.1.4

An access modifier is a keyword that specifies who can reach a member from outside the class. Java has four access levels: public (everyone), protected (the same package and subclasses), package access when nothing is written (classes in the same package) and private (only the class itself).

The general rule is simple: fields are declared private and the methods offered to the outside are declared public. The value of a field is read from outside with a getter; its name traditionally starts with get. The value is changed with a setter; its name starts with set. The real job of a setter is to check the incoming value and reject invalid ones.

public class BankAccount {
  private double balance;   // hidden field
  public double getBalance() {
    return balance;
  }
  public void setBalance(double b) {
    if (b >= 0) balance = b;  // reject invalid
  }
}
// in another class:
acct.balance = -500;

The balance field is private. A class outside BankAccount can neither read nor change this field. When the last line of the code is written in another class, the compiler gives this message:

class BankAccount {
  private double balance;   // hidden field
}
public class PrivateAccess {
  public static void main(String[] args) {
    BankAccount acct = new BankAccount();
    acct.balance = -500;
  }
}
PrivateAccess.java:7: error: balance has private access in BankAccount
    acct.balance = -500;
         ^
1 error

The only way in from outside is the two public methods. getBalance() returns the value. setBalance(b) checks the new value before writing it: if b is negative, no assignment is made. The test program below first tries to give a valid and then an invalid balance:

public class AccountTest {
  public static void main(String[] args) {
    BankAccount acct = new BankAccount();
    acct.setBalance(1500);
    acct.setBalance(-500);   // rejected
    System.out.println(acct.getBalance());
  }
}
1500.0

Because -500 is rejected, the balance stays 1500.0. The program cannot make the balance negative; the rule that prevents this is written in a single place, inside setBalance. Had the field been public, every line that changes the field would have had to check the same rule separately, and forgetting just one would corrupt the object.

Definition 4.1.5

Data hiding is the arrangement in which only the methods of the class itself can access the fields directly. Fields are made private, and the outside world talks to the object only through public methods. Data hiding is the foundation of encapsulation.

The second gain of data hiding is freedom to change. Suppose it is decided to keep the balance in a long field in cents instead of a double. Because the field is private, no line outside uses it. Only the bodies of two methods change; the code that uses the class does not change at all.

Common mistake

Adding a get and a set method to every private field without thinking. A method such as public void setBalance(double b) { balance = b; } that performs no check effectively makes the field public. A setter is written only if the field really has to be changed from outside, and it rejects invalid values. A field that must never change has no setter.

4.1.3Constructors and object creation

In CarTest each object was set up in five lines: first new Car(), then four separate assignments. In this arrangement, if one of the assignments is forgotten, the object is left half-built, and the error shows up only at run time, perhaps much later. Constructors make sure an object is put into a valid state at the moment it is created.

4.1.3.1What is a constructor?

Definition 4.1.6

A constructor is a special block of code that runs while an object is being created. It is called automatically whenever an object is created with new. Its name is exactly the same as the class name (including case) and it has no return type; not even void is written.

The job of a constructor is to give the fields their initial values and to do whatever else is needed to make the object ready for use. The constructor of the Student class below takes two parameters and writes them to the fields of the object.

public class Student {
  private String name;
  private int id;

  // Constructor: class name, no return type
  public Student(String name, int id) {
    this.name = name;
    this.id = id;
  }
}

// Usage:
Student s = new Student("Ali", 2012);

The header of a constructor resembles a method header, but with two differences. The name is the name of the class: Student. There is no return type before the name. A constructor does not return a value; the result of a new expression is always the new object itself. The line this.name = name; in the body writes the value of the name parameter to the name field of the object. Here this means "the object being created".

Constructors are usually declared public, because the code that creates the object is outside the class. Sometimes one wants to restrict object creation. In that case the constructor is made private and new cannot be called from outside the class. Singleton classes are built this way. A class may have several constructors with different parameter lists.

4.1.3.2The new expression

The general form of object creation is this:

ClassName objectName = new ClassName(arguments);

Car corolla = new Car("Toyota", "Corolla", 2022);
Scanner in = new Scanner(System.in);
Book book = new Book();

The first line shows the pattern and the next three lines show three examples. To the left of the equals sign is a variable declaration and to the right a new expression. Java's own classes are used the same way: to read from the keyboard one writes new Scanner(System.in), and for a modifiable text new StringBuilder("Java"). The program below creates and uses four objects.

import java.util.Scanner;
public class CreateDemo {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder text = new StringBuilder("Java");
    String title = "Objects";           // shortcut
    String author = new String("Sercan");  // long way
    text.append(" 21");
    System.out.println(text + " / " + title);
    System.out.println(author.length());
    System.out.println(in.nextInt() * 2);
  }
}

When 21 is typed at the keyboard, the program prints:

Java 21 / Objects
6
42

The new expression works in three steps:

  1. new reserves space for the object in the region of memory called the heap. All the fields of the object first receive their default values: numbers become 0, boolean fields false, reference fields null.
  2. The constructor matching the arguments is called and gives the fields their initial values.
  3. The result of the new expression is the reference to the new object. This reference is assigned to the variable to the left of the equals sign.

With String there is a familiar exception to this rule: writing a text literal also yields a String object. The line String title = "Objects"; puts the reference of a String object into title without using new. Writing new String("Sercan") is also valid, but it needlessly produces a new object each time it runs. Writing just String title; creates no object at all; it only declares a variable that can hold a reference.

The 6 in the second line of the output is the result of the call author.length(): "Sercan" has six letters. This call is also an instance method call made with the dot operator. There is no difference in usage between the classes a programmer writes and Java's ready-made classes.

4.1.3.3References

An object cannot be touched directly. A program works with an object only through the reference that leads to it. A variable of a class type stores not the object itself but this reference.

Definition 4.1.7

A reference is a value that points to the location of an object on the heap. It can be thought of as the object's address in memory. Variables of class types (Car, String, Scanner, arrays) hold references. A reference that points to no object has the value null.

Variables of primitive types such as int, double and boolean hold the value themselves. After the line int x = 5; the number 5 sits in the box of x. After the line Car a = new Car(...);, however, the box of a holds not a car but an arrow pointing to where the car is. An easy way to remember this difference is an analogy: the variable is a television remote control and the object is the television. Copying the remote does not create a second television; two remotes switch the same television on and off.

StackHeapmain()sportsCarclassicCarnewCarnullCar objectmodel"2022"color"RED"Car objectmodel"2023"color"WHITE"
Figure 4.1.5: Local variables are on the stack and objects on the heap. sportsCar and classicCar point to two separate objects; newCar does not point to any object yet (null).

Memory is divided into two regions. The frames and local variables of running methods are on the stack. Objects are kept on the heap. In Figure 4.1.5 the frame of main is on the left. The arrows leaving the boxes sportsCar and classicCar in the frame reach the two objects on the heap. The third variable, newCar, has been declared but no object has been assigned to it yet; its value is null. This drawing convention is used throughout the rest of the notes: a box is a variable, an arrow is a reference, and a framed box on the heap is an object.

4.1.3.4Tracing object creation step by step

The Car class below contains two fields, a constructor with two parameters and a method. main creates two objects and prints the information of both.

public class Car {
  private String model;
  private String color;

  public Car(String model, String color) {
    this.model = model;
    this.color = color;
  }

  public void printInfo() {
    System.out.println(model + " - " + color);
  }

  public static void main(String[] args) {
    Car sportsCar = new Car("2022", "RED");
    Car classicCar = new Car("2023", "WHITE");
    sportsCar.printInfo();
    classicCar.printInfo();
  }
}
2022 - RED
2023 - WHITE

Table 4.1.3 gives the eight steps of the program. The line numbers are the lines of the code above. The "Variables" column shows the variables of the topmost frame at that moment; the notation →#1 means the variable points to object number 1 on the heap, and ? means the variable has not been given a value yet.

Table 4.1.3: Trace of the calls new Car(...) and printInfo().
StepLineCall stackVariablesNew output
115: Car sportsCar = new Car("2022", "RED");main()sportsCar=?, classicCar=?—
25: public Car(String model, String color) {main() → Car(model, color)model="2022", color="RED"—
36: this.model = model;main() → Car(model, color)model="2022", color="RED"—
47: this.color = color;main() → Car(model, color)model="2022", color="RED"—
515: Car sportsCar = new Car("2022", "RED");main()sportsCar=→#1, classicCar=?—
616: Car classicCar = new Car("2023", "WHITE");main()sportsCar=→#1, classicCar=→#2—
717: sportsCar.printInfo();
11: System.out.println(model + " - " + color);
main() → printInfo()sportsCar=→#1, classicCar=→#22022 - RED
818: classicCar.printInfo();
11: System.out.println(model + " - " + color);
main() → printInfo()sportsCar=→#1, classicCar=→#22023 - WHITE

In the first step line 15 starts to run. new reserves space for a Car object on the heap. model and color are fields of type String, that is, of a reference type; their default values are null. The object exists at this moment, but it is empty inside.

StackHeapmain()sportsCar?classicCar?Car #1modelnullcolornull StackHeapCar(...)thismodel"2022"color"RED"main()sportsCar?classicCar?Car #1model"2022"color"RED" StackHeapprintInfo()thismain()sportsCarclassicCarCar #1model"2022"color"RED"Car #2model"2023"color"WHITE"
Figure 4.1.6: Three moments. Left: new has allocated the object and the fields are null. Middle: the constructor is running; this in the constructor's frame points to the new object and two fields have been filled. Right: the second printInfo() call; this time this points to object number 2.

In the second step the constructor is called and a new frame is opened on the stack. The parameters receive copies of the arguments: model = "2022", color = "RED". The frame has one more variable: this. When calling the constructor, Java quietly passes the reference of the new object under the name this. In the third and fourth steps this.model = model; and this.color = color; run. In each line this.model to the left of the equals sign is the field of the object, and model to the right is the parameter. After these two lines the object is ready (Figure 4.1.6, middle).

In the fifth step the constructor ends and its frame is removed. The parameters and this vanish with it, but the object stays on the heap. The reference, the value of the new expression, is assigned to sportsCar. The sixth step does the same for the second object. A separate object with its own copies of model and color appears on the heap, and classicCar points to it.

In the seventh step sportsCar.printInfo() is called. The method's frame also has a this, and its value is the reference to the left of the dot: object number 1. The names model and color in the body of the method mean this.model and this.color. That is why 2022 - RED is printed. In the eighth step the same method is called through classicCar; this time this points to object number 2 and 2023 - WHITE is printed. The code is single; the data are separate for each object.

The space an object occupies in memory is the sum of its fields. Methods are not copied into every object; the class's code exists in memory once. So creating a thousand Car objects takes a thousand times the space of two references, but the code of printInfo occupies space only once.

4.1.3.5The default constructor and default values

The first Car class had no constructor at all, yet new Car() compiled without trouble. The reason is help from the compiler.

Definition 4.1.8

The default constructor is the parameterless constructor with an empty body that the compiler adds when no constructor has been written in the class. If even a single constructor is written in the class, the compiler does not add the default constructor.

A constructor is always called when an object is created; the default constructor makes sure that this call has a target when the programmer has not written one. Because its body is empty, it gives no values to the fields. Fields that are not given a value stay at the default values they received in the first step of new. Table 4.1.4 lists these values.

Table 4.1.4: Default values of fields. Local variables get no default value.
Field typeDefault value
byte, short, int, long0
float, double0.0
booleanfalse
char'\u0000' (code 0)
Reference (String, arrays, objects)null
class Point3 {
  int x;
  double weight;
  boolean visible;
  char letter;
  String name;
}
public class Defaults {
  public static void main(String[] args) {
    Point3 n = new Point3();   // default constructor
    System.out.println(n.x + " " + n.weight);
    System.out.println(n.visible + " " + n.name);
    System.out.println((int) n.letter);
  }
}
0 0.0
false null
0

The Point3 class has no constructor; new Point3() calls the default constructor the compiler added. None of the five fields has been given a value, and each holds the value in the table. The value of the char field is the character with code 0. This character is not visible on the screen, so the program converts it to a number with (int) and prints it: 0.

The default value rule is only for fields and array elements. A local variable inside a method gets no default value. The compiler does not accept a local variable that is read without being given a value:

public class Uninitialized {
  public static void main(String[] args) {
    StringBuilder sb;
    sb.append("x");
  }
}
Uninitialized.java:4: error: variable sb might not have been initialized
    sb.append("x");
    ^
1 error

The reason for this difference is safety. The compiler can examine all the paths inside a method and see whether a local variable receives a value before it is read. For fields it cannot do this, because a field can be read from any method in any order. Java therefore starts fields at least with a defined value.

4.1.3.6No-argument and parameterized constructors

More than one constructor can be written for a class. The Vehicle class below has two constructors, one without parameters and one with three.

public class Vehicle {
  private String brand;
  private String model;
  private int year;
  public Vehicle() {                 // no-arg constructor
    brand = "Unknown";
    model = "Unknown";
    year = 0;
  }
  public Vehicle(String brand, String model, int year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
  }
  public void printInfo() {
    System.out.println(brand + " " + model + " " + year);
  }
  public static void main(String[] args) {
    Vehicle a1 = new Vehicle();
    Vehicle a2 = new Vehicle("Renault", "Clio", 2021);
    a1.printInfo();
    a2.printInfo();
  }
}
Unknown Unknown 0
Renault Clio 2021

Vehicle() is a no-argument constructor written by the programmer. It differs from the default constructor in that it gives the fields meaningful initial values: brand and model become "Unknown" instead of null. The two constructors have the same name and are told apart by their parameter lists. This is the constructor counterpart of overloading in methods: constructor overloading. The arguments in the new expression decide which constructor runs. new Vehicle() calls the no-argument constructor and new Vehicle("Renault", "Clio", 2021) calls the three-parameter one.

Once any constructor has been written in a class, the compiler no longer adds a default constructor. In a class that has only a parameterized constructor, creating an object without arguments with new is a compile error:

public class VehicleDefaults {
  private String brand;
  public VehicleDefaults(String brand) {
    this.brand = brand;
  }
  public static void main(String[] args) {
    VehicleDefaults a = new VehicleDefaults();
  }
}
VehicleDefaults.java:7: error: constructor VehicleDefaults in class VehicleDefaults cannot be applied to given types;
    VehicleDefaults a = new VehicleDefaults();
                       ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

The lower lines of the message say clearly what was expected: required: String, that is, a String argument is expected; found: no arguments, that is, no argument was given. If creating an object without arguments is needed, a no-argument constructor is also written by hand.

Common mistake

Writing a return type on a constructor. public void CtorError(String m) is not a constructor but an ordinary method that happens to have the same name as the class. Since the class has no other constructor, the compiler adds the no-argument default constructor, and new CtorError("hello") is rejected with this message:

CtorError.java:7: error: constructor CtorError in class CtorError cannot be applied to given types;
    CtorError h = new CtorError("hello");
              ^
  required: no arguments
  found:    String
  reason: actual and formal argument lists differ in length
1 error

The message saying required: no arguments shows that the compiler sees only the no-argument constructor. When void is removed, the method becomes a constructor.

4.1.4Fields

Fields are variables defined inside a class, outside the methods. They differ from local variables in three respects. They receive default values. They do not vanish when a method ends; they live as long as the object. They are visible from all the methods of the class. Whom a field belongs to depends on the word static.

4.1.4.1Instance fields and class fields

Definition 4.1.9

An instance field is a field declared without static; every object has a separate copy of it. A static field (class field) is a field declared with static; the class has a single copy and all objects share it.

Table 4.1.5: Instance fields compared with class fields.
Instance fieldClass field (static)
Declarationprivate String name;private static int accountCount;
Number of copiesA separate copy in every objectA single copy in the class, shared by all objects
When created?With every newOnce, when the class is loaded into memory
Accessobject.nameClassName.accountCount
ExampleStudent: name, surnameBankAccount: accountCount

Whether a field is an instance field or a class field is decided by this question: does the value vary from object to object? Every student's name is different; name is an instance field. The total number of accounts opened in the bank, on the other hand, is a single number. Keeping a separate counter in every account object would be both unnecessary and the counters would show different values. For this reason the counter is declared static.

4.1.4.2Tracing a static counter

In the class below each account keeps its own owner's name, while all accounts share a single counter. Every time the constructor runs, the counter goes up by one.

public class BankAccount {
  private String owner;
  private static int accountCount = 0;

  public BankAccount(String owner) {
    this.owner = owner;
    accountCount++;
  }

  public static int getAccountCount() {
    return accountCount;
  }

  public static void main(String[] args) {
    BankAccount h1 = new BankAccount("Ali");
    BankAccount h2 = new BankAccount("Ayşe");
    BankAccount h3 = new BankAccount("Can");
    System.out.println(h2.owner);
    int count = BankAccount.getAccountCount();
    System.out.println(count);
  }
}
Ayşe
3
Table 4.1.6: Trace of the static counter. In the Variables column, accountCount is the value of the class field.
StepLineCall stackVariablesNew output
13: private static int accountCount = 0;(class loading)accountCount=0—
25: public BankAccount(String owner) {
6: this.owner = owner;
7: accountCount++;
main() → BankAccount("Ali")accountCount=1, h1=?—
315: BankAccount h1 = new BankAccount("Ali");main()accountCount=1, h1=→#1—
416: BankAccount h2 = new BankAccount("Ayşe");main()accountCount=2, h1=→#1, h2=→#2—
517: BankAccount h3 = new BankAccount("Can");main()accountCount=3, h1=→#1, h2=→#2, h3=→#3—
618: System.out.println(h2.owner);main()accountCount=3Ayşe
719: int count = BankAccount.getAccountCount();
10: public static int getAccountCount() {
11: return accountCount;
main() → getAccountCount()accountCount=3—
820: System.out.println(count);main()accountCount=3, count=33

The first step happens before main. When the BankAccount class is loaded into memory, the static field is created once and receives its initial value: 0. At this moment there is no BankAccount object on the heap, but the counter exists. A static field is part of the class, not of the objects, and its life begins when the class is loaded.

In the second step new BankAccount("Ali") creates the first object. The first line of the constructor writes "Ali" to the object's own owner field. The accountCount++ in the second line raises the shared counter to 1. From inside the constructor the static field can be reached without writing the class name; the compiler knows the name is a class field. In the third step h1 starts pointing to this object.

StackHeapClass area (static): BankAccountaccountCount0 StackHeapClass area (static): BankAccountaccountCount3main()h1h2h3BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"BankAccount #3owner"Can"
Figure 4.1.7: Left: the class has been loaded, the counter is 0, there is no object yet. Right: three objects have been created; each has its own owner field, but the counter is a single box and its value is 3.

The fourth and fifth steps do the same thing twice more. A separate owner field is created for each object, but the counter being incremented is always the same box: 2, then 3. The right part of Figure 4.1.7 draws this moment. On the heap there are three objects and three separate owner boxes; accountCount, on the other hand, is a single box outside the objects, in the region that belongs to the class.

In the sixth step h2.owner is read: an instance field is read through the object, and Ayşe is printed. In the seventh step the static method getAccountCount() is called with the class name. The frame of this method has no this, because the method was not called through any object. The method only reads the static field and returns 3. In the eighth step the returned value is assigned to count and printed.

Because the main method is inside the BankAccount class, the line h2.owner compiles even though the field is private. private means "only code inside this class"; access is decided by the class, not by the object. Had the same line been written in the main of another class, a has private access error would have been the result.

4.1.4.3Field declarations and final

The general form of a field declaration is: [access] [static] [final] type name [= initialValue];. The parts in square brackets are optional. The two classes below show different combinations.

public class Book {
  // Instance fields
  private String title;
  private String author;
  private int pageCount;
  // Class field
  private static int bookCount;
  // a final field (constant)
  public static final double PI = 3.14159265359;
}
public class Fields {
  public int a;                         // public
  int b = 1, c = 2;                     // default (package)
  private double x;                     // private
  private static int xx;                // static, private
  public static int y;                  // static, public
  public final int CONST1 = 5;          // cannot change
  private static final int CONST2 = 6;  // static constant
}

The Book class has three instance fields, one class field and one constant. The Fields class lists the combinations of access modifiers with static and final. The line int b = 1, c = 2; declares two fields of the same type in one line and gives both an initial value. Because no access modifier is written, these two fields have package access.

A field declared final is given a value only once; it cannot be changed afterwards. The value is given either on the declaration line or in the constructor. A line that tries to assign a value later does not compile:

public class FinalAssign {
  public final int CONST1 = 5;
  void change() {
    CONST1 = 6;
  }
}
FinalAssign.java:4: error: cannot assign a value to final variable CONST1
    CONST1 = 6;
    ^
1 error

Class constants are usually declared static final and are written in capital letters separated by underscores: MAX_VALUE, PI. Because it is static, the constant has a single copy; because it is final, its value does not change. The PI in the Book class is defined only as an example. Java already has a ready-made constant that is more precise: Math.PI.

CONST1 in the Fields class is final but not static. So every object has a separate copy of it, and the value of all of them is 5. Storing a constant that is the same for everyone separately in every object wastes memory; such constants are made static final.

4.1.4.4Initializer blocks and initialization order

There are three ways to give a field an initial value: on the declaration line, in the constructor and in an initializer block. The third is used for preparation work that does not fit on one line.

Definition 4.1.10

An initializer block is a block of code written directly in the body of a class. A static initializer (static { ... }) runs only once, when the class is loaded into memory for the first time. An instance initializer ({ ... }) runs before the body of the constructor every time an object is created.

A static initializer is used to give a static field a complex initial value, for example to fill a table with a loop. An instance initializer gathers the work common to all constructors in one place. The order of the steps when an object is created is as follows:

  1. If the class is being used for the first time, the initial values of the static fields and the static blocks run once, in the order in which they are written.
  2. new allocates memory for the object; all fields receive default values.
  3. The initial values on the field declaration lines and the instance initializer blocks run in the order in which they are written.
  4. The body of the constructor runs.
1 static { } and static fieldsonce, on first use of the class2 new: memory allocatedfields at default values3 field initializers, { }in source order, every new4 constructor bodyevery new
Figure 4.1.8: The order of object creation. The first box runs only when the class is used for the first time; the other three run at every new.

The "order in which they are written" in the third step is important. Initial values on declaration lines and { } blocks do not run as separate groups; they run in whatever order they are written in the class, from top to bottom. If an initializer block is written before a field declaration, the block runs first. The Dog class below has both kinds of initializer.

public class Dog {
  String name;                 // field
  Dog(String name) {         // constructor
    this.name = name;
    System.out.println(name);
  }
  String bark() {            // instance method
    return name + " woof woof!";
  }
  static {                    // static initializer
    System.out.println("Dogs!");
  }
  {                           // instance initializer
    System.out.println("Creating a dog.");
  }
  public static void main(String... strings) {
    var d1 = new Dog("Kara");
    var d2 = new Dog("Gece");
    d2.bark();
  }
}
Dogs!
Creating a dog.
Kara
Creating a dog.
Gece

Two notations in main may be new. var (since Java 10) infers the type of the local variable from the expression on the right: the line var d1 = new Dog("Kara"); is the same as Dog d1 = .... String... strings is the variable-arity parameter notation that stands in for String[] strings; for main the two are equivalent.

Table 4.1.7: The order in which initializers and constructors run in the Dog class.
StepLineCall stackVariablesNew output
111: System.out.println("Dogs!");static initializer—Dogs!
217: var d1 = new Dog("Kara");main()d1=?, d2=?—
314: System.out.println("Creating a dog.");main() → Dog("Kara")d1=?, d2=?Creating a dog.
44: this.name = name;main() → Dog("Kara")name="Kara"—
55: System.out.println(name);main() → Dog("Kara")name="Kara"Kara
618: var d2 = new Dog("Gece");main()d1=→#1, d2=→#2Creating a dog. ⏎ Gece
719: d2.bark();
8: return name + " woof woof!";
main() → bark()d1=→#1, d2=→#2—

In the first step, before main even starts, the Dog class is loaded, because main is a method of this class. While the class is being loaded, the static block runs and Dogs! is printed. In the second step new Dog("Kara") allocates space for the object; the name field is null. In the third step the instance initializer runs before the body of the constructor: Creating a dog. In the fourth and fifth steps the body of the constructor fills in the field and prints the name: Kara.

StackHeapDog(name)thisname"Kara"main()d1?d2?Dog #1namenull StackHeapbark()thismain()d1d2Dog #1name"Kara"Dog #2name"Gece"
Figure 4.1.9: Left: the instance initializer has run and the constructor's frame is open; the object's name field is still null. Right: both objects are ready; bark() is running on object number 2.

The sixth step runs the initializer and the constructor again for the second object: Creating a dog. and Gece. The static block does not run this time, because the class is already loaded. In the seventh step d2.bark() is called. The method returns the text "Gece woof woof!", but main neither assigns this value to a variable nor prints it. The returned value is lost unused and nothing appears on the screen. To make this text appear on the screen one would have to write System.out.println(d2.bark());.

Example 4.1.1

What does the following program print?

class A {
  static { System.out.print("S"); }
  { System.out.print("I"); }
  A() { System.out.print("C"); }
}
public class Problem3 {
  public static void main(String[] args) {
    System.out.print("M");
    new A();
    new A();
    System.out.println();
  }
}

main first prints M. Because class A is not the class of main, it is not loaded when the program starts; it is loaded at the first new A() expression. At that moment the static block runs once: S. Then the instance initializer (I) and the constructor (C) run for the first object. At the second new A() the class is already loaded; only I and C are printed. Result:

MSICIC

4.1.5Methods

Methods define the behavior of a class. Defining a method, parameters, return values and the call stack are known from basic programming. The real question here is how methods relate to objects: whose data does a method work with, and how does it know?

4.1.5.1Instance methods and class methods

As with fields, there are two kinds of methods. An instance method is tied to an object and uses that object's fields: phone.call(...). A class method (static method) is tied to the class itself and is called through the class name: Phone.updateOS(...).

public class Phone {
  private String model;
  private static String osVersion = "Version 1";

  // Instance method
  public void call(String number) {
    System.out.println(model + " calling: " + number);
  }

  // Instance method
  public void sendMessage(String to, String msg) {
    System.out.println(to + " <- " + msg);
  }

  // Class method (static)
  public static void updateOS(String newVersion) {
    osVersion = newVersion;
  }

  public static void main(String[] args) {
    Phone phone = new Phone();
    phone.model = "A54";
    phone.call("5551234567");
    phone.sendMessage("Ayşe", "I'm coming");
    Phone.updateOS("Version 2");
    System.out.println(osVersion);
  }
}
A54 calling: 5551234567
Ayşe <- I'm coming
Version 2

call and sendMessage are instance methods. The model in the body of call is the model of the phone that called the method. updateOS, on the other hand, is static: it changes the operating system version common to all phones and is not tied to any particular phone. For this reason a static method cannot directly access data specific to an object, such as model. Whose phone's model? The question has no answer, because the method was not called through any phone. The last line of main reads osVersion without writing the class name; because main is also a static method of the same class, this notation is valid.

4.1.5.2A method that returns a value: Email

The header of a method summarizes what it does. The name of the send method below is send. It has three String parameters: the recipient, the subject and the body. Its return type is boolean and it reports whether the sending succeeded.

public class Email {
  public boolean send(String to, String subject,
             String body) {
    // a simulation, not a real send
    if (to == null || !to.contains("@")) {
      return false;               // failed
    }
    System.out.println(to + " <- " + subject);
    return true;                    // succeeded
  }

  public static void main(String[] args) {
    Email e = new Email();
    boolean s1 = e.send("ali@example.com", "Homework", "Hi");
    boolean s2 = e.send("ali.example.com", "Homework", "Hi");
    System.out.println(s1 + " " + s2);
  }
}
ali@example.com <- Homework
true false

The method does not send a real e-mail; it represents sending with a simulation. If the recipient address is null or does not contain @, it returns false. The || in the condition is the short-circuit operator: if to == null is true, the right side is never evaluated. Had the order been reversed, the call to.contains("@") would have thrown a NullPointerException for a null address. If the address is valid, the method prints the sending and returns true. main tries two sendings; in the second address there is a dot instead of @, so the second call returns false without printing anything to the screen.

Every path of a method that returns boolean must end with a return. Even a method whose body has not been written yet and contains only a comment does not compile:

public class MissingReturn {
  public boolean send(String to, String subject, String body) {
    // to be written later
  }
}
MissingReturn.java:4: error: missing return statement
  }
  ^
1 error

4.1.5.3One piece of code, many objects

Instance fields and methods are declared in the class without the word static. Every object carries its own copy of the fields; for this reason objects can work with different data. To use an instance member an object is needed first: first new, then object.method(). The code of the method, however, is single for all objects. On every call, this decides whose data the method works with.

greet() codeone copy in the classstudent1 objectname = "Ali"thisstudent2 objectname = "Ayşe"this
Figure 4.1.10: The code of greet() exists as a single copy in the class. In the call student1.greet(), this points to the first object; in the call student2.greet(), to the second.
Table 4.1.8: Instance methods compared with static methods.
Instancestatic
Belongs toThe objectThe class
Callobject.method()ClassName.method()
Object needed?YesNo
Has this?YesNo
Examplestr.length()Math.sqrt(x)

The last row of the table compares two familiar calls. str.length() gives the length of a text; str decides which text's length it is. Math.sqrt(x) gives the square root of a number. This job is not tied to any Math object; all the information needed is in the parameter x. Whether a method should be static is decided by this yardstick: if the method uses the fields of an object, it is an instance method; if it works only with its parameters, it can be static.

4.1.5.4The dot operator and object parameters

Once an object has been created, its fields and methods are reached with the dot operator: object.method(...), object.area. A method can also take another object as a parameter. In that case there are two objects inside the method: the object the method was called on and the object that came in as a parameter.

public class Phone {
  String number;
  public Phone(String number) {
    this.number = number;
  }
  public void call(Phone phone) {
    System.out.println(number + " calling: " + phone.number);
  }
  public void sendMessage(Phone phone, String msg) {
    System.out.println(phone.number + " <- " + msg);
  }
  public void openCamera() {
    System.out.println(number + " opened the camera.");
  }
  public static void main(String[] args) {
    Phone phone1 = new Phone("5551234567");
    Phone phone2 = new Phone("5051234567");
    phone1.call(phone2);
    phone2.sendMessage(phone1, "Hello!");
    phone1.openCamera();
  }
}
5551234567 calling: 5051234567
5551234567 <- Hello!
5551234567 opened the camera.

In the call phone1.call(phone2), the bare number in the body of the method is the number of the object the method was called on, that is, phone1. phone.number is the number of the object that came in as a parameter, that is, phone2. That is why the first line has the form "5551234567 calling: 5051234567".

The second call must be read carefully. In the call phone2.sendMessage(phone1, "Hello!") the object calling the method is phone2, but the body uses only the number of the phone in the parameter: phone.number, that is, the number of phone1. This is why 5551234567 appears in the output. Although the method is named "send message", the number printed is the recipient's; the number that would show the sender is never used in the body. A bare field name in the body of a method and a field name reached through a parameter belong to different objects; if this distinction is overlooked, the wrong object's data is read.

The private fields of an object that comes in as a parameter can also be accessed, as long as the accessing code is inside the same class. number here has package access, but even if it were private, the notation phone.number would still compile. The access rule is per class, not per object.

4.1.5.5The Rectangle class

The rectangle example from the comparison of the procedural and object-oriented approaches can now be written as a complete class.

public class Rectangle {
  private double length;     // rectangle's length
  private double width;    // rectangle's width

  // Constructor
  public Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
  }

  public double area() {      // computes the area
    return length * width;
  }

  public double perimeter() {     // computes the perimeter
    return 2 * (length + width);
  }
}

The fields are private; they are used from outside only through the methods. The constructor takes the two sides and records them in the object. area() and perimeter() take no parameters, because the data they need is inside the object. The procedural counterpart would be area(5.0, 3.0); with the object it is written rect.area(). The test class below creates two rectangles.

public class RectangleTest {
  public static void main(String[] args) {
    Rectangle rect = new Rectangle(5.0, 3.0);
    Rectangle square = new Rectangle(5.0, 5.0);
    double area = rect.area();
    double perimeter = rect.perimeter();
    System.out.println("Area: " + area
        + " Perimeter: " + perimeter);
    area = square.area();
    perimeter = square.perimeter();
    System.out.println("Area: " + area
        + " Perimeter: " + perimeter);
  }
}
Area: 15.0 Perimeter: 16.0
Area: 25.0 Perimeter: 20.0
Table 4.1.9: Trace of RectangleTest.
StepLineCall stackVariablesNew output
13: Rectangle rect = new Rectangle(5.0, 3.0);
4: Rectangle square = new Rectangle(5.0, 5.0);
main()rect=→#1, square=→#2—
25: double area = rect.area();main() → area()rect=→#1, square=→#2—
36: double perimeter = rect.perimeter();main() → perimeter()area=15.0—
47: System.out.println("Area: " + area
8: + " Perimeter: " + perimeter);
main()area=15.0, perimeter=16.0Area: 15.0 Perimeter: 16.0
59: area = square.area();
10: perimeter = square.perimeter();
main() → area()area=25.0, perimeter=20.0—
611: System.out.println("Area: " + area
12: + " Perimeter: " + perimeter);
main()area=25.0, perimeter=20.0Area: 25.0 Perimeter: 20.0

In the first step two objects are created; each has its own length and width values. In the second step rect.area() is called. In the method's frame this points to object number 1 and the method returns 5.0 × 3.0 = 15.0. In the third step perimeter() finds 2 × (5.0 + 3.0) = 16.0 for the same object. In the fourth step the two double values are appended to the text and printed; when double values are concatenated with +, they are written with their decimal part, in the form 15.0.

StackHeaparea()thismain()rectsquarearea?perimeter?Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0 StackHeaparea()thismain()rectsquarearea25.0perimeter20.0Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0
Figure 4.1.11: Left: rect.area() is running; this points to object number 1. Right: the same method called through square; this points to object number 2, and area and perimeter have received their new values.

In the fifth step the same two methods are called through square. This time this points to object number 2: 5.0 × 5.0 = 25.0 and 2 × (5.0 + 5.0) = 20.0. These values overwrite the old values of the variables area and perimeter. In the sixth step the second line is printed. That the println call is split over two lines is no problem: in Java a statement goes on until the semicolon.

The cost of both methods is constant: they do a few arithmetic operations and use no extra memory. Adding a field to the object, for example to keep the rectangle's color, does not affect these methods. In the procedural version, carrying the color information would require adding a new parameter to every call.

4.1.6static members

The word static has appeared with both fields and methods. Gathering its rules in one place also explains the cause of the most common compile error.

4.1.6.1Access without an object

Definition 4.1.11

A static member is a field or method declared with the static keyword that belongs not to any object but to the class itself. To reach a static member no object needs to be created; the class name and a dot are used: ClassName.fieldName, ClassName.methodName(arguments).

public class MathUtil {
  // Static add method
  public static int add(int a, int b) {
    return a + b;
  }

  public static void main(String[] args) {
    int result = MathUtil.add(5, 3);
    System.out.println("Sum: " + result);
    System.out.println(Math.max(4, 9));
    System.out.println(Math.sqrt(16.0));
  }
}
Sum: 8
9
4.0

The call MathUtil.add(5, 3) is made without creating any MathUtil object. Because main is inside the same class, add(5, 3) could also have been written without the class name. Math.max and Math.sqrt are calls of the same kind: static methods of the Math class. Java's ready-made library has many examples of this: Math.PI, Integer.parseInt("12"), Integer.MAX_VALUE. The main with which every program starts is also static. When the program starts, the JVM (Java Virtual Machine) has not yet created any object; for it to call main without an object, the method has to belong to the class.

A static member can also be reached through an object: h1.accountCount. Java accepts this notation, but it is discouraged. A reader of the code assumes the member belongs to the object and thinks the counter of h1 might differ from that of h2. The compiler treats this notation as BankAccount.accountCount; which object is used is irrelevant. If compiled with the -Xlint option, it also gives the warning static variable should be qualified by type name.

4.1.6.2The rules of the static context

An instance method can use both instance members and static members directly. Such a method is always called through an object; that object is this, and the instance fields are its fields. A static class field is single anyway. A static method, on the other hand, has no this. This method can reach instance members only through an explicitly given object. Table 4.1.10 summarizes the four cases.

Table 4.1.10: Which method can use which member directly?
FromInstance field / methodstatic field / method
An instance method✓ directly (name, this.name)✓ directly
A static method (including main)✗ only through an object (s.name)✓ directly

Violating the rule is the compile error that beginners meet most often. Calling an instance method directly from main:

public class Greeter {
  private String name = "Ali";
  public void greet() {
    System.out.println("Hello " + name);
  }
  public static void main(String[] args) {
    greet();
  }
}
Greeter.java:7: error: non-static method greet() cannot be referenced from a static context
    greet();
    ^
1 error

Reading an instance field directly from a static method:

public class Greeter2 {
  private String name = "Ali";
  public static void print() {
    System.out.println(name);
  }
}
Greeter2.java:4: error: non-static variable name cannot be referenced from a static context
    System.out.println(name);
                       ^
1 error

The same phrase appears in both messages: cannot be referenced from a static context. A "static context" means a place where there is no this. The call greet() is really this.greet(), and the read of name is this.name. Because main has no this, the compiler cannot know whose method or field is meant. Writing this explicitly changes nothing either; the message then becomes non-static variable this cannot be referenced from a static context.

There are two fixes, and which one to choose depends on the design. If the method really needs the data of an object, the call is made through an object: new Greeter().greet();. If the method uses no object's data, it is made static. The second way is right only when the method is truly independent of any object. Making all methods and fields static just to silence the compile error turns the program back into the procedural style. Where each object should have its own data, a single shared copy remains.

4.1.7References and this

The fact that a variable holds a reference, not an object, looks like a mere detail at first sight. But this detail determines how assignment, comparison and passing objects to methods behave.

4.1.7.1Reference assignment and aliasing

In Java objects are handled through references. Assigning one reference variable to another does not copy the object; it copies only the reference. After the assignment two variables point to the same object.

Definition 4.1.12

An alias is any one of several reference variables that point to the same object. There is one object; a change made through one of the aliases is visible through the others too.

There are similar situations in everyday life. The label on a library shelf is not the book itself; it shows where the book is. A car may have two keys; both keys open the same car. If someone gets in with one key and pushes the seat back, the person who gets in with the other key finds the seat pushed back. The program below shows this situation with a Car class whose brand field is private and which has a getter and a setter.

public class Car {
  private String brand;

  public Car(String brand) {
    this.brand = brand;
  }

  public String getBrand() {
    return brand;
  }

  public void setBrand(String brand) {
    this.brand = brand;
  }

}
public static void main(String[] args) {
  Car car1 = new Car("Toyota");
  Car car2 = car1;
  System.out.println("Car 1: " + car1.getBrand());
  System.out.println("Car 2: " + car2.getBrand());
  car2.setBrand("Ford");
  System.out.println("Car 1: " + car1.getBrand());
  car1 = null;
  System.out.println("Car 2: " + car2.getBrand());
}
Car 1: Toyota
Car 2: Toyota
Car 1: Ford
Car 2: Ford
Table 4.1.11: Trace of reference assignment. The line numbers are the lines of main.
StepLineCall stackVariablesNew output
12: Car car1 = new Car("Toyota");main()car1=→#1, car2=?—
23: Car car2 = car1;main()car1=→#1, car2=→#1—
34: System.out.println("Car 1: " + car1.getBrand());
5: System.out.println("Car 2: " + car2.getBrand());
main()car1=→#1, car2=→#1Car 1: Toyota ⏎ Car 2: Toyota
46: car2.setBrand("Ford");main() → setBrand("Ford")car1=→#1, car2=→#1—
57: System.out.println("Car 1: " + car1.getBrand());main()car1=→#1, car2=→#1Car 1: Ford
68: car1 = null;main()car1=null, car2=→#1—
79: System.out.println("Car 2: " + car2.getBrand());main()car1=null, car2=→#1Car 2: Ford

In the first step a single object is created on the heap and car1 points to it. The line Car car2 = car1; in the second step creates no new object. The reference in the box of car1 is copied into the box of car2. There is still a single object on the heap; now two arrows lead to it. In the third step the brand is read through both variables and both give Toyota: the field being read is the same field.

StackHeapmain()car1car2Car #1brand"Toyota" StackHeapsetBrand()thisbrand"Ford"main()car1car2Car #1brand"Ford" StackHeapmain()car1nullcar2Car #1brand"Ford"
Figure 4.1.12: From left to right: after car2 = car1 two arrows go to a single object; car2.setBrand("Ford") changes the shared object; car1 = null cuts only one arrow, and the object lives on through car2.

In the fourth step car2.setBrand("Ford") is called. The method's this is the object car2 points to, that is, the single object. In the fifth step the brand read through car1 is also Ford: the change is shared. This behavior is surprising if one does not know that the two variables point to the same object. The program thinks it has changed car2, but it has in fact also changed the object car1 points to.

In the sixth step car1 = null; runs. This line does not delete the object; it only cuts the link between the variable car1 and the object. The object stays where it is and car2 keeps pointing to it. In the seventh step the brand read through car2 is Ford.

For this reason the cost of assignment is also constant. However many fields the object has, b = a copies only one reference. If the object really has to be copied, a new object is created and the fields are transferred one by one; Java does not do this automatically with assignment.

The same rule applies when passing objects to methods. Java passes all arguments by value. If the argument is an object reference, the value copied is the reference. The method can change the shared object through this copy, but assigning a new object to its parameter does not affect the caller's variable:

class Box { int value; }
public class Problem4 {
  static void change(Box k) {
    k.value = 100;
    k = new Box();
    k.value = 7;
  }
  public static void main(String[] args) {
    Box x = new Box();
    x.value = 1;
    change(x);
    System.out.println(x.value);
  }
}
100

In the call change(x), k receives a copy of the reference in x. k.value = 100; writes to the shared object; because x points to the same object, the change is visible from main. k = new Box();, however, points only the local copy to a new object. The k.value = 7; after that writes to the new object; the object of x is not affected. The program prints 100.

4.1.7.2null and NullPointerException

null means that a reference variable points to no object. Reading a field or calling a method through a null reference causes an error at run time, because there is no object to read from.

public class Empty {
  String name;

  public static void main(String[] args) {
    Empty b = null;
    System.out.println(b.name.length());
  }
}
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "<local1>" is null
	at Empty.main(Empty.java:6)

The program compiles, because b has been given a value: null. When it runs, on line 6 it tries to read b.name and a NullPointerException is thrown. Since JDK 15 the message by default states the location of the error in detail: the name field could not be read because the variable is null. The notation "<local1>" in the message denotes local variable number 1 of main, that is, b. Had the program been compiled with debugging information (javac -g), the name of the variable would have appeared: because "b" is null.

If a local variable is used without ever being given a value, the situation is different: the program does not even compile (variable sb might not have been initialized). A NullPointerException, on the other hand, is an error the compiler cannot catch; it appears at run time. A field is its most frequent source: if a field of type String has not been given a value, its default value is null, and the first method called on it stops the program. The precaution is to check the reference before using it:

public class Empty2 {
  String name;

  public static void main(String[] args) {
    Empty2 b = new Empty2();
    if (b.name != null) {
      System.out.println(b.name.length());
    } else {
      System.out.println("name not set yet");
    }
    System.out.println(b.name.length());
  }
}
name not set yet
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>.name" is null
	at Empty2.main(Empty2.java:11)

The if block sees that name is null and takes the safe path. The last line, however, uses the same field without a check. This time the message says "<local1>.name": it is not b but the name field of b that is null.

main()bnullb.name→ NullPointerExceptionobject with no referencesgarbage collector removes it
Figure 4.1.13: A null reference points to no object; when b.name is read, a NullPointerException is thrown. On the right, the garbage collector removes the object that no reference points to.

An object that no reference points to can never be reached from the program again. The memory of such objects is reclaimed by the JVM's garbage collector when the time comes. In Java there is no need to delete an object by hand, and no way to do so. Had car2 also been set to null in the reference assignment trace, the last reference to the object would have been lost and the object would have become eligible for garbage collection. When the garbage collector will run is not known in advance; a program can only be sure that the object is no longer reachable.

4.1.7.3The this keyword

Definition 4.1.13

this is, inside an instance method or constructor, the reference to the object the method was called on (in a constructor, the object being created). There is no this in static methods.

this is most often used in constructors, when the name of the field and the name of the parameter are the same: this.name = name;. In this case the bare name name refers to the parameter, because the nearest declaration is the parameter. The parameter shadows the field of the same name. To reach the field one writes this.name. What happens if this is forgotten?

public class Shadow {
  private String name;

  public Shadow(String name) {
    name = name;            // forgot this!
  }

  public static void main(String[] args) {
    Shadow g = new Shadow("Ali");
    System.out.println(g.name);
  }
}
null
Shadow("Ali") framename"Ali"thisname = nameparameter to itselfShadow objectnamenullwith this.name = name, "Ali" would land here
Figure 4.1.14: In the constructor, name = name; assigns the parameter to itself; the object's name field stays null. Had this.name = name; been written, "Ali" would have gone to the object's field.

Both names on either side of the line name = name; are the parameter. The line assigns the parameter to itself and changes nothing. The object's name field is never touched; it stays at its default value null. The program prints null. The most dangerous part is this: the compiler gives no error for this line. The code compiles and runs; the error shows up only when the field is used, perhaps somewhere quite different, as a NullPointerException.

Had the field been final, the compiler would have caught the error. In the declaration private final String name; the field must receive a value in the constructor. Since name = name; gives the field no value, the compiler gives the message variable name might not have been initialized. Making fields that will never change final is therefore not only documentation but also a safety measure.

If there is no shadowing, writing this is optional. The bare model in a method body means this.model to the compiler. The trace below shows this step by step.

public class Student {
  private String name;

  public Student(String name) {
    this.name = name;
  }

  public void greet() {
    System.out.println("Hi, I am " + this.name);
  }

  public static void main(String[] args) {
    Student student1 = new Student("Ali");
    Student student2 = new Student("Ayşe");
    student1.greet();
    student2.greet();
  }
}
Hi, I am Ali
Hi, I am Ayşe
Table 4.1.12: Which object this points to in each call.
StepLineCall stackVariablesNew output
113: Student student1 = new Student("Ali");
4: public Student(String name) {
5: this.name = name;
main() → Student("Ali")name="Ali"—
214: Student student2 = new Student("Ayşe");main()student1=→#1, student2=→#2—
315: student1.greet();
8: public void greet() {
9: System.out.println("Hi, I am " + this.name);
main() → greet()student1=→#1, student2=→#2Hi, I am Ali
416: student2.greet();
8: public void greet() {
9: System.out.println("Hi, I am " + this.name);
main() → greet()student1=→#1, student2=→#2Hi, I am Ayşe

In the first step the constructor runs; this is the newly created object, and "Ali" is written to the field with this.name = name;. In the second step the second object is created with the same constructor; at that moment this points to object number 2. In the third step student1.greet() is called. The object to the left of the dot becomes the method's this, and Hi, I am Ali is printed. In the fourth step the same code runs with a different this and prints Hi, I am Ayşe. In this method, writing just name instead of this.name would give the same result, because the method has no parameter called name.

StackHeapgreet()thismain()student1student2Student #1name"Ali"Student #2name"Ayşe" StackHeapgreet()thismain()student1student2Student #1name"Ali"Student #2name"Ayşe"
Figure 4.1.15: Left: student1.greet(); this points to object number 1. Right: student2.greet(); the same method, but this points to object number 2.

4.1.7.4Passing the object with this

Because this is a reference, it can also be given to another method as an argument. This is the way to go when an object wants to introduce itself to another object.

public class Team {
  private String name;
  public Team(String name) {
    this.name = name;
  }
  public void addPlayer(Player player) {
    player.joinTeam(this);   // this object
  }
  public String getName() {
    return name;
  }
  public static void main(String[] args) {
    Team team = new Team("Giresunspor");
    Player player = new Player("Mert");
    team.addPlayer(player);
  }
}

In the same file, a second class that is not public:

class Player {
  private String name;
  Player(String name) {
    this.name = name;
  }
  void joinTeam(Team team) {
    String t = team.getName();
    System.out.println(name + " -> " + t);
  }
}
Mert -> Giresunspor

In the call team.addPlayer(player), the method's this is the team object. The player.joinTeam(this) in the body of the method hands this reference to the player. The team parameter of joinTeam now points to the same team object and reads the name with team.getName(). At this moment there are two separate this values in two frames: the this of addPlayer is the team, and the this of joinTeam is the player. The bare name in joinTeam is also the player's name. The output is Mert -> Giresunspor.

The Player class is defined inside the file Team.java, without public. A file can contain only one public class, but helper classes may be in the same file. These classes have package access; the other classes in the same folder can use them.

4.1.7.5Constructor chaining with this(...)

If a class has several constructors, most of them do the same things. Instead of copying the same assignments into every constructor, constructors can hand work over to each other.

Definition 4.1.14

this(...) is the notation that calls another constructor of the same class from inside a constructor. The sequence of constructors formed this way is called constructor chaining. this(...) must be the first statement of the constructor.

class Employee {
  private String name;
  private double salary;
  Employee(String name) {
    this(name, 20000.0);   // same-class constructor
  }
  Employee(String name, double salary) {
    this.name = name;        // init in one place
    this.salary = salary;
  }
}
Elif 20000.0

The common initial assignments are gathered in a single constructor; here this constructor is Employee(String, double). The other constructor adds the missing argument and delegates to it: this(name, 20000.0). Every employee created without a salary starts with 20000.0. If the default salary changes, a single number changes. If the assignment rules change, for example if one wants to check that the name is not empty, the check is written in a single constructor.

The chain has two rules, and the compiler checks both. this(...) must be on the first line of the constructor:

public class ThisFirst {
  int x;
  ThisFirst() { x = 1; this(2); }
  ThisFirst(int x) { this.x = x; }
}
ThisFirst.java:3: error: call to this must be first statement in constructor
  ThisFirst() { x = 1; this(2); }
                         ^
1 error

Constructors cannot call each other in a cycle; such a chain would never end:

public class ThisLoop {
  ThisLoop() { this(1); }
  ThisLoop(int x) { this(); }
}
ThisLoop.java:3: error: recursive constructor invocation
  ThisLoop(int x) { this(); }
                     ^
1 error

However many constructors the chain passes through, a single object is built. The body of the called constructor finishes first; then the remaining lines of the caller run. The trace below shows this.

class Book {
  String name;
  String author;
  int pageCount;
  public Book(String name) {
    this.name = name;
  }
  public Book(String name, String author) {
    this(name);  // constructor chaining
    this.author = author;
  }
}
// in main:
Book k2 = new Book("Nutuk", "Atatürk");
System.out.println(k2.name + " / "
    + k2.author + " / " + k2.pageCount);
Nutuk / Atatürk / 0
Table 4.1.13: Trace of the constructor chain in the call new Book("Nutuk", "Atatürk").
StepLineCall stackVariablesNew output
114: Book k2 = new Book("Nutuk", "Atatürk");main()k2=?—
28: public Book(String name, String author) {main() → Book(name, author)name="Nutuk", author="Atatürk"—
39: this(name); // constructor chainingmain() → Book(name, author) → Book(name)name="Nutuk"—
46: this.name = name;main() → Book(name, author) → Book(name)name="Nutuk"—
510: this.author = author;main() → Book(name, author)name="Nutuk", author="Atatürk"—
614: Book k2 = new Book("Nutuk", "Atatürk");main()k2=→Book—
715: System.out.println(k2.name + " / "
16: + k2.author + " / " + k2.pageCount);
main()k2=→BookNutuk / Atatürk / 0

In the first step new allocates a new Book object on the heap; the fields receive their default values: null, null, 0. In the second step, because the arguments are two Strings, the two-parameter constructor is chosen; this points to the new object. In the third step this(name) runs and the one-parameter constructor is called for the same object. The stack now holds two constructor frames one above the other; the this of both is the same object.

StackHeapBook(name)thisname"Nutuk"Book(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectnamenullauthornullpageCount0 StackHeapBook(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectname"Nutuk"author"Atatürk"pageCount0
Figure 4.1.16: Left: the deepest moment of the chain; two constructor frames are open and the this of both points to the same object. Right: the inner constructor has finished and the outer constructor has filled in the author field.

In the fourth step the inner constructor writes "Nutuk" to the name field with this.name = name; and ends. In the fifth step the outer constructor resumes where it left off and runs its remaining line: this.author = author;. In the sixth step both constructors have finished; the reference that is the value of the new expression is assigned to k2. In the seventh step the fields are read. Because no constructor gave pageCount a value, its default value is printed: Nutuk / Atatürk / 0.

There is also a side effect here. The initial values on the field declaration lines and the instance initializers run once, in the constructor of the chain that does not start with this(...), immediately before the body of that constructor. A constructor that starts with this(...) leaves this job to the constructor at the end of the chain. So however long the chain is, the initializers run exactly once for each object.

4.1.8Comparing objects: == and equals

Comparing two int variables with == compares the numbers. Comparing two reference variables with ==, however, compares not the objects but the references in the variables' boxes. The question is not "do these two objects have the same content?" but "do these two variables point to the same object?"

Definition 4.1.15

Reference equality means two references pointing to the same object and is tested with ==. Content equality means two objects carrying the same value in meaning and is tested with the equals() method. What equals counts as "the same" is decided by the programmer who writes the class.

In the program below, the Person class writes its own equals method: it counts two people as equal if their names and ages are the same. The Person0 class, on the other hand, does not write equals. The last part of the program reads a word from the keyboard and compares it with a text literal.

import java.util.Objects;
import java.util.Scanner;
class Person {
  private String name;
  private int age;
  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Person)) return false;
    Person k = (Person) o;
    return age == k.age && Objects.equals(name, k.name);
  }
  @Override
  public int hashCode() {
    return Objects.hash(name, age);
  }
  @Override
  public String toString() {
    return name + " (" + age + ")";
  }
}
class Person0 {
  String name;
  Person0(String name) { this.name = name; }
}
public class Equality {
  public static void main(String[] args) {
    Person k1 = new Person("Ali", 20);
    Person k2 = new Person("Ali", 20);
    Person k3 = k1;
    System.out.println(k1 == k3);
    System.out.println(k1 == k2);
    System.out.println(k1.equals(k2));
    System.out.println(k1.hashCode() == k2.hashCode());
    System.out.println(k1);
    Person0 a = new Person0("Ali");
    Person0 b = new Person0("Ali");
    System.out.println(a.equals(b));
    Scanner in = new Scanner(System.in);
    String input = in.next();
    System.out.println(input == "Java");
    System.out.println(input.equals("Java"));
  }
}

When Java is typed at the keyboard, the program prints:

true
false
true
true
Ali (20)
false
false
true
StackHeapmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20
Figure 4.1.17: k1 and k3 point to the same Person object, k2 to a separate object with the same content.
Table 4.1.14: Comparison results for three references.
ExpressionResultWhy
k1 == k3trueThe two variables point to the same object.
k1 == k2falseDifferent objects; the references differ even though the contents are the same.
k1.equals(k2)trueequals has been overridden; the name and age are the same.

The methods equals, hashCode, toString and getClass come to every class from Object, the topmost class of Java. The Object version of equals compares only references; that is, it behaves like ==. Because the Person0 class does not write equals, a.equals(b) gives false: there are two separate objects and the Object version does not look at the content. If the objects of a class are to be compared by content, equals must be overridden in that class.

The equals in Person works in three steps. First it checks with this == o whether it is the same object; if so, it returns true immediately. Then it checks with instanceof whether the incoming object is a Person; if not, or if o is null, it returns false. In the last step it compares the fields. age is an int, so it is compared with ==; name is a String, so it is compared with Objects.equals. This helper method also works safely when one of the two sides is null. The type of the parameter is Object, not Person. Had the type been written Person, the method would not have overridden the equals of Object but only overloaded it; the @Override annotation catches this error at compile time.

When equals is overridden, hashCode must be written too. The rule is: two objects that are equal according to equals must have equal hashCode values. The fourth line of the program verifies this. If the rule is broken, collections such as HashMap and HashSet look for equal objects in different places and fail to find them. Objects.hash(name, age) produces a value from the same fields used in equals. toString gives the text form of the object; println(k1) calls this method automatically and prints Ali (20). Had toString not been written, a text made of the class name and a number, such as Person@1b6d3586, would have been seen.

String and the wrapper classes are also objects and obey the same rule. The last two lines of the program show this. The "Java" read from the keyboard is a new String object created at run time. The "Java" literal in the code is another object. Although their contents are the same, == gives false and equals gives true. That == sometimes gives true when two text literals are compared is because Java stores the same literal as a single object. This is not a rule but an implementation detail; texts are always compared with equals.

4.1.9Wrapper classes

4.1.9.1The object counterpart of a primitive type

Definition 4.1.16

A wrapper class is a class that carries the value of a primitive type inside an object. Each of the eight primitive types in Java has a wrapper class.

Table 4.1.15: Primitive types and their wrapper classes.
Primitive typeWrapper classPrimitive typeWrapper class
byteBytefloatFloat
shortShortdoubleDouble
intIntegercharCharacter
longLongbooleanBoolean

Most of the names are the primitive type with a capital first letter; the two exceptions are Integer and Character. These classes are needed for three reasons:

  • Sometimes an object is required. Generic collections such as ArrayList<Integer> cannot take a primitive type; the notation ArrayList<int> does not compile.
  • The "no value" case. null cannot be assigned to a primitive type; it can be assigned to a variable of the wrapper type. If the grade of an exam has not been entered yet, Integer grade = null; shows this explicitly. With int and a 0, "scored zero" and "no grade yet" could not be told apart.
  • Helper methods and constants. Integer.parseInt("12") converts a text to a number, Integer.MAX_VALUE gives the largest int value, and Character.isDigit(c) tells whether a character is a digit.
StackHeapint num42Integer wInteger objectvalue = 42the value itselfw may also be null
Figure 4.1.18: An int value is kept directly on the stack. An Integer variable points to an object on the heap; the value is inside that object, and null can also be assigned to the variable.

Wrappers have a price. As seen in Figure 4.1.18, an int value sits in the variable's box; an Integer requires a separate object, a reference leading to it and an indirect access when read. In a loop that processes millions of numbers this difference is measurable. For this reason the primitive type is preferred unless there is a need.

4.1.9.2Autoboxing and unboxing

Definition 4.1.17

Autoboxing is the conversion of a primitive value into a wrapper object, when needed, through a call the compiler inserts. Unboxing is the conversion of the value in a wrapper object back into the primitive type.

public class Wrappers {
  public static void main(String[] args) {
    // an int variable
    int num = 42;
    // using the Integer wrapper
    Integer w1 = Integer.valueOf(num);
    // Autoboxing (automatic)
    Integer w2 = num;
    // Unboxing (explicit and automatic)
    int n2 = w2.intValue();
    int n3 = w2;
    System.out.println(n2 + n3);
    System.out.println(w1.equals(w2));
    System.out.println(Integer.parseInt("123") + 1);
    System.out.println(Integer.MAX_VALUE);
    System.out.println(Character.isDigit('7'));
    System.out.println(Double.parseDouble("2.5") * 2);
    Integer empty = null;      // an int can't be null
    System.out.println(empty);
  }
}
84
true
124
2147483647
true
5.0
null

The line Integer w2 = num; assigns an int to an Integer variable. The compiler silently turns this line into the call Integer.valueOf(num); this is autoboxing. The line int n3 = w2; is turned into the call w2.intValue(); this is unboxing. The explicit forms (Integer.valueOf, intValue()) and the automatic forms produce the same code.

The first line of the output is 42 + 42 = 84. The contents of the two wrappers are the same: true. The text "123" is converted to a number and 1 is added: 124. The fourth line is the largest int value: 2147483647, that is, 231 − 1. '7' is a digit: true. "2.5" is converted to double and multiplied by 2: 5.0. On the last line an Integer with the value null is printed. println prints a null reference as the word null; since there is no unboxing here, there is no error either. Assigning the same value to an int does not compile:

public class IntNull {
  public static void main(String[] args) {
    int empty = null;
  }
}
IntNull.java:3: error: incompatible types: <null> cannot be converted to int
    int empty = null;
              ^
1 error

4.1.9.3The Integer cache and the null trap

Automatic conversions shorten the code, but they hide two traps. Both come from forgetting that wrappers are objects.

import java.util.ArrayList;
public class Pitfalls {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    list.add(5);                 // autoboxing: 5 -> Integer
    int first = list.get(0);       // unboxing: Integer -> int
    System.out.println(first + 1);
    Integer a = 127, b = 127;
    Integer c = 128, d = 128;
    System.out.println(a == b);
    System.out.println(c == d);
    System.out.println(c.equals(d));
    Integer empty = null;
    int x = empty;                  // NullPointerException
  }
}
6
true
false
true
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "<local7>" is null
	at Pitfalls.main(Pitfalls.java:14)

The first three lines are fine: list.add(5) boxes the 5, list.get(0) returns the object, and it is unboxed when assigned to int first; first + 1 is 6. The next two comparisons, however, are surprising: a == b gives true and c == d gives false. Although the values are equal, why does the second comparison come out false? The trace below shows it step by step.

Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
int t = c + d;
System.out.println(t);
Integer empty = null;
int x = empty;
Table 4.1.16: Trace of the Integer cache and of unboxing null.
StepLineCall stackVariablesNew output
11: Integer a = 127, b = 127;—a=→cache(127), b=→cache(127)—
22: Integer c = 128, d = 128;—a=→cache, b=→cache, c=→#1, d=→#2—
33: System.out.println(a == b);—a=→cache, b=→cachetrue
44: System.out.println(c == d);—c=→#1, d=→#2false
55: System.out.println(c.equals(d));—c=→#1, d=→#2true
66: int t = c + d;—c=→#1, d=→#2, t=256—
77: System.out.println(t);—t=256256
88: Integer empty = null;—t=256, empty=null—
99: int x = empty;—empty=null, x=?Exception in thread "main" ⏎ java.lang.NullPointerException

In the first step Integer a = 127 turns into the call Integer.valueOf(127) through autoboxing. The valueOf method does not create a new object every time for values between −128 and 127; the objects for these values are ready in a cache. a and b receive the same object from the cache. In the second step 128 is outside this range; valueOf creates a new object on each call, and c and d point to two separate objects.

StackHeapmain()abcdcache: 127value127Integer #1value128Integer #2value128c == d → false (#1 ≠ #2) StackHeapmain()abcdt256emptynullx?cache: 127value127Integer #1value128Integer #2value128empty.intValue() → NullPointerException
Figure 4.1.19: Left, c == d: the values are the same (128), but the two arrows go to two separate objects; a and b share the single object in the cache. Right, empty points to no object; when int x = empty tries to unbox, a NullPointerException is thrown.

In the third and fourth steps == compares references. The result is true because a and b point to the same object, and false because c and d point to different objects. The values are the same, the objects are different. In the fifth step c.equals(d) compares the int values inside the objects and gives true. The trap is here: a trial with small numbers gives the impression that == works correctly; when the code meets large numbers it silently produces a wrong result. Wrapper objects are always compared with equals.

In the sixth step int t = c + d; runs. The + operator does not work with objects; both objects are unboxed (intValue()) and 128 + 128 = 256 is found. t is a primitive int and its value sits in its box on the stack. The same rule applies in comparison: if an Integer is compared with an int using ==, the Integer is unboxed and the numbers are compared. In the seventh step 256 is printed.

In the eighth step Integer empty = null; runs. null can be assigned to a wrapper variable. In the ninth step int x = empty; is quietly turned into the call empty.intValue(). There is no object to point to and a NullPointerException is thrown. The message names this hidden call explicitly: Cannot invoke "java.lang.Integer.intValue()". That a line in which no method call is visible in the code gives this error is the most dangerous side of automatic unboxing.

Common mistake

Comparing wrapper objects with ==. Integer values in the range −128…127 seem to give the right result with ==; outside the range the same values give false. The upper limit of the cache can be raised with a JVM setting, so relying on the limit is not right either. Content is always compared with equals.

4.1.10Records and enums

Some classes are written only to carry a few pieces of data together: the two coordinates of a point, the name and number of a student. Some types, on the other hand, take one of a known, limited set of values: the days of the week, the seasons. Java offers a short and safe notation for each of these cases.

4.1.10.1Records

Definition 4.1.18

A record (Java 16 and later) is a kind of class designed to write classes that only carry data in a short form. All the fields of a record are private final and it has no setters; its objects are therefore immutable.

record Point(double x, double y) { }

This single line defines a record with two double components named x and y. From this definition the compiler generates two private final fields and a constructor with two parameters. It also adds the accessors x() and y(), an equals that compares by content, a matching hashCode and a readable toString. The names of the accessors do not start with get; they carry the name of the component. Writing the same class by hand would take about 30 lines.

public class RecordTest {
  public static void main(String[] args) {
    Point p1 = new Point(1.0, 2.5);
    Point p2 = new Point(1.0, 2.5);
    boolean same = p1.equals(p2);
    System.out.println(same);
    System.out.println(p1 == p2);
    System.out.println(p1);
    System.out.println(p1.x() + p1.y());
  }
}
true
false
Point[x=1.0, y=2.5]
3.5

The two points are created with the same coordinates. equals gives true because it compares content, and == gives false because it compares references. println(p1) calls the toString that the record generates: Point[x=1.0, y=2.5]. The last line adds the two values read with the accessors: 3.5.

If an attempt is made to change a field of a record, the program does not compile:

record Point(double x, double y) { }
public class RecordChange {
  public static void main(String[] args) {
    Point n = new Point(1.0, 2.5);
    n.x = 3.0;
  }
}
RecordChange.java:5: error: x has private access in Point
    n.x = 3.0;
     ^
1 error

If a record needs a new value, a new record is created. A record can also have its own methods. To add a check to the constructor, a compact constructor is defined without repeating the component list:

record Point(double x, double y) {
  Point {
    if (Double.isNaN(x) || Double.isNaN(y))
      throw new IllegalArgumentException("NaN not allowed");
  }
  double distance() { return Math.sqrt(x * x + y * y); }
  Point shift(double dx) { return new Point(x + dx, y); }
}
public class RecordExtra {
  public static void main(String[] args) {
    Point n = new Point(3.0, 4.0);
    Point m = n.shift(1.0);
    System.out.println(n + " " + n.distance());
    System.out.println(m);
    System.out.println(n.hashCode() == new Point(3.0, 4.0).hashCode());
  }
}
Point[x=3.0, y=4.0] 5.0
Point[x=4.0, y=4.0]
true

The Point { ... } block is the compact constructor. The compiler adds the parameters, and the block does only the check; the assignment to the fields is done automatically after the block ends. distance() computes the distance of the point from the origin: √(3² + 4²) = 5.0. shift does not change the object; it returns a new Point, and n keeps its old value. The last line verifies that the hashCode values of two equal records are also equal.

4.1.10.2enum

Definition 4.1.19

An enum (enumeration type) is a special kind of class that represents a fixed, limited set of values. Each value is the one and only object of that type for the whole program.

enum Weekday {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
  FRIDAY, SATURDAY, SUNDAY
}
public class DayTest {
  public static void main(String[] args) {
    Weekday[] allDays = Weekday.values();
    Weekday thu = Weekday.valueOf("THURSDAY");
    System.out.println(allDays.length + " days");
    System.out.println(thu + " " + thu.ordinal());
    for (Weekday day : allDays) {
      boolean weekend = day == Weekday.SATURDAY
          || day == Weekday.SUNDAY;
      if (weekend) {
        System.out.println(day + ": weekend");
      }
    }
  }
}
7 days
THURSDAY 3
SATURDAY: weekend
SUNDAY: weekend

The Weekday type has only seven values and no other value can be created. It would also have been possible to keep the days of the week as numbers 0–6 in an int, but then the compiler could not catch a meaningless assignment such as day = 9. Only values of an enum type can be assigned to a variable of that type.

Three useful methods come with every enum type. values() returns all the values as an array in declaration order; a loop can be run over it. valueOf("THURSDAY") converts a text into the value of the same name. ordinal() gives the value's position number starting from 0: THURSDAY is 3 because it is the fourth value. Because every value is a single object, enum values are compared safely with ==; the weekend check in the loop is written this way.

Because an enum is a class, it can have fields, a constructor and methods. In the example below each planet carries its own gravity factor. The program also shows the use of enum with switch and that valueOf looks for the name exactly.

enum Planet {
  MERCURY(0.38), EARTH(1.0), MARS(0.38);
  private final double gravity;
  Planet(double gravity) { this.gravity = gravity; }
  double weight(double mass) { return mass * gravity; }
}
public class EnumFeatures {
  public static void main(String[] args) {
    Planet g = Planet.MARS;
    switch (g) {
      case EARTH -> System.out.println("home");
      case MARS -> System.out.println("red");
      default -> System.out.println("other");
    }
    System.out.println(g.weight(70.0));
    System.out.println(Planet.valueOf("Mars"));
  }
}
red
26.6
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Planet.Mars
	at java.base/java.lang.Enum.valueOf(Enum.java:293)
	at Planet.valueOf(EnumFeatures.java:1)
	at EnumFeatures.main(EnumFeatures.java:16)

The parentheses next to the values are arguments passed to the constructor. The constructor of an enum is always private; new Planet(...) cannot be written from outside. In switch, the type name is not written in the case labels: case MARS. 70 × 0.38 = 26.6 is computed. On the last line valueOf("Mars") is called; since the name of the value is MARS, no match is found and an IllegalArgumentException is thrown. valueOf is case-sensitive.

4.1.11Inner classes

Definition 4.1.20

An inner class is a class defined inside another class. An inner class can directly access the fields and methods of the outer class, including the private ones.

Inner classes are used to gather, inside a class, helper classes that serve only that class. The most common example is the listener classes in graphical interfaces, which carry the code that runs when a button is clicked. There are four kinds of inner class, depending on where they are defined.

Table 4.1.17: Kinds of inner classes.
KindWhere defined?How created?
static inner classIn the class body, with staticWithout an outer object: new Outer.StaticInner()
Member inner classIn the class body, without staticThrough an outer object: outer.new MemberInner()
Local inner classInside a methodOnly from inside that method
Anonymous inner classInside an expression, namelessA single object where it is defined; implements an interface or abstract class

4.1.11.1static inner class

public class Outer {
  // a static inner class inside Outer
  static class StaticInner {
    void display() {
      System.out.println("Static Inner Class");
    }
  }

  public static void main(String[] args) {
    // access without an Outer instance
    Outer.StaticInner staticInner = new Outer.StaticInner();
    staticInner.display();
  }
}
Static Inner Class

A static inner class is like an ordinary class placed inside the outer class. It can be created without an object of the outer class: new Outer.StaticInner(). Its full name is Outer.StaticInner; the outer class acts here as a namespace. Because it is not tied to an outer object, it can directly access only the static members of the outer class. If it tries to read an instance field of the outer class, the familiar message results:

public class InnerStaticOuter {
  private int count = 5;
  static class StaticInner {
    void display() { System.out.println(count); }
  }
}
InnerStaticOuter.java:4: error: non-static variable count cannot be referenced from a static context
    void display() { System.out.println(count); }
                                        ^
1 error

4.1.11.2Member inner class

public class Outer {
  private int count = 5;          // outer's private field

  class MemberInner {            // member inner class
    void display() {
      System.out.println("Member Inner Class, count = " + count);
    }
  }

  public static void main(String[] args) {
    // access via an Outer instance
    Outer outer = new Outer();
    Outer.MemberInner memberInner = outer.new MemberInner();
    memberInner.display();
  }
}
Member Inner Class, count = 5

A member inner class is defined as a member of the outer class without static. Every member inner object is tied to an outer object. For this reason an outer object is needed when it is created, and the notation is unusual: outer.new MemberInner(). Thanks to this tie, display() can read the private count field of the outer object. Writing new MemberInner() directly in main does not compile:

public class MemberInnerStatic {
  private int count = 5;
  class MemberInner {
    void display() { System.out.println(count); }
  }
  public static void main(String[] args) {
    MemberInner m = new MemberInner();
  }
}
MemberInnerStatic.java:7: error: non-static variable this cannot be referenced from a static context
    MemberInner m = new MemberInner();
                    ^
1 error

The message again mentions this. new MemberInner() means this.new MemberInner() inside the class: the inner object is to be tied to this. Because main is static, there is no this. The trace below shows how the tie is made.

public class Outer {
    private int count = 5;
    class MemberInner {
        void display() {
            System.out.println("count = " + count);
        }
    }
    public static void main(String[] args) {
        Outer o1 = new Outer();
        Outer o2 = new Outer();
        o2.count = 8;
        Outer.MemberInner m = o2.new MemberInner();
        m.display();
    }
}
count = 8
Table 4.1.18: Tying a member inner object to the outer object.
StepLineCall stackVariablesNew output
19: Outer o1 = new Outer();—o1=→#1—
210: Outer o2 = new Outer();—o1=→#1, o2=→#2—
311: o2.count = 8;—o1=→#1, o2=→#2—
412: Outer.MemberInner m = o2.new MemberInner();—o2=→#2, m=→#3—
513: m.display();
4: void display() {
—this=→#3—
65: System.out.println("count = " + count);—this=→#3, count=Outer.this.count=8count = 8

In the first and second steps two Outer objects are created; both have their own count field and start with 5. In the third step o2.count = 8; changes only object number 2. Because main is inside Outer, it can write to the private field. In the fourth step o2.new MemberInner() creates the inner object. The inner object keeps the reference of the outer object that created it in a hidden field. The name of this field in Java is Outer.this.

StackHeapmain()o1o2mOuter #1count5Outer #2count8MemberInner #3Outer.this StackHeapdisplay()thismain()o1o2mOuter #1count5Outer #2count8MemberInner #3Outer.thiscount = Outer.this.count = 8
Figure 4.1.20: Left: the inner object (#3) has been created; the hidden Outer.this field points to outer object number 2. Right: display() is running: count means Outer.this.count, and the arrow goes to object number 2, to the value 8.

In the fifth step m.display() is called. The method's this is the inner object. The inner class has no count field of its own. In the sixth step the compiler resolves the bare name count as Outer.this.count: the arrow in the inner object's hidden field goes to outer object number 2, and count = 8 is printed. Had the inner object been created with o1.new MemberInner(), the arrow would go to object number 1 and 5 would be printed. When the inner and outer classes have fields of the same name, the inner class's own field is distinguished by the notation this.x and the outer object's field by Outer.this.x.

4.1.11.3Local and anonymous inner classes

public class Outer {
  void outerMethod() {
    class LocalInner {         // defined inside the method
      void display() {
        System.out.println("Local Inner Class");
      }
    }
    // usable only inside this method
    LocalInner localInner = new LocalInner();
    localInner.display();
  }

  public static void main(String[] args) {
    Outer outer = new Outer();
    outer.outerMethod();
  }
}
Local Inner Class

A local inner class is defined inside a method and can be used only from inside that method. Outside the method the name LocalInner is unknown:

public class LocalOuter {
  void outerMethod() {
    class LocalInner { void display() { } }
    new LocalInner().display();
  }
  void other() {
    LocalInner li = new LocalInner();
  }
}
LocalOuter.java:7: error: cannot find symbol
    LocalInner li = new LocalInner();
    ^
  symbol:   class LocalInner
  location: class LocalOuter
LocalOuter.java:7: error: cannot find symbol
    LocalInner li = new LocalInner();
                        ^
  symbol:   class LocalInner
  location: class LocalOuter
2 errors

A local inner class is used for a small helper type that is needed several times inside one method. Its scope is like that of a local variable: it ends at the end of the block in which it is defined.

interface MyInterface {
  void myMethod();
}

public class Outer {
  public static void main(String[] args) {
    // usually implements an interface or abstract class
    MyInterface myInterface = new MyInterface() {
      @Override
      public void myMethod() {
        System.out.println("Anonymous Inner Class");
      }
    };
    myInterface.myMethod();
    MyInterface short = () -> System.out.println("Lambda");
    short.myMethod();
    System.out.println(myInterface.getClass().getName());
  }
}
Anonymous Inner Class
Lambda
Outer$1

An anonymous class is a class without a name; a single object of it is created where it is defined. It usually implements an interface or an abstract class. The notation new MyInterface() { ... } means "define a nameless class that implements MyInterface and create an object of it". The bodies of the interface's methods are written inside the curly braces. The semicolon at the end belongs to the assignment statement; if it is forgotten, a compile error results.

The nameless class also has a name given by the compiler. The last line of the program prints it: Outer$1, that is, the first anonymous class inside Outer. A separate file called Outer$1.class is also created in the build folder. For interfaces that have only a single abstract method, since Java 8 there is a shorter notation: the lambda expression. () -> System.out.println("Lambda") does the same job in one line.

4.1.12Kinds of classes and design

4.1.12.1One class, many types

An object can belong to only a single class: it is an object of whichever class it was created from with new. But it can have many types. In the definitions below, Dog derives from Animal and implements the Runner interface; Animal implements the Printable and Serializable interfaces.

interface Printable { ... }
interface Runner { ... }
class Animal implements Printable, Serializable { ... }
class Dog extends Animal implements Runner { ... }
var winner = new Dog(...);
Object«interface»Printable«interface»SerializableAnimal«interface»RunnerDogextendsextends
Figure 4.1.21: UML type hierarchy. The solid line with an empty triangle shows inheritance (extends), the dashed line shows the implementation of an interface (implements). Every class derives from Object at the top.

The object the variable winner points to belongs only to the class Dog. But the types of this object are Dog, Runner, Animal, Printable, Serializable and Object. The instanceof operator gives true for all six. A small program that fills the definitions with real bodies and tests them:

import java.io.Serializable;
interface Printable { }
interface Runner { }
class Animal implements Printable, Serializable { }
class Dog extends Animal implements Runner { }
public class Types {
  public static void main(String[] args) {
    var winner = new Dog();
    Object o = winner;
    System.out.println((o instanceof Dog) + " " + (o instanceof Runner) + " " + (o instanceof Animal)
        + " " + (o instanceof Printable) + " " + (o instanceof Serializable) + " " + (o instanceof Object));
    System.out.println(winner.getClass().getName());
  }
}
true true true true true true
Dog

That an object can be seen as more than one type is the basis of polymorphism. A variable of type Animal can point to a Dog object; a method that expects a Runner can take a Dog. The conclusion is this: "class" and "type" are not the same concept.

4.1.12.2Kinds of classes

Classes are written in different forms depending on their purpose. Table 4.1.19 lists the kinds most often met. A class can belong to several kinds at once: Math is both a utility class and final.

Table 4.1.19: Kinds of classes.
KindPropertyExample
Enumeration (enum)Its values are a fixed set of objectsenum Day { MONDAY, TUESDAY, ... }
SingletonOnly one object can be createdprivate constructor + static single object
Abstract (abstract)No object of its own can be createdabstract class Shape
Sealed (sealed, Java 17+)Its subtypes are a fixed setsealed interface Move permits Walk, Run
finalNo subclass can be derivedfinal class String
Record (record)Its objects are immutablerecord Point(double x, double y)
UtilityContains only static methodsMath, Arrays
ApplicationContains the main methodThe class where the program starts
final class Utils {             // utility, final class
  private Utils() { }         // no instances
  static int square(int x) { return x * x; }
}
class Settings {                   // singleton
  private static final Settings INSTANCE = new Settings();
  private Settings() { }
  static Settings get() { return INSTANCE; }
}
abstract class Shape {            // abstract class
  abstract double area();
}
// sealed (Java 17+)
sealed interface Move permits Walk, Run { }
final class Walk implements Move { }
final class Run implements Move { }
public class Kinds {           // application class
  public static void main(String[] args) {
    System.out.println(Utils.square(7));
    System.out.println(Settings.get() == Settings.get());
  }
}
49
true

Utils is a utility class. Because its constructor is private, no object of it can be created from outside; no object is needed anyway, because all its methods are static. Because it is final, no subclass can be derived from it either. The compiler enforces both restrictions:

final class Utils {
  private Utils() { }
}
class SubUtils extends Utils { }
public class FinalExtend { }
FinalExtend.java:4: error: cannot inherit from final Utils
class SubUtils extends Utils { }
                         ^
FinalExtend.java:4: error: Utils() has private access in Utils
class SubUtils extends Utils { }
^
2 errors

Settings is a singleton class. The single object is created, when the class is loaded, in a private static final field. Because the constructor is private, no other object can be created; the object is reached only through get(). Because get() returns the same reference on every call, Settings.get() == Settings.get() gives true. If new Settings() is written in another class:

SingletonNew.java:8: error: Settings() has private access in Settings
    Settings a = new Settings();
                ^
1 error

Shape is an abstract class: the method area() has no body, because the area of a "shape" cannot be computed; only the area of a circle or a square can. An object cannot be created from an abstract class:

AbstractNew.java:6: error: Shape is abstract; cannot be instantiated
    Shape s = new Shape();
              ^
1 error

Move is a sealed interface. The permits list names the types that may implement it: only Walk and Run. If a class that is not in the list tries to implement Move, it does not compile:

SealedViolation.java:4: error: class is not allowed to extend sealed class: Move (as it is not listed in its 'permits' clause)
final class Flight implements Move { }
      ^
1 error

Sealed types are used where the set of subtypes is closed by design. Because the compiler knows all the possible subtypes, it can check, for example, whether every case of a switch has been covered.

4.1.12.3A design example: Rational

By putting together the pieces so far, a class can be designed from scratch. The Rational class represents fractions of the form num/den. Three questions are asked when designing a class:

  • Interface: What will the code that uses the class see? Here a public constructor, add, which adds two fractions, and toString, which gives the fraction as text.
  • Representation: How will the data be stored? Two private int fields: num and den. The constructor stores the fraction in lowest terms; so every object is always in its simplest form.
  • Implementation: The bodies of the methods and the helpers not exposed to the outside. The greatest common divisor needed for simplification is found with Euclid's algorithm in a hidden gcd method.
public class Rational {
  // Representation: hidden fields
  private int num, den;
  // Interface: public constructor and methods
  public Rational(int num, int den) {
    int g = gcd(Math.abs(num), Math.abs(den));
    this.num = num / g;
    this.den = den / g;
  }
  public Rational add(Rational d) {
    int newNum = num * d.den + d.num * den;
    return new Rational(newNum, den * d.den);
  }
  @Override
  public String toString() { return num + "/" + den; }
  // Implementation detail: hidden helper
  private static int gcd(int a, int b) {
    while (b != 0) { int k = a % b; a = b; b = k; }
    return a;
  }
}

The test program creates a = new Rational(8, 10) and b = new Rational(2, 3) and first calls println(a), then println(a.add(b)). The whole output of the program is this:

4/5
22/15
11/12 3/4
-2/3 1/-3 0/1
1/1

The first two lines of the output are these two calls. 8/10 has been simplified and stored as 4/5. 4/5 + 2/3 = (4 × 3 + 2 × 5) / (5 × 3) = 22/15; since 22 and 15 have no common divisor, the fraction stays in lowest terms. The third line is produced by the same call with a = (6, 8) and b = (1, 6). This call is traced step by step below.

public Rational(int num, int den) {
    int g = gcd(Math.abs(num), Math.abs(den));
    this.num = num / g;
    this.den = den / g;
}
private static int gcd(int a, int b) {
    while (b != 0) { int k = a % b; a = b; b = k; }
    return a;
}
public Rational add(Rational d) {
    int newNum = num * d.den + d.num * den;
    return new Rational(newNum, den * d.den);
}
Rational a = new Rational(6, 8);   // main
Rational b = new Rational(1, 6);
System.out.println(a.add(b) + " " + a);
Table 4.1.20: Trace of the Rational constructor, gcd and add. The line numbers are the lines of the shortened code above.
StepLineCall stackVariablesNew output
114: Rational a = new Rational(6, 8); // main
1: public Rational(int num, int den) {
—num=6, den=8—
22: int g = gcd(Math.abs(num), Math.abs(den));
6: private static int gcd(int a, int b) {
—a=6, b=8—
37: while (b != 0) { int k = a % b; a = b; b = k; }—a=8, b=6, k=6—
47: while (b != 0) { int k = a % b; a = b; b = k; }—a=6, b=2, k=2—
57: while (b != 0) { int k = a % b; a = b; b = k; }—a=2, b=0, k=0—
68: return a;
3: this.num = num / g;
4: this.den = den / g;
—g=2, this.num=3, this.den=4—
715: Rational b = new Rational(1, 6);—a=→#1 (3/4), b=→#2 (1/6)—
816: System.out.println(a.add(b) + " " + a);
10: public Rational add(Rational d) {
11: int newNum = num * d.den + d.num * den;
—this=→#1, d=→#2, newNum=22—
912: return new Rational(newNum, den * d.den);
1: public Rational(int num, int den) {
2: int g = gcd(Math.abs(num), Math.abs(den));
—num=22, den=24, g=2—
1016: System.out.println(a.add(b) + " " + a);—a=→#1 (3/4), result=→#3 (11/12)11/12 3/4

In the first step new Rational(6, 8) allocates the object; the fields are 0 at first and the constructor's parameters are 6 and 8. In the second step the hidden helper gcd(6, 8) is called. Because this method is private, the code that uses the class cannot see or call it. It is static because it works only with its parameters; it touches no object's fields.

The third, fourth and fifth steps are the three rounds of Euclid's algorithm. In each round k = a % b is computed, then a ← b and b ← k. In the first round 6 % 8 = 6; the numbers just swap places: a = 8, b = 6. In the second round 8 % 6 = 2: a = 6, b = 2. In the third round 6 % 2 = 0: a = 2, b = 0. When b becomes zero the loop ends and a, that is, 2, is returned. In the sixth step the constructor divides the numerator and denominator by 2 and stores them: the object becomes 3/4.

StackHeapRational()num6den8g2main()a?Rational #1num3den46/8 → 6/2 = 3, 8/2 = 4 StackHeapRational()num22den24g2add()thisdnewNum22main()abRational #1num3den4Rational #2num1den6Rational #3num11den12gcd(22, 24) = 2 → 11/12 StackHeapmain()abRational #1num3den4Rational #2num1den6Rational #3num11den12add() returned a new object; a is still 3/4
Figure 4.1.22: From left to right: the first object has been simplified, 3/4; a new Rational(22, 24) is being built inside add; the result 11/12 is a separate object, and a is still 3/4.

The seventh step does the same work for (1, 6). gcd(1, 6) returns 1; the fraction is already in lowest terms and is stored as 1/6. In the eighth step a.add(b) is called. The method's this is object number 1 and the parameter d is object number 2. newNum = num * d.den + d.num * den = 3 × 6 + 1 × 4 = 22. d.den is a private field of another object, but it can be read because the code is inside the same class.

In the ninth step new Rational(22, 24) is called. The constructor runs gcd again: b takes the values 24, 22, 2, 0 in turn and the result is 2. The new object is stored as 11/12. In the tenth step println prints first the returned result and then a: 11/12 3/4. add has not changed the existing object; it has returned a new one. Rational has no setters and no method changes the fields; its objects are immutable in this sense.

In terms of cost, the loop of gcd runs a number of rounds proportional to the number of digits of the smaller number; the number of rounds of Euclid's algorithm is O(log min(a, b)). The constructor and add are therefore very fast. Every call of add creates a new object; this is the price of the immutable design. In return, even if a variable holding a fraction is shared elsewhere, its value never changes unexpectedly.

The last two lines of the test program try boundary cases. new Rational(-4, 6) correctly becomes -2/3. For new Rational(0, 5), gcd(0, 5) = 5 is found and the fraction is stored as 0/1. On the last line 1/2 + 1/2 = 4/4 is computed and, simplified, becomes 1/1. These trials expose two limits of the design. new Rational(3, -9), however, is stored as 1/-3: the constructor does not move the sign from the denominator to the numerator. Because the same value can be stored in two different forms, an equals written for this class might count equal fractions as different. The fix is to flip the signs of both when den is negative in the constructor. The second limit is a zero denominator. In the call new Rational(0, 0), gcd(0, 0) returns 0 and the division gives this error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Rational.<init>(RationalZero.java:10)
	at RationalZero.main(RationalZero.java:3)

A constructor that does not allow a zero denominator should report the error at the moment the fraction is created and with a meaningful message. For example, the first line of the constructor could be if (den == 0) throw new IllegalArgumentException("den cannot be 0");. Keeping the representation hidden makes these fixes easy: the change affects only the constructor, and the code that uses the class stays as it is.

4.1.13Sample problems and exercises

Example 4.1.2

What does the following program print?

class Counter {
  static int total = 0;
  int count = 0;
  void inc() { total++; count++; }
}
public class Problem1 {
  public static void main(String[] args) {
    Counter a = new Counter(), b = new Counter();
    a.inc(); a.inc(); b.inc();
    System.out.print(a.count + " " + b.count);
    System.out.println(" " + Counter.total);
  }
}
2 1 3

count is an instance field; every object has a separate copy. Because a.inc() is called twice and b.inc() once, a.count is 2 and b.count is 1. total, on the other hand, is static; all three calls increment the same box and its value becomes 3. The output is 2 1 3.

Example 4.1.3

What does the following program print?

class Box { int value; }
public class Problem2 {
  public static void main(String[] args) {
    Box k1 = new Box();
    k1.value = 5;
    Box k2 = k1;
    k2.value = 9;
    Box k3 = new Box();
    k3.value = 9;
    System.out.println(k1.value);
    System.out.println(k1 == k2);
    System.out.println(k2 == k3);
  }
}
9
true
false

Box k2 = k1; creates no new object; k2 and k1 point to the same object. k2.value = 9 writes to this shared object, so k1.value is also 9. k1 == k2 gives true. k3 is a separate object created with new; even though its value is also 9, k2 == k3 gives false.

Example 4.1.4

What do the following two programs print?

record Money(int lira) { }
public class Problem5 {
  public static void main(String[] args) {
    Money p1 = new Money(10);
    Money p2 = new Money(10);
    Integer i1 = 1000, i2 = 1000;
    System.out.println(p1.equals(p2));
    System.out.println(p1 == p2);
    System.out.println(i1.equals(i2));
    System.out.println(p1);
  }
}
true
false
true
Money[lira=10]
class Point {
  int x, y;
  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}
public class Problem6 {
  public static void main(String[] args) {
    Point a = new Point(1, 2);
    Point b = new Point(1, 2);
    System.out.println(a.equals(b));
    System.out.println(a.x == b.x);
  }
}
false
true

In the first program Money is a record. The record's equals compares content: true. == compares two separate objects: false. i1 and i2 are two separate Integer objects with the value 1000; because they are outside the cache range, == would give false, but equals is always safe: true. The last line is the toString the record generates. In the second program Point is an ordinary class and has not written equals. The Object version compares references: false. a.x == b.x, on the other hand, compares two int values: true.

The following five exercises bring together the topics of these notes. A solution program and its output follow.

  1. A Book class: private title, author, pageCount; a three-parameter constructor, get methods and toString().
  2. Add to Book a static counter bookCount and a setPageCount that accepts only positive values.
  3. A Circle class: radius, area(), perimeter(); printing with two decimal places for new Circle(3).
  4. Printing the values of the Season enum with their ordinal numbers.
  5. A StudentRecord(String name, int id) record and printing one of its objects.
class Book {
  private String title, author;
  private int pageCount;
  private static int bookCount = 0;
  Book(String title, String author, int pageCount) {
    this.title = title;
    this.author = author;
    setPageCount(pageCount);
    bookCount++;
  }
  String getTitle() { return title; }
  String getAuthor() { return author; }
  int getPageCount() { return pageCount; }
  void setPageCount(int pageCount) {
    if (pageCount > 0) this.pageCount = pageCount;
  }
  static int getBookCount() { return bookCount; }
  @Override
  public String toString() { return title + " (" + author + ", " + pageCount + " s.)"; }
}
class Circle {
  private double radius;
  Circle(double radius) { this.radius = radius; }
  double area() { return Math.PI * radius * radius; }
  double perimeter() { return 2 * Math.PI * radius; }
}
enum Season { SPRING, SUMMER, AUTUMN, WINTER }
record StudentRecord(String name, int id) { }
public class Exercises {
  public static void main(String[] args) {
    Book k = new Book("Nutuk", "Atatürk", 600);
    System.out.println(k);
    Book k2 = new Book("Essay", "Author", -5);
    System.out.println(k2.getPageCount() + " " + Book.getBookCount());
    Circle d = new Circle(3);
    System.out.printf("%.2f %.2f%n", d.area(), d.perimeter());
    for (Season m : Season.values()) System.out.print(m.ordinal() + ":" + m + " ");
    System.out.println();
    System.out.println(new StudentRecord("Ali", 7));
  }
}
Nutuk (Atatürk, 600 p.)
0 2
28,27 18,85
0:SPRING 1:SUMMER 2:AUTUMN 3:WINTER 
StudentRecord[name=Ali, id=7]

The constructor of Book does not write the page count directly to the field; it calls setPageCount. In this way the check stays in one place and the constructor uses it too. For the second book with −5 pages the setter rejects the value; the field stays at its default value 0. The counter, however, counts both books: 0 2. For Circle, printf("%.2f %.2f%n", ...) is used; on a Turkish locale the decimal separator is a comma: π × 9 ≈ 28,27 and 2 × π × 3 ≈ 18,85. The values of Season are traversed with values(), and ordinal() starts at 0.

4.1.14Common mistakes

The compiler catches most of the errors related to objects and classes, and its message points directly to the location of the error. Some, however, lead to programs that compile but run wrongly; these are more dangerous.

Common mistake

Calling an instance method from main without an object. Message: non-static method greet() cannot be referenced from a static context. The call is made through an object (new Greeter().greet()); if the method really uses no object's data, it is made static.

Common mistake

Writing void on a constructor. public void CtorError(String m) is not a constructor but an ordinary method. new CtorError("hello") is rejected with this message: constructor CtorError in class CtorError cannot be applied to given types. A constructor has no return type.

Common mistake

Creating an object without arguments when there is only a parameterized constructor. When a constructor is written, the default constructor is not added; new Product() gives the message cannot be applied to given types. If needed, a no-argument constructor is written as well.

Common mistake

Forgetting new. The line Product u = Product("Pen"); reads like a method call, and the compiler looks for such a method:

ForgotNew.java:7: error: cannot find symbol
    Product u = Product("Pen");
             ^
  symbol:   method Product(String)
  location: class ForgotNew
1 error
Common mistake

Accessing a private field from outside. Message: balance has private access in BankAccount. The field is reached through the class's get and set methods.

Common mistake

Using this in a static method. Message: non-static variable this cannot be referenced from a static context. A static method has no object.

Common mistake

Forgetting this in a constructor (shadowing). name = name; compiles but assigns the parameter to itself; the field stays null. The correct form is this.name = name;. If the field is made final, the compiler catches the error.

Common mistake

Writing this(...) after the first line. Message: call to this must be first statement in constructor. Delegating to the other constructor must be the first statement of the constructor.

Common mistake

Comparing objects with ==. k1 == k2 gives false for two separate objects with the same content. Content is compared with equals(), including for String and the wrapper classes. If equals has not been written in one's own class, the Object version also behaves like ==.

Common mistake

Using a null reference. A method cannot be called on an object that has not been created or after null has been assigned; a NullPointerException is thrown. Reference fields that have not been given a value are also null. A null check is made before use.

Common mistake

Trying to change a record field. Message: x has private access in Point. A record is immutable; a new object is created for a new value.

Common mistake

Creating a member inner class directly in static main. Message: non-static variable this cannot be referenced from a static context. The correct form is outer.new MemberInner(); or the inner class is made static.

4.1.15Summary

  • Object-oriented programming builds a program from interacting objects. Every object has state (fields) and behavior (methods). The three basic features are encapsulation, inheritance and polymorphism; abstraction is often added.
  • A class is the blueprint of an object; an object is an instance produced with new. Objects of the same class carry the same field names, but each has its own values. The method code is single in the class.
  • Access modifiers: public, protected, package access, private. Fields are private and the methods offered to the outside are public; the value is read with a getter and written with a setter that performs checks (data hiding).
  • A constructor has the same name as the class and no return type. new allocates space on the heap, gives the fields default values, calls the constructor and returns the reference. If no constructor is written, the compiler adds a no-argument default constructor; once a constructor is written, it does not.
  • Default values of fields: numbers 0, boolean false, char '\u0000', references null. Local variables get no default value.
  • An instance field is separate in every object; a static field is single and shared in the class. A static method has no this; it reaches instance members only through an object. A final field is given a value once; class constants are static final and written in capitals.
  • Initialization order: static fields and static { } blocks once, when the class is first used; then at every new the default values, the field initial values and { } blocks (in the order written), and finally the body of the constructor.
  • A variable holds not the object but the reference. Assignment copies the reference and creates an alias. Passing an object to a method also gives a copy of the reference. Access through a null reference throws a NullPointerException; the garbage collector removes an object that has no reference left.
  • this is the object the method was called on; a shadowed field is reached with this.name, and the object can be passed to other methods with this. this(...) calls another constructor of the same class, must be on the first line and builds a single object.
  • == tests reference equality and equals tests content equality. When equals is overridden, hashCode is written too. String and the wrappers are compared with equals.
  • Wrapper classes carry primitive values as objects. Autoboxing is a call to valueOf and unboxing a call to xxxValue(). Integers between −128 and 127 come from the cache; unboxing a null wrapper throws a NullPointerException.
  • A record is an immutable data class; the constructor, accessors, equals, hashCode and toString are generated automatically. An enum is a fixed set of values; it is used with values(), valueOf(), ordinal() and ==.
  • Inner classes: static (no outer object needed), member (tied to an outer object, outer.new), local (inside a method) and anonymous (nameless, a single object).
  • An object belongs to a single class, but it can have many types. Kinds of classes: enum, singleton, abstract, sealed, final, record, utility and application class. In class design the interface, representation and implementation are separated; the representation is kept hidden.

4.1.16Key terms

  • object-oriented programming
  • procedural programming
  • class
  • object
  • instance
  • member
  • field
  • method
  • dot operator
  • access modifier
  • getter
  • setter
  • data hiding
  • encapsulation
  • constructor
  • default constructor
  • constructor chaining
  • reference
  • heap
  • stack
  • null reference
  • garbage collector
  • static member
  • initializer block
  • this keyword
  • shadowing
  • wrapper class
  • autoboxing / unboxing
  • record
  • enum
  • immutable
  • inner class
  • anonymous class
  • sealed class / interface
  • abstraction

4.1.17Test Yourself

  1. Three objects (p, q, r) are created in a row from the class class Counter2 { static int s = 0; int n; Counter2() { s += 2; n = s; } }. What are p.n, q.n, r.n and Counter2.s?

    Answer

    s is static and all three constructors increment the same box: 2, 4, 6. Each constructor copies the current value into the object's own n field. A later change of s does not affect the n of earlier objects. Result: 2 4 6 6.

  2. The class Cell has a single int v field and a constructor that assigns v. The method static void change(Cell h, Cell g) { h.v = 10; g = h; g.v = 20; } is called as change(a, b) with a = new Cell(1) and b = new Cell(2). What are a.v and b.v afterwards?

    Answer

    h points to the object of a; h.v = 10 makes it 10. g = h only points the local copy g at the object of a; b does not change. g.v = 20 now writes to the object of a. Result: a.v = 20, b.v = 2.

  3. Two objects are created from the class class C { static int t = 0; int a = ++t; { t *= 10; } C() { t++; } }. What are the a of the first object, the a of the second object and finally C.t?

    Answer

    For every object the order is: field initial value, then instance initializer, then constructor body. First object: a = ++t → t = 1, a = 1; t *= 10 → 10; t++ → 11. Second object: a = 12, t = 120, t = 121. Result: 1 12 121.

  4. The class Chain has the fields int x; String s = ""; and these constructors: Chain() { this(1); s += "a"; }, Chain(int x) { this(x, x + 1); s += "b"; }, Chain(int x, int y) { this.x = x * y; s += "c"; }. After new Chain(), what are x and s?

    Answer

    The chain descends to the innermost constructor: Chain(1, 2). The initial value s = "" is given once, immediately before the body of this constructor. The innermost body runs first: x = 2, s = "c". As the chain unwinds, each constructor runs its remaining line: "cb", then "cba". Result: 2 cba.

  5. After the declarations Integer i1 = 127, i2 = 127, i3 = 1000, i4 = 1000; Long l = 127L;, what do i1 == i2, i3 == i4, i3.equals(i4), l.equals(127) and l == 127 give?

    Answer

    true false true false true. 127 comes from the cache; for 1000 two separate objects are created. equals compares values. In l.equals(127) the 127 is boxed into an Integer; the equals of Long counts only another Long as equal, so the result is false. In l == 127, l is unboxed and the two numbers are compared: true.

  6. With the Rational class in this chapter, how is new Rational(10, -4) printed? What does new Rational(2, 6).add(new Rational(1, 6)) give?

    Answer

    gcd(10, 4) = 2; the numerator and denominator are divided by 2 and the sign stays in the denominator: 5/-2. In the second expression 2/6 is first stored as 1/3. 1/3 + 1/6 = (1 × 6 + 1 × 3) / 18 = 9/18, and the constructor simplifies it: 1/2.

  7. To get rid of the non-static method ... cannot be referenced from a static context error in main, a student makes all the fields and methods in the class static. The program compiles. What is the problem with this solution?

    Answer

    When the fields are static, a single copy of each field is left in the class. Even if two objects are created, they share the same fields; changing the name of one changes the name of the other. The program effectively becomes procedural. The right solution is to call the object-dependent methods through an object and to make static only those that are truly independent of any object.

  8. What happens with new Rational(0, 0) in the Rational class? Which method must be changed, and how, to remove this error and the sign problem? Does the code that uses the class have to change?

    Answer

    gcd(0, 0) returns 0 and the line num / g throws ArithmeticException: / by zero. Only the constructor changes: at the start, if den == 0, an IllegalArgumentException with a meaningful message is thrown; after simplification, if den is negative, the signs of numerator and denominator are flipped. Because the fields are private and the representation is hidden, the code that uses the class does not change at all.

4.1.18Further reading

  • Oracle, The Java Tutorials, the "Classes and Objects" lesson: covers defining classes, constructors, this, access control, class members and nested classes with short examples; it is free and online.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), Chapters 10 and 11: explains objects, references and writing one's own class step by step with stack diagrams.
  • J. Bloch, Effective Java (3rd ed., Addison-Wesley, 2018): an experienced programmer's advice on writing equals, hashCode and toString correctly, immutable classes and static factory methods.
  • J. Gosling et al., The Java Language Specification, Java SE 21, Chapter 8: defines the precise rules for fields, initializers, constructors, enums and records; it is the source to consult for questions about initialization order.

4.1.19References

  • Oracle, The Java Tutorials: "Classes and Objects", "Nested Classes", "Enum Types", "Record Classes", "Autoboxing and Unboxing".
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (Chapter 8 Classes: 8.3 Fields, 8.6–8.7 Initializers, 8.8 Constructors, 8.9 Enum Classes, 8.10 Record Classes).
  • P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapters 3 and 8: Classes and Objects).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022 (Chapter 4: Objects and Classes).
  • A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapters 10–11).
  • J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018 (the items on equals, hashCode, toString).