Reputation: 457
This question is from SCJP dumps. May be it seems stupid , but i have a bit confusion about options. please help me out
public class Donkey2 {
public static void main(String[] args) { boolean assertsOn = true; assert (assertsOn) : assertsOn = true; if(assertsOn) { System.out.println("assert is on"); } }
}
If class Donkey is invoked twice, the first time without assertions enabled, and the second time with assertions enabled, what are the results?
A. no output
B. no output ; assert is on
C. assert is on
D. no output ; An AssertionError is thrown.
E. assert is on ; An AssertionError is thrown
Answer ) if i invoke it twice i will get assert is on assert is on
Is that true?
Book says answer is C) but i guess it should be twice i.e. assert is on ; assert is on in both cases
Upvotes: 2
Views: 2879
Reputation: 279920
To the Java Language Specification we go
If the value is true, no further action is taken and the assert statement completes normally.
If the value is false, the execution behavior depends on whether Expression2 is present:
If Expression2 is present, it is evaluated.
If the evaluation completes abruptly for some reason, the assert statement completes abruptly for the same reason.
If the evaluation completes normally, an AssertionError instance whose "detail message" is the resulting value of Expression2 is created.
If the instance creation completes abruptly for some reason, the assert statement completes abruptly for the same reason.
If the instance creation completes normally, the assert statement completes abruptly by throwing the newly created AssertionError object.
If assertion is disabled, the assert
is skipped, assertsOn
is true
, so the if
block is executed.
If assertion is enabled, the assert
is executed, assertsOn
is true
, so assertion passes. assertsOn
is true
, so the if
block is executed.
The answer is what you say it is.
assert is on ; assert is on
There might be something you aren't telling/showing us or the answers presented there are missing the correct one.
Upvotes: 1