wood burning stoves*
The moose likes Java in General and the fly likes Assertion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Assertion" Watch "Assertion" New topic
Author

Assertion

Shannon Sims
Ranch Hand

Joined: Jul 03, 2003
Posts: 197
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

Joined: Sep 10, 2003
Posts: 101
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

Joined: Jul 03, 2003
Posts: 197
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.
 
wood burning stoves
 
subject: Assertion
 
Similar Threads
assertions doubt
Assertion querry
assertions
Assertion
Mock Exam - Exception handling