Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Initialization

In the last section, you introduced the numberOfStudents field and initialized it to 0. This initialization is technically not required—int fields are initialized to 0 by default. Explicitly initializing a field in this manner, while unnecessary, is useful to help explain the intent of the code.

For now, you have two ways to initialize fields: You can initialize at the field level or you can initialize in a constructor. You could have initialized numberOfStudents in the CourseSession constructor:

class CourseSession {
   private String department;
   private String number;
   private int numberOfStudents;

   CourseSession(String department, String number) {
      this.department = department;
      this.number = number;
      numberOfStudents = 0;
   }
   ...

There is no hard-and-fast rule about where to initialize. I prefer initializing at the field level when possible—having the initialization and declaration in one place makes it easier to follow the code. Also, as you will learn later in this lesson, you can have more than one constructor; initializing at the field level saves you from duplicate initialization code in each constructor.

You will encounter situations where you cannot initialize code at the field level. Initializing in the constructor may be your only alternative.

  • + Share This
  • 🔖 Save To Your Account