您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 38

Assigning values to variables

Although it is possible to assign an initial value to a variable when it is first declared, variables will usually have their value changed one or more times during the execution of the program. This makes sense, since variables by their nature are designed to have their values changed (i.e. vary) — if the value is not to change one should define a constant instead.

The way to assign a value to a variable is the same way as giving it an initial value — i.e. by the use of the assignment operator =. When we assign a value to a variable, this new value overwrites any previous value. Examples of assigning values to variables include:

age = 21;

sum = (2 + 2);

nextAge = (age + 1);

stockLevel = 100;

stockLevel = (stockLevel + deliverySize);

carLockCode = Math.random();

As you may have inferred from these examples, there is a required format for variable assignment statements. On the left hand side is the variable identifier, followed by the assignment symbol =, and on the right hand side is an expression, that must evaluate to a type that can be stored in the variable.

The format of the expression can be simple or complex. Expressions are investigated later this unit. A summary of the different expressions in the example above is as follows:

expression

evaluates to

expression type

21

21

any integer or real type

(2 + 2)

4

any integer or real type

(age + 1)

22 (21 + 1)

any integer or real type

Math.random()

a pseudo-random number from 0.0 up to but not include 1.0

double (since the random() method defines its reply type as double)

.Back to top

 basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg