File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg 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 "Reg Assertions" Watch "Reg Assertions" New topic
Author

Reg Assertions

Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Hi Everyone,
This is one of the Questions from the Dan's mock Exam.
Please go through the code...

class C {
int a, b, c;
public void setA(int i) {a = i; assert validateC() : c;}
public void setB(int i) {b = i; assert validateC() : c;}
private boolean validateC() {
return c > a + 2 * b;
}
public int m1(int i) {
c = a + b + i;
assert validateC() : c;
return c;
}
public C(int i) {
c = i; assert validateC() : c;
}
public static void main(String[] args) {
C c = new C(251); c.setA(50); c.setB(100);
}}

Which statements are true?

a. If assertions are not enabled at run time it prints an error message.
b. If assertions are not enabled at run time it prints nothing.
c. With assertions enabled it prints an error message.
d. With assertions enabled it prints nothing.
e. The assert statement is being used to check a class invariant--something that must be true about each instance of the class.
f. The assert statements are being used to check a precondition--something that must be true when the method is invoked.

The answers given are b,d,e.

I did not understand what answer e means. I don't know what invarinat means.
Also i am of the opinion that Assert statement should not be used with the parameters of a method.
Can any one explain me about the answers to this Question.

Thanks in Advance.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Consider a class that models a traffic light (a red, orange, green one).
An instance (object) of this class represents a working traffic light only if the state of the lamps is valid. Suppose the lamps are topLamp, middleLamp, bottomLamp. We can represent the state of the object by (topLamp.color, middleLamp.color, bottomLamp.color) [where color = red, yellow, yellowBlink, green, off]

A class invariant is a proposition (true or false) which must always be true for any instance of the class at all times.

For our traffic light:
(red, off, off), (red, yellow, off), (off, off, green), (off, yellow, off), (off, yellowBlink, off) are the valid states.

So a class invariant assertion is


The above assertion should be placed in every method that can change the state of the object, usally at the entry and before the return.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reg Assertions