Page 488 - Introduction to Programming with Java: A Problem Solving Approach
P. 488

                454 Chapter 11 Type Details and Alternate Coding Mechanisms
if ((attempted > 0) && ((double) made / attempted) >= .5)
With division, you should always think about, and try to avoid, division by zero. If attempted equals zero, will the JVM attempt to divide by zero? Nope! Short-circuit evaluation saves the day.
Short-circuit evaluation means that the JVM stops evaluating an expression whenever the expression’s outcome becomes certain. More specifically, if the left side of an && expression evaluates to false, then the expression’s outcome is certain (false && anything evaluates to false) and the right side is skipped. Likewise, if the left side of an || expression evaluates to true, then the expression’s outcome is certain (true || anything evaluates to true) and the right side is skipped. So in Figure 11.9’s if statement con- dition, if attempted equals zero, the left side of the && operator evaluates to false and the right side is skipped, thus avoiding division by zero.
So what’s the benefit of short-circuit evaluation?
1. Error avoidance: It can help to prevent problems by enabling you to avoid an illegal op- eration on the right side of an expression.
2. Performance:Sincetheresultisalreadyknown,thecomputerdoesn’thavetowastetime calculating the rest of the expression.
As an aside, note the %% in Figure 11.9’s printf statement. It’s a conversion specifier for the printf method. Unlike the other conversion specifiers, it is a standalone entity; it doesn’t have an argument that plugs into it. It simply prints the percent character. Note the printed % at the end of Figure 11.9’s second sample session.
It’s sometimes possible to put all of a loop’s functionality inside of its header. For example:
for (int i=0; i<1000000000; i++)
{}
The Java compiler requires that you include a statement for the for loop’s body, even if the statement doesn’t do anything. The above empty braces ({ }) form a compound statement2 and satisfy that require- ment. In this section, you learn about an alternative way to satisfy that requirement. You learn about the empty statement.
Using the Empty Statement
The empty statement consists of a semicolon by itself. Use the empty statement in places where the compiler requires a statement, but there is no need to do anything. For example, the below for loop can be used as a “quick and dirty” way to add a delay to your program:
monster.display();
for (int i=0; i<1000000000; i++)
;
monster.erase();
       Utilize built-in behavior.
  Apago PDF Enhancer
11.10 Empty Statement
This section supplements the loop material you studied in Chapter 4.
     2 The compound statement, defined in Chapter 4, is a group of zero or more statements surrounded by braces.
Coding convention:
Put the empty statement on a line by itself and indent it.










































































   486   487   488   489   490