File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertion problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertion problem" Watch "Assertion problem" New topic

Assertion problem

sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
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 {
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

Joined: Jan 16, 2008
Posts: 110
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!

Nikos' Java blog
sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
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

Joined: Jul 22, 2007
Posts: 125
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.

Anand Shrivastava
I agree. Here's the link:
subject: Assertion problem
It's not a secret anymore!