Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an exam coming up and I'm looking at past papers to get some ideas of what to expect. I'm a bit stuck on the following one and would really appreciate if someone could give some example answers.

Write preconditions and postconditions in OCL for each of the following operations (included in the Stack class in the java.util package):

  • (1) Boolean empty() - Tests if this stack is empty
  • (2) E peek() - Looks at the object at the top of this stack without removing from the stack
  • (3) E pop() - Removes the object at the top of this stack and returns that object as the value of this operation
  • (4) E push(E item) - pushes an item onto the top of this stack

Here E denotes the type of elements in the stack.

My attempts are as follows:

Boolean empty()
pre: none
post: self -> IsEmpty() = true
//should this be result -> IsEmpty() = true because it returns a boolean value?

E peek()
pre: self -> NotEmpty() = true
post: result = ??? 
// I lose hope at this stage. 

I also don't know if I should be referencing the elements in the stack. For example: self.elements -> IsEmpty() = true

If anyone could help me out I'd really appreciate it.


A friend has the following ideas:

context Stack empty()
pre: = 0

context Stack peek()

context Stack pop()
pre: !
post: (not sure about this one)
post: = @pre:data - 1

context Stack push(E Item)
post: = + 1
share|improve this question
If you don't get any help here, you could try the UMLforum group on Google Groups. – Stephen C May 12 '13 at 4:06
Or maybe on StackOverflow :-) – Stephen C May 12 '13 at 4:15
You can find illustrative OCL samples here: – Axel Kemper May 12 '13 at 7:30
A lecture on OCL 2.0: – Axel Kemper May 12 '13 at 13:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.