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:
Random, imported from the type java.util.Random of the package java.util, is declared
divisor in the class MiscMath is declared to be of type int
l of the method ratio is declared to be of type long
ratio is declared to be of type float, and the result of the method gausser is declared to be of type double
MiscMath is declared to be of type int
r and val of the method gausser are declared to be of types Random and double[] (array of double)
e of the catch clause is declared to be of type Exception
and in expressions of the following kinds:
r of method gausser is initialized by a class instance creation expression that uses the type Random
val of method gausser is initialized by an array creation expression that creates an array of double with size 2
return statement of the method ratio uses the float type in a cast
instanceof operator (§15.19.2); here the instanceof operator tests whether e is assignment compatible with the type ArithmeticException