Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertion problem

 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class B {
private static int x1;
public void setX(int x) {x1 = x;}
public int getX() {return x1;}
public static void main(String[] args) {
int i1 = 0, j1 = 0;
do {
System.out.print(j1++);
assert (i1 = j1 + x1) < 6;
} while (i1 < 3);
}}

if setX method is never invoked then what would be the result?

Ans :
With assertions enabled it prints 012.
With assertions disabled it attempts to print an infinite sequence of numbers

Can anyone explain this???
 
Nikos Pougounias
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sinha,

with assertions disabled it's like the following line has comments


If you take a look,



you'll see that the value of i1 controls the while loop. But with the above line commented, the value of i1 never changes; it's always 0!
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
O.k i understand the second answer but i didn't get the 1st answer
why with assertion enabled it prints only 012 why not 012345???

thanks in advance
 
Anand Shrivastava
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your code since the set method is not being executed the value of x1 is default value that is 0.
the assert clause sets i1 to j1++ + x1
In the first iteration of the loop j1=0 and x1 is 0 (remember the post increment operator first uses the value in the expression and then increments it).
therefore i1 becomes 1 which is less than 6 so you assert true.
the while loop tests for i1<3 which is true.
So in the first iteration 0 is printed.

Similarly in the second iteration 1 is printed.
and in the third iteration 2 is printed.

But in the fourth iteration j1 becomes 3 and the while loop terminates as 3 is not less than 3.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic