• No results found

In Java, all named constants and variables must be declared before using them

In document Java Programming Fundamentals (Page 77-82)

NAMED CONSTANTS AND VARIABLES

Note 2.14 In Java, all named constants and variables must be declared before using them

Using a named constant or a variable without declaring is a syntax error, and as such Java compiler will generate an error message. In the case of primitive data types, you must also initialize the variables before using them.

? nextCharacter

? totalGamesPlayed

6.85 stateTaxRate

12084 nextLine

(2 bytes allocated)

(machine dependent) (4 bytes allocated)

(8 bytes allocated)

Have a close look at me!

Memory location 12084

FIGURE 2.3 Variables.

Apago PDF Enhancer

Self-Check 29. Declare a variable to store product description.

30. Declare a variable to store number of dependents of an employee.

Changing Data Values of Variable

In Java, you can change the value of a variable either through an assignment statement or through increment or decrement operators.

Assignment Statement

Th e assignment statement has three parts: a variable, followed by the equal sign (known as the assignment operator), and then an expression. Th us, the syntax of an assignment statement is

variable = expression;

Example 2.21 Consider the following:

char grade;

double currentScore, totalScore = 0.0;

grade = 'A'; // (1)

currentScore = 30.0 ; totalScore = 95.7;

Th e statement 1 changes the value stored at grade to 'A'. Once the statement 1 is executed, any value previously kept in grade will be lost forever.

In mathematics, if you say y = 5, you are indicating the fact that the value of the vari-able y is 5. For example, you may start with an equation such as 3y − 15 = 0 and then arrive at the conclusion that y = 5. Th e semantics of an assignment statement is quite diff erent. For example, statement 1 specifi es that the character ‘A’ is stored at memory location grade.

In an assignment statement, the expression on the right side is evaluated and then the value computed is stored at the variable on the left side. Th erefore, in an assignment statement, the value of the expression on the righthand side and the variable on the left -hand side should match in data type. Just as in the evaluation of mixed expressions, if the variable on the left -hand side is a data type of wider range than the data type at right-hand side, the right-hand side value will be promoted to match the left -hand side data type. If the variable on the left -hand side is a data type of narrower range than the right-hand data type, then the compiler will issue an error message similar to the following:

possible loss of precision

found : right_hand_side_data_type required: left_hand_side_data_type

Apago PDF Enhancer

A statement that places a value in a variable for the fi rst time is called an initialization statement.

Example 2.22

Assignment Operator Expression on the

Right–Hand Side Left -Hand Variable Type is int Left -Hand Variable Type is double

37 37 is assigned. (data

types match)

37.0 is assigned. (37 is promoted to 37.0 double)

12.5F Error:possible loss of

precision (int is narrower than float)

12.5 is assigned. (12.5 is promoted to double)

56.8 Error:possible loss of

precision (int is narrower than double)

56.8 is assigned. (data types match)

Example 2.23 Consider the following program:

/**

Demonstration of assignment operator

*/

public class Assignments {

public static void main(String[] args) {

If you compile the above program, the following error messages will be generated:

C:\dirName\Assignments.java:11: possible loss of precision found : double

required: int

numberOfStudents = 25.0;

^

Apago PDF Enhancer

C:\dirName\Assignments.java:13: incompatible types found : int

required: java.lang.String heading = 2004;

^

C:\dirName\Assignments.java:14: incompatible types found : java.lang.String

required: boolean

smartStudents = "All students";

^

3 errors

Th e fi rst error message is generated due to line 11 of the fi le C:\dirName\

Assignments.java. Th e error is then summarized as follows:

possible loss of precision found : double

required: int

In other words, the right-hand side of the assignment statement is found to be of data type double, whereas variable on the left -hand side is of the data type int. Note that in this case, the error is “possible loss of precision.” Interpretation of second and third error messages is similar. However, the error is stated as “incompatible types.”

Th us, if you mismatch the data types within numerical data types, system generates a “possible loss of precision” error message. If you assign a String or boolean to a number (or assign a String or number to boolean; or assign a number or bool-ean to a String) the error message produced will be “incompatible types.”

Th e “possible loss of precision” can be avoided through the use of the cast opera-tor. Th e cast operator is explained later in this chapter.

Example 2.24

Th e following Java statements illustrate the assignment statements for diff erent data types:

int hoursWorked;

double hourlyRate, weeklySalary;

char status;

String fullName;

hoursWorked = 5 * 8 - 3;

hourlyRate = 16.75;

weeklySalary = hourlyRate * hoursWorked;

status = 'S';

fullName = "James F. Kirk";

Apago PDF Enhancer

Consider the assignment statement:

hoursWorked = 5 * 8 - 3;

Th e computer fi rst evaluates the expression on the right to an int data type of value 37. Now the variable on the left -hand side is of type int. Th erefore, int value 37 is stored at memory location hoursWorked.

Semantics of other assignment statements are similar.

A Java statement such as k = k + 1;

means take the current value of variable k, add 1 to it, and assign the new value to the memory location k. In the case of an assignment statement, the expression on the right side is evaluated fi rst irrespective of the variable on the left -hand side. Once the right--hand side value is computed, the result is stored in the memory location specifi ed by the variable on the left side. Th us, if value of k was 10 before the execution of the statement, k becomes 11 aft er the execution of the statement.

Semantics of Assignment Operator

Statement i j k p q

int i; 0

int j = 10; 10

int k = j +2; 12

double p; 0.0

double q = 1.234; 1.234

i = j * i + k; 12

k = j % i; 10

p = i / (k + 2) + q; 2.234

k = i / (k + 2) + q; error

Suppose that a, b, c, and d are variables of the same data type. Th e following statement is legal in Java:

a = b = c = d;

In this statement, fi rst the value of d is assigned to c. Since = is an operator, c = d produces (or returns) a value and the value retuned is equal to that of c. Th erefore, this statement is equivalent to the following two statements:

c = d;

a = b = c;

By the same argument, the statement a = b = c; is equivalent to the following two statements:

b = c;

a = b;

Apago PDF Enhancer

Th us, the statement a = b = c = d; is equivalent to the following three statements:

c = d;

b = c;

a = b;

Note 2.15 Th e associativity of the assignment operator is from right to left . Th ere-fore, the assignment operator, =, is evaluated from right to left .

Self-Check

31. Assume that x and y are two variables of type int and let x be 10 and y be 20.

Aft er executing the statement x = y, the value of x is and the value of y is .

32. Write the assignment statement that will change the value of x to two times the current value of x plus three times the current value of y.

In document Java Programming Fundamentals (Page 77-82)