|
CHAPTER 4: Types, Values, and Variables |
|
 Previous |
 Java Language |
 Index |
 Next |
4.4 Where Types Are Used
Types are used when they appear in declarations or in certain expressions.
The following code fragment contains one or more instances of each kind of usage of a type:
import java.util.Random;
class MiscMath {
int divisor;
MiscMath(int divisor) {
this.divisor = divisor;
}
float ratio(long l) {
try {
l /= divisor;
} catch (Exception e) {
if (e instanceof ArithmeticException)
l = Long.MAX_VALUE;
else
l = 0;
}
return (float)l;
}
double gausser() {
Random r = new Random();
double[] val = new double[2];
val[0] = r.nextGaussian();
val[1] = r.nextGaussian();
return (val[0] + val[1]) / 2;
}
}
In this example, types are used in declarations of the following:
- Imported types (S7.5); here the type Random
, imported from the type java.util.Random
of the package java.util
, is declared
- Fields, which are the class variables and instance variables of classes (S8.3), and constants of interfaces (S9.3); here the field divisor
in the class MiscMath
is declared to be of type int
- Method parameters (S8.4.1); here the parameter l
of the method ratio
is declared to be of type long
- Method results (S8.4); here the result of the method ratio
is declared to be of type float
, and the result of the method gausser
is declared to be of type double
- Constructor parameters (S8.6.1); here the parameter of the constructor for MiscMath
is declared to be of type int
- Local variables (S14.3, S14.12); the local variables r
and val
of the method gausser
are declared to be of types Random
and double[]
(array of double
)
- Exception handler parameters (S14.18); here the exception handler parameter e
of the catch
clause is declared to be of type Exception
and in expressions of the following kinds:
- Class instance creations (S15.8); here a local variable r
of method gausser
is initialized by a class instance creation expression that uses the type Random
- Array creations (S15.9); here the local variable val
of method gausser
is initialized by an array creation expression that creates an array of double
with size 2
- Casts (S15.15); here the return
statement of the method ratio
uses the float
type in a cast
- The instanceof
operator (S15.19.2); here the instanceof
operator tests whether e
is assignment compatible with the type ArithmeticException
 | © 1996 Sun Microsystems, Inc. All rights reserved. |