Basic Comparisons
In this lesson, we will compare two primitives that have the same type, and then discuss how to compare two objects.
We'll cover the following...
Comparing primitives
When comparing primitives, as in the previous examples, we use operators such as ==
or <
. These operators are examples of relational operators. The figure given below lists these operators and their meanings. Notice the two-character operators <=
and >=
. These exist because characters such as ≤
and ≥
are not on standard keyboards.
Checkpoint question
Imagine that your job is to sell tickets in a movie theater. As you sell each ticket, a Java program counts how many you have sold so that you do not exceed the capacity of the theater. The program contains the integer constant THEATER_CAPACITY
and the integer variable ticketCounter
. This variable is initially 0
and will be incremented by 1
for each ticket you sell.
Write statements that compare the values of ticketCounter
and THEATER_CAPACITY
and display a message when the theater’s capacity has been reached or exceeded.
To simplify testing your answer, change the value of ticketCounter
from zero each time you run the program.
public class Question{static final int THEATER_CAPACITY = 250;public static void main( String args[] ){int ticketCounter = 0;// Write your answer here:} // End main} // End Question
Checkpoint question
Suppose you earn d dollars per hour, and you work h hours a week. Your base pay would be d × h dollars. However, if you work more than 35
hours, you would earn an extra d / 2
dollars for each hour over 35
. Write Java statements to compute your base pay and then adjust it if you work overtime.
public class Question{public static void main( String args[] ){ // Test your answer using 30 hours; then test it using 40 hours.double hours = 30; // Hours worked// Write your answer here:} // End main} // End Question
Comparing objects
The chapter Using Classes and Objects showed that all objects whose type is String
, LocalTime
, or BigDecimal
have the methods equals
and compareTo
. We use these methods, not the operators just listed in the above table, to ...