(^60) | Java Syntax and Semantics, Classes, and Objects
Assignment We can set or change the value of a variable through an assignment statement.For
example,
lastName = “Lincoln”;
assigns the string value ”Lincoln”to the variable lastName(that is, it stores the sequence of
characters “Lincoln” into the memory associated with the variable named lastName).
Here’s the syntax template for an assignment statement:
The semantics (meaning) of the assignment operator (=) are “is set equal to” or
“gets”; the variable is set equal tothe value of the expression. Any previous value in
the variable is destroyed and replaced by the value of the expression. If you look
back at the syntax for a field declaration, you can see that it uses the same syn-
tax to assign an initial value to a field.
Only one variable can appear on the left side of an assignment statement. An
assignment statement is notlike a math equation (x+ y= z+ 4). Instead, the ex-
pression (what is on the right side of the assignment operator) is evaluated, and the
resulting value is stored into the single variable on the left side of the assignment
operator. A variable keeps its assigned value until another statement stores a new
value into it.
Because you are accustomed to reading from left to right, the way that the as-
signment operator moves a value from right to left may at first seem awkward. Just
remember to read the =as “is set equal to” or “gets”—then the process seems more
natural.
The value assigned to a variable must be of the same type as the variable. Given the
declarations
String firstName;
String middleName;
String lastName;
String title;
char middleInitial;
char letter;
the following assignment statements are valid:
firstName =“Abraham”; // String literal assigned to string variable
middleName = firstName; // String variable assigned to string variable
middleName = “”; // String literal assigned to string variable
Variable = Expression ;
Assignment-Statement
Assignment statement A
statement that stores the value
of an expression into a variable
Expression An arrangement
of identifiers, literals, and opera-
tors that can be evaluated to
compute a value of a given type
Evaluate To compute a new
value by performing a specified
set of operations on given val-
ues
T
E
A
M
F
L
Y
Team-Fly®