PREV NEXT
This topic is part of SCJP 1.4 exam but not SCJP 1.2 exam.
1.What happens when the following code is compiled and run. Select the one correct answer.
for(int i = 1; i < 3; i++) for(int j = 3; j > i; j–) assert i!=j {System.out.println(i); } |
A.The class compiles and runs, but does not print anything.
B.The number 1 gets printed with AssertionError
C.The number 2 gets printed with AssertionError
D.The number 3 gets printed with AssertionError
E.The program generates a compilation error.
2.What happens when the following code is compiled and run. Select the one correct answer.
for(int i = 1; i < 3; i++) for(int j = 3; j >= 1; j–) assert i!=j : i; |
A.The class compiles and runs, but does not print anything.
B.The number 1 gets printed with AssertionError
C.The number 2 gets printed with AssertionError
C.The number 3 gets printed with AssertionError
E.The program generates a compilation error.
3.What happens when the following code is compiled and run. Select the one correct answer.
for(int i = 1; i < 4; i++) for(int j = 1; j < 4; j++) if(i < j) assert i!=j : i; |
A.The class compiles and runs, but does not print anything.
B.The number 1 gets printed with AssertionError
C.The number 2 gets printed with AssertionError
D.The number 3 gets printed with AssertionError
E.The program generates a compilation error.
4.Which of the following statement is true about the assert statement. Select the one correct answer.
A.If a Java class contains assert statements, then it must be compiled with -1.4 option.
B.When a program having assertions is run, -assertion option must be specified, otherwise the assertions get ignored.
C.A possible syntax of assert statement is
assert logical_expression |
If logical_expression evaluates to true, the program generates an AssertionError.
D.The program terminates on its first AssertionError.
Answers to Java Assertions Question
- e. The condition in assert statement must be followed by a semi-colon.
- b. When i and j are both 1, assert condition is false, and AssertionError gets generated.
- a. When the if condition returns true, the assert statement also returns true. Hence AssertionError does not get generated.
- d. The option A is incorrect, as the Java compiler option is -source 1.4 . The option B is incorrect, as the runtime option is -ea or -enableassertions. If the logical expression evaluates to false, then the program generates an AssertionError, hence C is incorrect.
For more questions on Assertions, you may want to visit Khalid Mughal’s sample chapter on Assertions.
Post Your Thoughts