File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

assertions

 
Mila Snov
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1865
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Vad Fogel
Ranch Hand
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it. Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic