Java Reference
In-Depth Information
It is fine to declare i in two
nonnested blocks.
It is wrong to declare i in two
nested blocks.
public static void method1() {
int x = 1 ;
int y = 1 ;
public static void method2() {
int
= 1 ;
int sum = 0 ;
i
for ( int i = 1 ; i < 10 ; i++) {
x += i;
for ( int
i
= 1 ; i < 10 ; i++)
}
sum += i;
}
for ( int i = 1 ; i < 10 ; i++) {
y += i;
}
}
}
F IGURE 5.6
A variable can be declared multiple times in nonnested blocks, but only once in nested blocks.
Caution
Do not declare a variable inside a block and then attempt to use it outside the block.
Here is an example of a common mistake:
for ( int i = 0 ; i < 10 ; i++) {
}
System.out.println(i);
The last statement would cause a syntax error, because variable i is not defined outside
of the for loop.
5.20
What is a local variable?
Check
5.21
What is the scope of a local variable?
Point
5.10 The Math Class
The Math class contains the methods needed to perform basic mathematical functions.
Key
Point
a b
You have already used the pow(a, b) method to compute in Section 2.9.3, Exponent Oper-
ations, and the Math.random() method in Section 3.8, Generating Random Numbers. This
section introduces other useful methods in the Math class. They can be categorized as
trigonometric methods , exponent methods , and service methods. Service methods include the
rounding, min, max, absolute, and random methods. In addition to methods, the Math class pro-
vides two useful double constants, PI and E (the base of natural logarithms). You can use these
constants as Math.PI and Math.E in any program.
5.10.1 Trigonometric Methods
The Math class contains the following trigonometric methods:
/** Return the trigonometric sine of an angle in radians */
public static double sin( double radians)
/** Return the trigonometric cosine of an angle in radians */
public static double cos( double radians)
/** Return the trigonometric tangent of an angle in radians */
public static double tan( double radians)
 
 
 
Search WWH ::




Custom Search