Boolean-Valued Methods

In this lesson, we will explore some examples of methods that return either true or false.

The chapter Using Classes and Objects introduced methods that compare two objects and return a value based on the result of the comparison. In particular, we described the method equals for the class String. This method tests whether two strings are the same by returning either true or false. Further, we gave an example of using an if statement to react to the result of String’s equals method. Classes often include methods like equals that return a Boolean value.

A Class of calendar dates

Imagine a class that represents a date consisting of a month, day, and year, where each of these three components is an integer. The class has simple accessor methods, the methods setDate and toString, and the method isLeapYear, which tests whether a particular date occurs within a leap year. Let’s name the class CalendarDate.

Using the class CalendarDate

The program given below demonstrates the use of this class.

Get hands-on with 1200+ tech skills courses.