Variables are defined in a class or in a method. There are no global variables in Java.
Variables declared in a class
Variables defined in a class and not in the methods of a class are either class variables or instance variables.
class CookieMonster
{
static int cookiesAvailable = 100; // I am a class variable
String monsterName = ""; // I am an instance variable
int cookiesEaten; // I am an instance variable
// Class methods
// ||
// \/
}
Instance variables
Instance variables get their name because the act of creating an object variable from a class is called instantiation. Each object or you could say each instance of the class gets a separate copy of the instance variables.
// Construct an instance named monster1
// from CookieMonster class
CookieMonster monster1 = new CookieMonster;
// Accessing instance variable.
System.out.println( monster1.cookiesEaten );
Class (static) variables
Class variables are shared by all object variables of the class. Said another way all instances of the class share these variables. Technically they are static variables. Class variables are defined with the static access modifier keyword.
Accessing static variables uses the class name or an object variable constructed from a class.
// Accessing a class static variable using class name
System.out.println( CookieMonster.cookiesAvailable );
// Construct an instance named monster1
// from CookieMonster class
CookieMonster monster1 = new CookieMonster;
// Accessing a class static variable using object name
System.out.println( monster1.cookiesAvailable );
Variables declared in a method
Variables defined in a method only exist while the method runs and we can call them local variables.
class CookieMonster
{
static int cookiesAvailable = 100; // I am a class variable
String monsterName = ""; // I am an instance variable
int cookiesEaten; // I am an instance variable
void eatCookies(int howMany)
{
// The cookiesToEat and COOKIESPERBITE variables
// only exist for duration of eatCookies method
int cookiesToEat = Math.min(cookiesAvailable, howMany) ;
final int COOKIESPERBITE = 3 ;
// more lines of code for this method
Primitive variables as declared in a method argument
Primitive variables can be defined in a method argument. Theses variable only exist while the method runs and therefore are local variables.
class CookieMonster
{
static int cookiesAvailable = 100; // I am a class variable
String monsterName = ""; // I am an instance variable
int cookiesEaten; // I am an instance variable
void eatCookies(int howMany)
{
// Update field cookiesEaten with local
// variable howMany
cookiesEaten -= howMany;
// howMany variable goes out of scope
}
}
Object variables as declared in a method argument
Object variables can be defined in a method argument. Theses variable exist outside the method and therefore do not have a local scope. We will look at the details of object variable later.