Java Beginners - Java For Beginners Java Variables Rating: 0.0/5 (0 votes cast) | Level : Beginners Author : Arunkumar S Download Source : Not Avaliable
Java Variables -Using Java Variables 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;
In the class displayed below, two instances of class VariableExample are instantiated in main(). VariableExample has three variables declared, classCounter, instanceCounter, and localCounter. classCounter is shared by all instances of VariableExample. Each instance of VariableExample, on the other hand, has its own unique value stored in instanceCounter. Since localCounter is a local variable, a new version of localCounter is created each time the increment() method is called. When execution hits the closing curly brace of the increment method, localCounter becomes invalid.
/** * 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(); } }
Save this class as VariableExample.java and compile it with the javac command. Then run the example with the java command. c:\>arun\javac VariableExample.java c:\>arun\java VariableExample classCounter: 1 instanceCounter: 1 localCounter: 1
classCounter: 2 instanceCounter: 1 localCounter: 1
As you can see in the program output, increment() was called once on each of the two instances of VariableExample. The classCounter reflects this with a final count of two. Each instanceCounter only has a count of one because each was only incremented once when increment() was called on its instance. Finally, localCounter also only has one as its final count since it was reset after each call to the enclosing method. < Previous 1 | 2 |
Discussion about this tutorial
 Start a new Discussion | Read All Discussion
|