Summer 2010 15-110 (Reid-Miller) 25
Testing for Equality with doubles
• Which statement will Java print?
double x = Math.sqrt(2.0);!
double y = x * x;!
if (y == 2.0) {!
!System.out.println("sqrt(2) * sqrt(2) is 2");!
} !
else {!
!System.out.println("sqrt(2) * sqrt(2) “!
! ! ! !+ “is not 2. It is " + y);!
}!
Never test for exact equality
with floating point numbers!
Summer 2010 15-110 (Reid-Miller) 26
Testing for Equality with doubles
• Because of round-off errors, you should test if the
numbers are close.
double tolerance = 1.0e-10;!
double x = Math.sqrt(2.0);!
double y = x * x; !
if (Math.abs(y - 2.0) < tolerance) {!
!System.out.println("sqrt(2) * sqrt(2) is 2");!
} !
else {!
!System.out.println("sqrt(2) * sqrt(2) “!
! ! ! !+ “is not 2. It is " + y);!
}!
Summer 2010 15-110 (Reid-Miller) 27
Short-Circuit Evaluation
• Short circuit evaluation (or lazy evaluation) : If the first
conditional in an && expression is false, Java does
not execute the second conditional.
Example:
! if (liters > 0 && total/liters > threshold) {!
! System.out.println(“WARNING: Exceeds threshold”);!
}
What if the expression was an || expression?
Summer 2010 15-110 (Reid-Miller) 28
The switch statement
• If an if/else statement with multiple alternatives
compares an int or char variable or expression
against several constants you can use a switch
statement.
Example:
!switch (suitAsChar) {!
!case ‘C’: suitAsName = “Clubs”; break;!
!case ‘D’: suitAsName = “Diamonds”; break;!
!case ‘H’: suitAsName = “Hearts”; break;!
!case ‘S’: suitAsName = “Spades”; break;!
!default: suitAsName = “Unknown”;!
}!