The assignment statement
An assignment statement assigns a value to a variable. When executed,
the expression on the right-hand side of the assignment operator (=
) is evaluated, and the result is stored in the memory location indicated
by the variable on the left-hand side. This is called right-to-left associativity.
Example 2: Here are some valid Java assignment statements.
x = 5;
n = 3.5;
myState = false;
myName = "Jane Doe";
myName = new String("Jane Doe");
int ans = 90;
Variables that represent primitive types are ready to be assigned values
after they are declared. Variables that represent objects have to be
instantiated before they can be accessed.
To summarize, in the assignment
state A = B:
Exercise: 5 Using assignment to exchange values.
Draw a picture of what happens for the following code
(assignment involving a variable of primitive type):
- A must represent a location.
- A value is computed for B and put into the location represented
by A .
- A and B must have compatible types.
int count = 5;
next = count;
Note: You are not required to understand assignment with objects at this point.
Exercise 6: Assignment with objects. (Draw a picture.)
Draw a picture of what happens for the following code:
String AnotherString = new String("Hello");
thisString = AnotherString;
Constants hold a particular value for the duration of their existence. Java uses the
keyword final to designate a constant.
Here are some valid Java constant declarations:
final int MAX_OCCUPANCY = 427;
final double CONVERSION_FACTOR = 9/4;