|
Variables are categorized based on where they are declared within a class body. You can declare variables inside a class body but not inside any method. You can also declare variables inside a method body. In addition, you can also declare variable inside a code block.
|
|
A code block is nothing but a Java code enclosed by a pair of curly brackets. You can define code block inside a class body as well as inside a method body. |
Let us first understand these three different scopes, the class body, method body and a code block. Figure 1.4 illustrates these three scopes.
![]() |
Figure 1.4 Three different scopes of variable declarations
When you declare variables directly inside a class body (but not inside any method or code block), they are called as the member variables. When you declare variables inside a method body or inside a code block, they are called as the local variables. Note that the method parameters are also considered as local variables. Listing 1.2 shows the member variables and local variables in the class Account.

Let us discuss the subcategories of member variables and the local variables with the help of the class Account.
As you can see in Listing 1.2, the class Account has two member
variables, totalAccounts and balance. Note that they are of two different
kinds of member variables. The member variables can be of two types, static
variables (aka class variables) and instance variables.
a) The static variable is a member variable
declared using the keyword static
within a class body. Static variables are also known as class variables. They
are created when the class is loaded[†].
The variable totalAccounts in listing 1.2 is a static variable. It will be
created when the Account class is loaded first time by the Java class loader.
b)
The instance variable
is also a member variable, but it is declared without the keyword static. Instance variables come into
life when an instance (i.e. object) of a class is created and they
remain associated with that instance. Instance variables are destroyed as soon
as that particular instance is destroyed. The variable balance in listing 1.2
is an instance variable. It is created whenever you create an object of Account
class.
In Listing 1.2, the method getInterest() has two local
variables, interest and amount. Note that a local variable is destroyed
after the execution of its declaring method or block is complete. Therefore,
the variable interest in listing 1.2 will be accessible only within the getInterest()
method body. Since method parameters are also local variables, the variable amount
in listing 1.2 is also local to method getInterest() and it too is
accessible only within the getInterest() method body.