Tag: global variables in java

Variables in Java with examples

Elements of a class in Java-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the variables of Java in detail.

Variables in Java-

 

  • Variable is an element of a class that is used for storing the values.
  • It is basically a name that is assigned to a memory location where a particular value is stored.

 

Concept of Areas in Java-

In any java program, the area can be classified into 2 types-

  1. Instance Area
  2. Static Area

 

1. Instance area-

Instance area is the area inside instance methods or instance blocks or constructors.

Example-

void m1( )           // "Instance Method" 
{ 
   // This area is called "Instance Area" 
}

 

2. Static area-

Static area is the area inside static methods or static blocks.

Example-

static void m1( )   // Static Method
{
   // This area is called "Static Area"
}

 

Types of Variables in Java-

 

Variables in Java can be broadly classified into following three types-

 

 

1. Local Variables-

 

  • Variables declared inside the methods or constructors or blocks are called as local variables.
  • The scope of local variables is within that particular method or constructor or block in which they have been declared.
  • Local variables are allocated memory when the method or constructor or block in which they are declared is invoked and memory is released after that particular method or constructor or block is executed.
  • Stack memory is allocated for storing local variables.
  • JVM takes no responsibility for assigning default value to the local variables. It is the responsibility of the programmer to initialize the local variables explicitly before using them otherwise syntax error is raised. It is important to note that no error will be raised as long as the uninitialized local variables are not used.

 

How to access local variables?

 

  • They can be called directly with their names.

 

2. Instance Variables-

 

  • Variables declared outside the methods or constructors or blocks but inside the class are called as instance variables.
  • The scope of instance variables is inside the class and therefore all methods, constructors and blocks can access them.
  • Instance variables are allocated memory during object creation and memory is released during object destruction. If no object is created, then no memory is allocated.
  • For each object, a separate copy of instance variable is created.
  • Heap memory is allocated for storing instance variables.
  • It is the responsibility of the JVM to assign default value to the instance variables as per the type of variable.

 

How to access instance variables?

 

  • Instance variables can be called directly inside the instance area.
  • Instance variables can not be called directly inside the static area and necessarily requires an object reference for calling them.

 

3. Static Variables-

 

  • Variables declared with “static” modifier outside the methods or constructors or blocks but inside the class are called as static methods.
  • The scope of static variables is inside the class and therefore all methods, constructors and blocks can access them.
  • Static variables are allocated memory during loading of .class file by the JVM and memory is released during unloading of .class file.
  • A single copy gets created for the static variables and this single copy is shared by all the objects belonging to that class.
  • Non-heap memory is allocated for storing static variables.
  • It is the responsibility of the JVM to assign default value to the static variables as per the type of variable.

 

Since, static variables are associated with the entire class, they are popularly called as class variables.

 

How to access static variables?

 

  • It is allowed to call static variables by using class name and dot operator. (Recommended)
  • It is allowed to call static variables directly within the same package.
  • It is allowed to call static variables by using object reference and dot operator.

 

NOTE-

 

  • Although static variables can be accessed using object reference and dot operator but it is not recommended because it does not make it clear that we are talking about the class variables.

Always make a habit of calling the static variables using class name and dot operator.

 

Default values of the variables-

 

JVM assigns default value to the instance and static variables automatically when the programmer does not initialize the variables with some value.

However, JVM takes no responsibility for initializing the local variables with default values.

The default values are assigned as per the following table-

 

Data Type of the variableDefault Value
byte0
short0
int0
long0
float0.0
double0.0
char<single space>
BooleanFalse
classNull

 

Real life example illustrating where to use what kind of variable-

 

  • We must declare the variable as instance variable if the value of that variable will be different for different objects.
  • We must declare the variable as static variable if the value of that variable will be same for different objects so as to save the memory.

 

Example-01:

 

  • If we are creating a class ‘Student‘, then in that class all the Student objects will obviously have different names but the school name for all the students will be definitely same.
  • So, we can declare the variable ‘student_name’ as instance variable and variable ‘school_name‘ as static variable.
  • If we would have declared variable ‘school_name‘ as instance variable, then one copy of it would have been created for each Student object and the memory would be wasted unnecessarily.

 

class Student
{
   static String school_name;
   String student_name;
}

 

Example-02:

 

  • If we are creating a class ‘Employee‘, then in that class all the Employee objects will obviously have different names but the company name for all the employees will be definitely same.
  • So, we can declare the variable ’employee_name’ as instance variable and variable ‘company_name‘ as static variable.
  • If we would have declared variable ‘company_name‘ as instance variable, then one copy of it would have been created for each Employee object and the memory would be wasted unnecessarily.

 

class Employee
{
   static String company_name;
   String employee_name;
}

 

Comparison table of different types of variables in Java-

 

 Local VariablesInstance VariablesStatic Variables
Declaration placeInside the methods or constructors or blocks.Outside the methods or constructors or blocks but inside the class.Outside the methods or constructors or blocks but inside the class.
ScopeWithin that particular method or constructor or block in which they have been declared.Inside the class.Inside the class.
Time of memory allocationMemory is allocated when the method or constructor or block in which they are declared is invoked.Memory is allocated during object creation.Memory is allocated during loading of .class file by the JVM.
Time of memory deallocationMemory is released after that particular method or constructor or block is executed.Memory is released during object destruction.Memory is released during unloading of .class file.
Storing placeStack memoryHeap memoryNon-heap memory
Assigning of default valuesResponsibility of programmer to initialize with values.

JVM takes no responsibility for initializing with default values.

Responsibility of JVM to initialize with default valuesResponsibility of JVM to initialize with default values
Accessing methodCan be called directly with name.Can be called directly inside the instance area but inside the static area requires an object reference.Recommended way is by using class name and dot operator.

 

Program illustrating how to use different kinds of variables-

class Test
{
   int a = 10;                              // "Instance Variable"
   static int b = 20;                       // "Static Variable"

   void print( )                            // "Instance method"
   {
      System.out.println(a);                // "Accessing instance variable directly in instance area"
   }

   public static void main(String[ ] args)
   {
      Test t = new Test( );                 // "Object Creation"
      System.out.println(t.a);              // "Accessing instance variable using object reference in static area"
      System.out.println(b);                // "Accessing static variable directly within same package"
      System.out.println(t.b);              // "Accessing static variable using object reference"
      System.out.println(Test.b);           // "Accessing static variable using class name and dot operator"
      t.print();                            // "Accessing instance method using object reference in static area"
   }
}

OUTPUT-

10
20
20
20
10

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.