| 1. | public class Test2 switch (z) if ( z < 10 ) which line is an example of an inappropriate use of assertions? |
|||||||
Answer: Option D Explanation: Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false. Option A is fine; a second expression in an assert statement is not required. Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement. Option C is fine because it is proper to call an assert statement conditionally. |
| 2. | What will be the output of the program (when you run with the -ea option) ? public class Test |
|||||||
Answer: Option C Explanation: An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option) Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6. |
| 3. | What will be the output of the program? public class Test |
|||||||
Answer: Option D Explanation: The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile. |
| 4. | public class Test What causes compilation to fail? |
|||||||
Answer: Option D Explanation: Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also be unreachable. The answer must be something other than assert. Examine the following: A while statement can complete normally if and only if at least one of the following is true: - The while statement is reachable and the condition expression is not a constant expression with value true. -There is a reachable break statement that exits the while statement. The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code: |
| 5. | What will be the output of the program? public class Test |
|||||||
Answer: Option B Explanation: Compilation Fails. You can't use the Assert statement in a similar way to the ternary operator. Don't confuse. |
