Java Reference
In-Depth Information
Tip
Often new programmers write the code that assigns a test condition to a boolean
variable like the code in (a):
assign boolean variable
if (number % 2 == 0 )
even = true ;
else
even = false ;
boolean even
= number % 2 == 0 ;
Equivalent
This is shorter
(a)
(b)
The code can be simplified by assigning the test value directly to the variable, as shown
in (b).
Check
Point
3.11
Which of the following statements are equivalent? Which ones are correctly indented?
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 ;
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 ;
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 ;
3.13
Are the following statements correct? Which one is better?
if (age < 16 )
System.out.println
( "Cannot get a driver's license" );
if (age >= 16 )
System.out.println
( "Can get a driver's license" );
if (age < 16 )
System.out.println
( "Cannot get a driver's license" );
else
System.out.println
( "Can get a driver's license" );
(a)
(b)
3.14
What is the output of the following code if number is 14 , 15 , and 30 ?
if (number % 2 == 0 )
System.out.println
(number + " is even" );
if (number % 5 == 0 )
System.out.println
(number + " is multiple of 5" );
if (number % 2 == 0 )
System.out.println
(number + " is even" );
else if (number % 5 == 0 )
System.out.println
(number + " is multiple of 5" );
(a)
(b)
 
Search WWH ::




Custom Search