1.8 - Documentation with Comments
Comments are notes for programmers (you, or anyone else reading the code), and the compiler completely ignores them. There are three types in Java:
/* This is a block comment, it can span multiple lines */ // This is a single-line comment /** This is a Javadoc comment, used to generate API documentation */
A precondition is something that has to be true right before a method runs in order for it to behave correctly. The method itself doesn’t check whether this condition is actually met, that’s on you.
A postcondition is something that’s guaranteed to be true after the method finishes running, describing what gets returned or what the object’s state looks like afterward.
On the exam, preconditions and postconditions usually show up in the comment above a method, like this:
/** * Returns how many boxes can be completely filled with items. * Precondition: items >= 0 and perBox > 0 * Postcondition: returns items / perBox (leftover items are not counted) */ public static int fullBoxes(int items, int perBox) { return items / perBox; }
The method never checks that
perBox is greater than 0. If someone calls fullBoxes(10, 0) anyway, the precondition is broken and the method throws an ArithmeticException. Meeting the precondition is the caller’s job. When it is met, fullBoxes(10, 3) returns 3, just like the postcondition promises.Exam tip: on free-response questions, you can assume preconditions are met, so you don’t need to write extra code to check them.