Java Reference
In-Depth Information
exceptions. It is also possible to add another block called a “ finally block” that
contains code to execute in all cases, whether an error occurs or not. This technique
can be useful to consolidate cleanup code that should be run after the try block fin-
ishes. These syntax variations are outside the scope of this textbook.
The assert Statement
In Chapters 4 and 5 we discussed preconditions, postconditions, and logical asser-
tions. Sometimes programmers want to test logical assertions (Boolean expressions)
as sanity checks in their own code. As the code runs, it will check each assertion that
it reaches. If the assertion's expression is not true, the program will halt with an error.
Java supports the testing of assertions with its assert statement, which uses the
following syntax:
assert <boolean test> ;
For example, to test that a variable x is nonnegative, you could write the following
line of code:
assert x >= 0;
In general, we expect these assertions to succeed. When an assertion fails, it sig-
nals a problem. It means that the program has a logic error that is preventing the
assumptions from holding true.
Testing of assertions can be expensive, so Java lets you control whether this fea-
ture is enabled or disabled. You can enable assertion checking in your Java editor
while you are developing and testing a program to make sure it works properly. Then
you can disable it when you're fairly confident that the program works and you want
to speed it up. By default, assertion checking is disabled.
Enumerations: enum
Since Chapter 2 we have seen the usefulness of class constants. Sometimes we want
to create a type that has only a small number of predefined constant values. For
example, suppose we are writing a program for a card game. Each card has a suit:
Clubs, Diamonds, Hearts, or Spades. We could represent these values as integers
(0 through 3) or strings, but these are clumsy solutions because the range of integers
and strings is large, so it may be possible to slip in an invalid suit value.
In such situations, it can be useful to create an enumerated type , which is a simple
type that has only a small number of constant values.
public enum <name> {
<name> , <name> , ..., <name>
}
 
 
Search WWH ::




Custom Search