Forums Register Login

Assertion problem

+Pie Number of slices to send: Send
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???
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
Hug your destiny! And hug this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 757 times.
Similar Threads
Assertion question
Strange Assertion Behaviour
Assertions
Inserting single column values of database table into multiple columns of jtable and do comparison
Assertion Question from Dan's exam
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:40:31.