Java Reference
In-Depth Information
Common Pitfall 1: Simplifying Boolean Variable Assignment
Often, new programmers write the code that assigns a test condition to a boolean variable
like the code in (a):
if (number % 2 == 0 )
even = true ;
else
even = false ;
boolean even
= number % 2 == 0 ;
Equivalent
This is shorter
(a)
(b)
This is not an error, but it should be better written as shown in (b).
Common Pitfall 2: Avoiding Duplicate Code in Different Cases
Often, new programmers write the duplicate code in different cases that should be combined
in one place. For example, the highlighted code in the following statement is duplicated.
if (inState) {
tuition = 5000 ;
System.out.println( "The tuition is " + tuition);
}
else {
tuition = 15000 ;
System.out.println( "The tuition is " + tuition);
}
This is not an error, but it should be better written as follows:
if (inState) {
tuition = 5000 ;
}
else {
tuition = 15000 ;
}
System.out.println( "The tuition is " + tuition);
The new code removes the duplication and makes the code easy to maintain, because you only
need to change in one place if the print statement is modified.
3.11
Which of the following statements are equivalent? Which ones are correctly
indented?
Check
Point
if (i > 0 ) if
(j > 0 )
x = 0 ; else
if (k > 0 ) y = 0 ;
else z = 0 ;
if (i > 0 ) {
if (j > 0 )
x = 0 ;
else if (k > 0 )
y = 0 ;
}
else
z = 0 ;
if (i > 0 )
if (j > 0 )
x = 0 ;
else if (k > 0 )
y = 0 ;
else
z = 0 ;
if (i > 0 )
if (j > 0 )
x = 0 ;
else if (k > 0 )
y = 0 ;
else
z = 0 ;
(a)
(b)
(c)
(d)
3.12
Rewrite the following statement using a Boolean expression:
if (count % 10 == 0 )
newLine = true ;
else
newLine = false ;
 
 
Search WWH ::




Custom Search