Variable Assignment
Variables are assigned, or given, values using one of the assignment operators. The variable is always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment operator. Assignment is always from right to left.
Here are some examples of assignments:
//assign 1 to
//variable a
int a = 1;
//assign the result
//of 2 + 2 to b
int b = 2 + 2;
//assign the result
//of a + b to c
int c = a + b;
//assign the result
//of b + 2 to b
b += 2;
//assign the literal
//"Hello" to str
String str = new String("Hello");
//assign b to a, then assign a
//to d; results in d, a, and b being equal
int d = a = b;
/**
* Demonstrates variable identifiers,
* types, and scopes
*/
public class VariableExample {
private static int classCounter = 0;
private int instanceCounter = 0;
public void increment() {
int localCounter = 0;
classCounter++;
instanceCounter++;
localCounter++;
System.out.println(
"classCounter:\t\t" + classCounter + "\n" +
"instanceCounter:\t" + instanceCounter + "\n" +
"localCounter:\t\t" + localCounter + "\n"
);
}
public static void main(String args[]) {
VariableExample var1 = new VariableExample();
VariableExample var2 = new VariableExample();
var1.increment();
var2.increment();
}
}
c:\>arun\javac VariableExample.java c:\>arun\java VariableExample classCounter: 1 instanceCounter: 1 localCounter: 1 classCounter: 2 instanceCounter: 1 localCounter: 1