After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign ( = ) is used as the assignment operator . The syntax for assignment statements is as follows :
variable = expression;
An expression represents a computation involving values, variables , and operators that together evaluates to a value. For example, consider the following code:
int x = 1 ; // Assign 1 to variable x; double radius = 1.0 ; // Assign 1.0 to variable radius; x = 5 * ( 3 / 2 ) + 3 * 2 ; // Assign the value of the expression to x; x = y + 1 ; // Assign the addition of y and 1 to x; area = radius * radius * 3.14159 ; // Compute area
A variable can also be used in an expression. For example,
x = x + 1 ;
In this assignment statement, the result of x + 1 is assigned to x . If x is 1 before the statement is executed, then it becomes 2 after the statement is executed.
To assign a value to a variable, the variable name must be on the left of the assignment operator . Thus, 1 = x would be wrong.
In Java, an assignment statement can also be treated as an expression that evaluates to the value being assigned to the variable on the left-hand side of the assignment operator. For this reason, an assignment statement is also known as an assignment expression . For example, the following statement is correct:
System.out.println(x = 1 );
which is equivalent to
x = 1 ; System.out.println(x);
The following statement is also correct:
i = j = k = 1 ;
which is equivalent to
k = 1 ; j = k; i = j;
Note
In an assignment statement, the data type of the variable on the left must be compatible with the data type of the value on the right. For example, int x = 1.0 would be illegal because the data type of x is int . You cannot assign a double value ( 1.0 ) to an int variable without using type casting. Type casting is introduced in §2.8, "Numeric Type Conversions." |
Variables often have initial values. You can declare a variable and initialize it in one step. Consider, for instance, the following code:
int x = 1 ;
This is equivalent to the next two statements:
int x; x = 1 ;
You can also use a shorthand form to declare and initialize variables of the same type together. For example,
int i = 1 , j = 2 ;
Tip
A variable must be declared before it can be assigned a value. A variable declared in a method must be assigned a value before it can be used. Whenever possible, declare a variable and assign its initial value in one step. This will make the program easy to read and avoid programming errors. |