Chapter 3
Topic: Variables & their Scope
Outlines [Expected Time: 1 Hours]
• Variables and their Scope
• Local Variables
• Instance Variables
• Class Variables
Variables
Variables are the data members or the fields defined
inside a class.
There are three types of variables:
Local Variables
Instance Variables
Class Variables
Local Variables
Local variables are those data members which are
declared in methods, constructors, or blocks.
They are created only when the method, constructor or
block is executed and destroyed as soon as the
execution of that block is completed.
So the visibility of local variables is inside the block
only, they can’t be accessed outside the scope of that
block.
Important
Access modifiers are NOT ALLOWED with local
variables.
Local variables are created in STACK.
Default value is NOT ASSIGNED to the local variables in
Java.
Instance Variables
• Variables which are declared in a class, but outside a
method, constructor or any block are known as instance
variables.
• They are created inside the object in heap.
• Each object has its own set of instance variables and
they can be accessed/modified separately using object
reference.
• Instance variables are created when an object is created
with the use of the 'new' keyword and destroyed when the
object is destroyed.
• Access modifiers can be used with instance variables.
• Instance variables have default values (Initialization is not
mandatory, JVM will take the default value)
• For numbers the default value is 0,
• for Booleans it is false
• and for object references it is NULL.
Class (Static) Variables
Class variables are also known as static variables.
Variable which are declared in a class, but outside a method,
constructor or a block and qualified with ‘static’ keyword are known
as class variables.
Used when we don’t want to modify the value from object to object.
Only one copy of each class variable is created, regardless of how
many objects are created from it.
Static variables can be accessed by calling with the class name.
ClassName.VariableName
Static variables are created with the start of execution of a
program and destroyed when the program terminates.
Default values are same as instance variables.
A public static final variable behaves as a CONSTANT in
Java.
Static variables can be initialized using static block also.
Variable Initialization
Local variables must be initialized explicitly by the
programmer as the default values are not assigned to them
where as the instance variables and static variables are
assigned default values if they are not assigned values at the
time of declaration.
Data Types
• Data types represent the different values to
be stored in the variable.
• In Java, there are two types of data types:
1.Primitive data types
2.Non-primitive data types