July 6, 2014
Variables in Java
Java Programming languages defines four flavors of variables:
- Instance variables (also known as non-static variables). They are declared inside a Java class, but outside of the scope of a method. Their values are unique to each instance (object) of the class.
- Class variable (also known as static variables). It can be said that a class variable is an instance variable declared with static keyword. Regardless how many object of the class has been instantiated, they share the same value for a class variable.
- Local variables. This are variables defined within the scope of a method. Such variables are defined only to the method within they are declared (i.e are not accessible from the rest of the class).
- Method variables (or simple parameters).
NOTE : Instance variables and class variable are sometimes called fields.
Take away 1 : Each object has its own copy of the instance variable.
Take away 2 : All objects share the same value for the class variable.