Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertion

 
Shannon Sims
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I recently took a mock exam with a question that was confusing. The following question was asked:
class A {
void m1(int i) {
int j = i % 3;
switch (j) {
case 0: System.out.print("0"); break;
case 1: System.out.print("1"); break;
default:
assert j == 2;
System.out.print(j);
}}
public static void main (String[] args) {
A a = new A();
for (int i=5; i >= -1; i--) {a.m1(i);}
}}
Which statements are true?
a. With assertions enabled it prints 210210-1 followed by an
AssertionError message.
b. With assertions enabled it prints 210210 followed by an AssertionError
message.
c. With assertions enabled it prints only 210210.
d. With assertions enabled it prints nothing.
e. With assertions disabled it prints 210210-1
f. With assertions disabled it prints only 210210
g. Assertions should not be used within the default case of a switch
statement.
The answer is: b and e. My question is how would any output be displayed if he didn't use this format: assert j == 2 : j; In addition, if assertion is "disabled", why would any output be disabled at all???
Thanks for your help.
 
Angel Dobbs-Sciortino
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An assertion throws an AssertionError if it evaluates to be false. assert j == 2 : j would throw an AssertionError with j being the error code. When assertion is enabled, it will print out 210210 before the error is thrown, because at that point the method is passed -1. If assertions are disabled, no error is thrown, and it prints 210210-1 because -1 is what j equaled at the end of the for loop.
Angel
 
Shannon Sims
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the clarification! I realized I had confused myself with the System.out.print(j) which would print the values if assertion was disabled.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic