ptg7068951
ifStatements 81
if (account <= 0) {
System.out.println(“You are flat broke”);
}
There’s also a >=operator for greater-than-or-equal-to tests.
Equal and Not Equal Comparisons
Anothercondition to check in a program is equality. Is a variable equal to a
specific value? Is one variable equal to the value of another? These ques-
tions can be answered with the==operator, as in the following statements:
if (answer == rightAnswer) {
studentGrade = studentGrade + 10;
}
if (studentGrade == 100) {
System.out.println(“Show off!”);
}
You also can test inequality, whether something is not equal to something
else, with the!=operator, as follows:
if (answer != rightAnswer) {
score = score - 5;
}
You can use the ==and !=operators with every type of variable except for
strings, because strings are objects.
Organizing a Program with Block Statements
Up to this point, the ifstatements in this hour have been accompanied by
a block contained within the {and }brackets. (I believe the technical term
for these characters is “squiggly bracket marks.”)
Previously, you have seen how block statements are used to mark the
beginning and end of the main()block of a Java program. Each statement
within the main()block is handled when the program is run.
An ifstatement does not require a block statement. It can occupy a single
line, as in this example:
if (account <= 0) System.out.println(“No more money”);
CAUTION
The operator used to conduct
equality tests has two equal
signs:==. It’s easy to confuse
this operator with the =opera-
tor,which is used to give a
value to a variable. Always use
two equal signs in a conditional
statement.