Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertion querry

 
Yati Tan
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a question :

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 to this is band e.

Iam unable to understand b, can anybody help me !!


 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);}
}}

when we pass 5 4 3 2 1 0 we get output 210210 now
When we pass -1 see to m1 at that time
j = -1 % 3 means j = -1
not we reach default where
assert -1 == 2; // assert false;

so assertion error is thrown
and so System.out.println(j) wont be executed.

hope this helps
 
Yati Tan
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tx alot Santana !!

Yati
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic