aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertions" Watch "Assertions" New topic
Author

Assertions

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi ,I got it from http://www.danchisholm.net/july21/topic/section2/assertions1.html

class D
{
private boolean b1, b2;
public void setB1(boolean b)
{
b1 = b;
}
public void setB2(boolean b)
{
b2 = b;
}
public void m1 ()
{
if (!b2 & !b1)
{
System.out.print("A");
}
else if (!b2 & b1)
{
System.out.print("B");
}

else if (b2 & !b1)
{
System.out.print("C");
}
else
{
assert false;
}
}
public static void main (String[] args) {
D d = new D();
d.setB1(true); d.setB2(true);
d.m1();
}}

Which statements are true?

a. With assertions enabled it prints an AssertionError message.
b. With assertions enabled it prints nothing.
c. With assertions disabled it prints an AssertionError message.
d. With assertions disabled it prints nothing.
e. An assertion should not be placed at any location that the programmer believes will never be reached under normal operating conditions.
f. The assert statement is being used to check a control-flow invariant to verify that the control flow never reaches a point in the program

Answers: a,d,f.
I couldn't understand this ,can anyone explain the logic and how did assert reach here?

Thanks in advance

Preparing Scjp 1.5
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Its simple Preetha...

You have set b1 and b2 to true by calls to setB1 and setB2.

And in your if else conditions, you finally hit the final else part (because for & to pass, both the operands should evaluate to true).

In the final else part, you say "assert false", which means, "throw assertion error here if the condition is false". Since, you have explicitly mentioned false, it WILL throw an assertion error, but only if assertions are enabled by -ea or -enableassertions while running java command...

If assertions are not enabled, your "assert false" statement does not mean anything..ie. it does not come into picture during runtime.

So, as per the above explanation, options a and d are correct.

Assertions are placed in such control blocks like if-else to ensure that the program flow does not reach some unintended code...in the eg you have given, we are ensuring that both b1 and b2 variables are true. If anyone is false, assertion error is thrown. As per this, option f is correct.

Hope I am clear.

A small suggestion: Please use the "CODE" marker to properly indent your code...You know, its difficult to read the code if it is not indented, that too, in such code where there are many if-else's
[ November 17, 2008: Message edited by: Rekha Srinath ]
 
Don't get me started about those stupid light bulbs.
 
subject: Assertions