Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Assertion  RSS feed

 
Ranch Hand
Posts: 200
  • 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.
 
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: 200
  • 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
Boost this thread!