Java Reference
In-Depth Information
which is equivalent to
x = 1 ;
System.out.println(x);
If a value is assigned to multiple variables, you can use this syntax:
i = j = k = 1 ;
which is equivalent to
k = 1 ;
j = k;
i = j;
Note
In an assignment statement, the data type of the variable on the left must be compatible
with the data type of the value on the right. For example, int x = 1.0 would be illegal,
because the data type of x is int . You cannot assign a double value ( 1.0 ) to an int
variable without using type casting. Type casting is introduced in Section 2.15.
2.7 Named Constants
A named constant is an identifier that represents a permanent value.
Key
Point
The value of a variable may change during the execution of a program, but a named constant,
or simply constant, represents permanent data that never changes. In our ComputeArea pro-
gram, is a constant. If you use it frequently, you don't want to keep typing 3.14159 ;
instead, you can declare a constant for
constant
p
p .
Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = value;
A constant must be declared and initialized in the same statement. The word final is a
Java keyword for declaring a constant. For example, you can declare
final keyword
p
as a constant and
rewrite Listing 2.1 as follows:
// ComputeArea.java: Compute the area of a circle
public class ComputeArea {
public static void main(String[] args) {
// Declare a constant
final double PI = 3.14159 ;
// Assign a radius
double radius = 20 ;
// Compute area
double area = radius * radius * ;
PI
// Display results
System.out.println( "The area for the circle of radius " +
radius + " is " + area);
}
}
There are three benefits of using constants: (1) You don't have to repeatedly type the same
value if it is used multiple times; (2) if you have to change the constant value (e.g., from
3.14 to 3.14159 for PI ), you need to change it only in a single location in the source code;
and (3) a descriptive name for a constant makes the program easy to read.
benefits of constants
 
 
Search WWH ::




Custom Search