| Author |
assertions
|
Mila Snov
Greenhorn
Joined: Jan 23, 2004
Posts: 4
|
|
Hi, Example from Kathy Sierra & Bert Bates books. Given the following, 1. public class Test2 { 2. public static int x; 3. public static int foo(int y) { 4. return y * 2; 5. } 6. public static void main(String [] args) { 7. int z = 5; 8. assert z > 0; 9. assert z > 2: foo(z); 10. if ( z < 7 ) 11. assert z > 4; 12. switch (z) { 13. case 4: System.out.println("4 "); 14. case 5: System.out.println("5 "); 15. default: assert z < 10; 16. } 17. if ( z < 10 ) 18. assert z > 4: z++; 19. System.out.println(z); 20. } 21. } which line is an example of an inappropriate use of assertions? A. Line 8 B. Line 9 C. Line 11 D. Line 15 E. Line 18 The correct answer is only E, line 18. I am agree, but I think that B,line 9 also is an example of an inappropriate use of assertions. Am I wrong? Why? Thanks.
|
 |
Dan Chisholm
Ranch Hand
Joined: Jul 02, 2002
Posts: 1865
|
|
Mila, Line 18 is inappropriate because it produces the side effect of changing the value of z. Line 9 invokes a method that does some math, but the results have no impact on the value of z. What problem do you see with line 9?
|
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
|
 |
Vad Fogel
Ranch Hand
Joined: Aug 25, 2003
Posts: 504
|
|
Mila, I think, I know where you're coming from: appropriate assertions usage doesn't modify the values of the variables which would be different with assertions disabled. In this question though, variable z is a primitive and therefore doesn't get modified by the foo method if the assertion condition fails. Still appropriate use of assertions.
|
 |
Mila Snov
Greenhorn
Joined: Jan 23, 2004
Posts: 4
|
|
|
I got it. Thanks.
|
 |
 |
|
|
subject: assertions
|
|
|