Java Reference
In-Depth Information
In Java (within a method), you must declare all identifiers before you can use them. If you
refer to an identifier without declaring it, the compiler will generate an error message
indicating that the identifier is not declared.
2
Putting Data into Variables
Now that you know how to declare variables, the next question is: How do you put data
into those variables? The two common ways to place data into a variable are:
1. Use an assignment statement.
2. Use input (read) statements.
ASSIGNMENT STATEMENT
The assignment statement takes the following form:
variable = expression;
In an assignment statement, the value of the expression should match the data type of
the variable . The expression on the right side is evaluated, and its value is assigned to
the variable (and thus to a memory location) on the left side.
A variable is said to be initialized the first time a value is placed in the variable.
In Java, = (the equal sign) is called the assignment operator.
EXAMPLE 2-13
Suppose you have the following variable declarations:
int num1;
int num2;
double sale;
char first;
String str;
Now consider the following assignment statements:
num1 = 4;
num2 = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day.";
For each of these statements, the computer first evaluates the expression on the right and
then stores that value in a memory location named by the identifier on the left. The first
statement stores the value 4 in num1 , the second statement stores 9 in num2 , the third
statement stores 20.00 in sale , and the fourth statement stores the character 'D' in
first . The fifth statement assigns the string "It is a sunny day." to the variable str .
 
 
Search WWH ::




Custom Search