19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.7 Named Constants 43<br />

which is equivalent <strong>to</strong><br />

x = 1;<br />

System.out.println(x);<br />

If a value is assigned <strong>to</strong> multiple variables, you can use this syntax:<br />

i = j = k = 1;<br />

which is equivalent <strong>to</strong><br />

k = 1;<br />

j = k;<br />

i = j;<br />

Note<br />

In an assignment statement, the data type of the variable on the left must be <strong>com</strong>patible<br />

with the data type of the value on the right. For example, int x = 1.0 would be illegal,<br />

because the data type of x is int. You cannot assign a double value (1.0) <strong>to</strong> an int<br />

variable without using type casting. Type casting is introduced in Section 2.15.<br />

2.7 Named Constants<br />

A named constant is an identifier that represents a permanent value.<br />

The value of a variable may change during the execution of a program, but a named constant,<br />

or simply constant, represents permanent data that never changes. In our ComputeArea program,<br />

p is a constant. If you use it frequently, you don’t want <strong>to</strong> keep typing 3.14159;<br />

instead, you can declare a constant for p. Here is the syntax for declaring a constant:<br />

Key<br />

Point<br />

constant<br />

final datatype CONSTANTNAME = value;<br />

A constant must be declared and initialized in the same statement. The word final is a<br />

<strong>Java</strong> keyword for declaring a constant. For example, you can declare p as a constant and<br />

rewrite Listing 2.1 as follows:<br />

final keyword<br />

// ComputeArea.java: Compute the area of a circle<br />

public class ComputeArea {<br />

public static void main(String[] args) {<br />

final double PI = 3.14159; // Declare a constant<br />

// Assign a radius<br />

double radius = 20;<br />

// Compute area<br />

double area = radius * radius * PI;<br />

}<br />

}<br />

// Display results<br />

System.out.println("The area for the circle of radius " +<br />

radius + " is " + area);<br />

There are three benefits of using constants: (1) You don’t have <strong>to</strong> repeatedly type the same<br />

value if it is used multiple times; (2) if you have <strong>to</strong> change the constant value (e.g., from<br />

3.14 <strong>to</strong> 3.14159 for PI), you need <strong>to</strong> change it only in a single location in the source code;<br />

and (3) a descriptive name for a constant makes the program easy <strong>to</strong> read.<br />

benefits of constants

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!