These code snippets show the different types of variables and how they are used.
Instance Variables - Non-Static Fields
Instance variables are fields which are not declared with the static keyword. Its values are unique for an instance. The value of a field changed in one instance of a class is not reflected in another instance of the same class.
class SimpleVariables {
public String instanceVar = "Hello World";
public static void main(String args[]) {
SimpleVariables instance1 = new SimpleVariables();
SimpleVariables instance2 = new SimpleVariables();
instance2.instanceVar = "Hello all";
System.out.println(instance1.instanceVar);
System.out.println(instance2.instanceVar);
}
}
Class Variables - Static Fields
A class variable is a field which has been declared as static and there is only ever one copy of the field throughout its existence. Its value can be changed but it will be reflected anywhere the variable has been used.
class SimpleVariables {
public static String staticVar = "Hello World";
public static void main(String args[]) {
SimpleVariables instance1 = new SimpleVariables();
SimpleVariables instance2 = new SimpleVariables();
instance2.staticVar = "Hello all";
System.out.println(instance1.staticVar);
// Prints Hello all
}
}
Local Variables
Local variables are defined within a method and are only available and visible by the method which defined it. Once the method has terminated the local variables will go out of scope.
class SimpleVariables {
public static void main(String args[]) {
string localVar = "Hello World";
System.out.println(localVar);
}
}
Parameter Variables
Parameter variables are those that are used in the signature of a method/construct. In the examples above the parameter variable is
String args[] where args[] is the variable name.
No comments:
Post a Comment