Java Reference
In-Depth Information
thread to know the type of each object when it receives it. Another situation in which know-
ledge of an object's type at run time is important involves casting. In Java, an invalid cast
causes a run-time error. Many invalid casts can be caught at compile time. However, casts
involving class hierarchies can produce invalid casts that can only be detected at run time.
Because a superclass reference can refer to subclass objects, it is not always possible to
know at compile time whether or not a cast involving a superclass reference is valid. The
instanceof keyword addresses these types of situations. The instanceof operator has this
general form:
objref instanceof type
Here, objref is a reference to an instance of a class, and type is a class or interface type.
If the object referred to by objref is of the specified type or can be cast into the specified
type, then the instanceof operator evaluates to true . Otherwise, its result is false . Thus, in-
stanceof is the means by which your program can obtain run-time type information about
an object.
strictfp
One of the more esoteric keywords is strictfp . When Java 2 was released several years
ago, the floating-point computation model was relaxed slightly. Specifically, the new model
does not require the truncation of certain intermediate values that occur during a computa-
tion. This prevents overflow or underflow in some cases. By modifying a class, method, or
interface with strictfp , you ensure that floating-point calculations (and thus all truncations)
take place precisely as they did in earlier versions of Java. When a class is modified by
strictfp , all of the methods in the class are also strictfp automatically.
assert
The assert keyword is used during program development to create an assertion , which is
a condition that is expected to be true during the execution of the program. For example,
you might have a method that should always return a positive integer value. You might test
this by asserting that the return value is greater than zero using an assert statement. At run
time, if the condition actually is true, no other action takes place. However, if the condi-
tion is false, then an AssertionError is thrown. Assertions are often used during testing to
verify that some expected condition is actually met. They are not usually used for released
code.
The assert keyword has two forms. The first is shown here:
assert condition ;
Search WWH ::




Custom Search