Java Reference
In-Depth Information
Every variable has a scope. The scope of a variable is the part of the program where the
variable can be referenced. The rules that define the scope of a variable will be introduced
gradually later in the topic. For now, all you need to know is that a variable must be declared
and initialized before it can be used. Consider the following code:
scope of a variable
int interestRate = 0.05
int interest = interestrate * 45
This code is wrong, because interestRate is assigned a value 0.05 , but interestrate
has not been declared and initialized. Java is case sensitive, so it considers interestRate and
interestrate to be two different variables.
2.6 Assignment Statements and Assignment
Expressions
An assignment statement designates a value for a variable. An assignment statement
can be used as an expression in Java.
Key
Point
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 state-
ments is as follows:
assignment statement
assignment operator
variable = expression;
An expression represents a computation involving values, variables, and operators that,
taking them together, evaluates to a value. For example, consider the following code:
expression
int y = 1 ; // Assign 1 to variable y
double radius = 1.0 ; // Assign 1.0 to variable radius
int x = 5 * ( 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
You can use a variable in an expression. A variable can also be used in both sides of the
operator. For example,
=
x = x + 1 ;
In this assignment statement, the result of x + 1 is assigned to x . If x is 1 before the state-
ment is executed, then it becomes 2 after the statement is executed.
To assign a value to a variable, you must place the variable name to the left of the assign-
ment operator. Thus, the following statement is wrong:
1 = x; // Wrong
Note
In mathematics, x = 2 * x + 1 denotes an equation. However, in Java, x = 2 * x
+ 1 is an assignment statement that evaluates the expression 2 * x + 1 and assigns
the result to x .
In Java, an assignment statement is essentially an expression that evaluates to the value to
be assigned to the variable on the left 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:
assignment expression
System.out.println(x = 1 );
 
 
Search WWH ::




Custom Search