Using Java Assert Approval, Exam Certification 1Z0-851

I am studying 1Z0-851 Oracla Java SE 1.6 Certification, and I saw this question:

Question from test

I designated the first option as correct and could not! β€œAll assert statements are used appropriately,” and the answer says the first assert(x > 0); is incorrect. The question is why?

+6
source share
4 answers

Correct answer:

Appropriate and improper use of claims

You can post a statement anywhere you don’t expect it to be achieved normally. Assertions can be used to validate parameters passed to a private method. However, statements should not be used to verify parameters passed to public methods, since the public method should check its arguments whether statements are included or not. However, you can check postconditions with statements in both public and non-public methods. In addition, statements must not in any way alter the state of a program.

Src: http://www.freejavaguide.com/java-scjp-part1.pdf

+4
source

Line 12 is redundant.

if you delete it, the statement on line 15 will cover the case where x <= 0

Honestly, this is a strangely worded question, but that's all I see. I'm not sure what is meant by appropriately

+3
source

If you read only the first assert statement, which should be interpreted as a β€œprecondition” because of its position, this means that the function should work properly with any positive int value, which is incorrect. Therefore, this statement is misleading.

+1
source

Starting with go2 , the statement is easy to understand.
The method does nothing, it simply asserts your expectation that x < 0 .

The go method, on the other hand, has a switch .
This is good practice for assert false in the default clause, unless you absolutely expect your program to fall under this clause, that is, under normal circumstances, one of the case should be correct.

The only case on switch expects x exactly 2 .
So, to summarize, you do not expect x be greater than 0 , as the first statement says, you expect x be 2 and nothing more. Therefore, the statement is not used properly.

However, as Jeff noted, case does not have a break , which means that default will always be executed, leading in each script, to assert false .

Conclusion: The go method should always result in an error using assert false correctly, and assert x > 0 is incorrect.

0
source

All Articles