Win a copy of Modern frontends with htmx this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

assertions

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got it. Thanks.
 
reply
    Bookmark Topic Watch Topic
  • New Topic