Java Reference
In-Depth Information
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.6
✓
✓
Identify and fix the errors in the following code:
Check
Point
1
public class
Test {
2
public static void main
(String[] args) {
3
int
i = j = k =
2
;
4 System.out.println(i +
""
+ j +
""
+ k);
5 }
6 }
A named constant is an identifier that represents a permanent value.
Key
Point
constant
The value of a variable may change during the execution of a program, but a
named con-
stant,
or simply
constant
, represents permanent data that never changes. In our
ComputeArea
program,
p
is a constant. If you use it frequently, you don't want to keep typing
3.14159
;
instead, you can declare a constant for
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
p
as a constant and
rewrite Listing 2.1 as in Listing 2.4.
final keyword
L
ISTING
2.4
ComputeAreaWithConstant.java
1
import
java.util.Scanner;
// Scanner is in the java.util package
2
3
public class
ComputeAreaWithConstant {
4
public static void
main(String[] args) {
5
final double
PI =
3.14159
;
// Declare a constant
6
7
// Create a Scanner object
8 Scanner input =
new
Scanner(System.in);
9
10
// Prompt the user to enter a radius
11 System.out.print(
"Enter a number for radius: "
);
12
double
radius = input.nextDouble();
13
14
// Compute area
15
double
area = radius * radius * PI;
16
17
// Display result
18 System.out.println(
"The area for the circle of radius "
+
19 radius +
" is "
+ area);
20 }
21 }
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