Java Reference
In-Depth Information
Making Decisions
Making choices will be a fundamental element in all your programs. You need to be able to make
decisions like, "If the bank balance is large, buy the car with the go-faster stripes, else renew the
monthly bus ticket". In programming terms this requires the ability to make comparisons between
variables, constants, and the values of expressions, then executing one group of statements or another,
depending on the result of a given comparison. The first step to making decisions in a program is to
look at how we make comparisons.
Making Comparisons
Java provides you with six relational operators for comparing two data values. Either of the data values
you are comparing can be variables, constants or expressions drawn from Java's primitive data types -
byte , short , int , long , char , float or double .
Relational
Operators
Description
>
Produces the value true if the left operand is greater than the right operand,
and false otherwise.
>=
Produces the value true if the left operand is greater than or equal to the
right operand, and false otherwise.
==
Produces the value true if the left operand is equal to the right operand, and
false otherwise.
!=
Produces the value true if the left operand is not equal to the right operand,
and false otherwise.
<=
Produces the value true if the left operand is less than or equal to the right
operand, and false otherwise.
<
Produces the value true if the left operand is less than the right operand, and
false otherwise.
As you see, each operator produces either the value true , or the value false , and so is eminently
suited to the business of making decisions.
If you wish to store the result of a comparison, you use a boolean variable. We saw how to declare these
in the previous chapter. For example you can define a boolean variable state and you can set its value
in an assignment as follows:
boolean state = false;
state = x - y < a + b;
The value of the variable state will be set to true in the assignment if x-y is less than a+b , and to
false otherwise.
Search WWH ::




Custom Search