Variables in Java


Variable is a container which holds the value during the execution of Java program. In other words, Variable is the name of the memory locations reserved for storing value. Each variable in Java has a specific type that determines the size of the memory. The size of the memory reserved depends on the data type. 
There are two types of data types in Java: primitive and non-primitive. A variable with primitive type holds the value of primitive type. A reference type variable holds either a null reference or a reference to an object of the same type as the variable.

For example, If we write int x=20, the variable name is x which stores the value 20 in a location of memory. where int is a primitive data type which represents that this variable can store only integer values. In other words, it can only take integer values.
The value stored in any variable can be changed during program execution. 
Variables in Java, Types of variables in Java.

Variable Declaration in Java


In  Java, all the variables must be declared before they can be used. We can declare a variable in Java by using two types of syntax:
1. data_type  variable_name;
2. data_type  variable_name=value;
For example:
      int a; where int is a data type and a is variable.
      int b=20; where int is a data type and b is a variable. Here we can say that b is a type of int having value as twenty.
To declare more than one variable of the same type, we can use a comma-separated list.

Following are the valid examples of the variables declaration and initialization in Java:
 int x, y, z; //  Declares three ints x, y, and z.
 int x=10, y=20; // Example of Initialization.
 byte A=30; // Initializes a byte type variable A.
 double pi=3.14; // declares and assigns a value of PI.

Initialization of Variables in Java


The value of variables can be assigned in two ways:
1. Static: When the class is loaded into the memory, the memory is determined for the variables. Such variables are known as static variables.
For example:
       static String name="Kiran";
2. Dynamic: In dynamic initialization, you can declare variables anywhere in the program. because when the statement is executed, the memory is assigned to them.
For example:
        char ch='B'; // Declaring and Initializing character variables.
        int number=100; // Declaring and Initializing integer variables.
        int time=40, distance= 50;

Naming Convention for the declaring variables in Java
➲ As per Java coding standard, the variable name should start with a lower case letter.
For example:
             int age; 
If you have lengthy variables such as more than one words then you can declare first word small and second word with the capital letter like this:
             int smallNumber;
             String collegeName;
➲ The variable name should not contain blank space.
             int num ber=100; is invalid because there is a blank space between num and ber.
➲ The variable name can begin with a special character such as $ and _. 
➲ The first character must be a letter.
➲ Java keywords should not be used as variable name.
➲ The variable names are case sensitive in Java.
So these are some important points which you have to keep in mind for the declaration of variables in Java.

Types of variables in Java


There are three types of variable in Java:
1. Local variables.
2. Instance variables.
3. Class/Static variables.

Local Variables in Java


➲ A variable which is declared inside the body of methods, constructors or blocks is called local variable. 
➲ Local variables must be assigned a value at the time of creating. If you use a local variable without initializing a value, you will get compile time error like "variable x not have been initialized".
For example:
          public void mySchool()  {
 // Declaration of Local Variables.
String schoolName;    // Compilation error due to not initializing of value.
System.out.println("Name of School: " +schoolName);
       }
➲ No access modifiers can be used with local variables.
➲ The local variables are visible only within the declared constructor, method, or block.
➲ A local variable is not equivalent to an instance variable.
➲ A local variable cannot be static.

Scope of Local Variables in Java


1. When the local variable is created inside a method, constructor or block, their scope only remains within the method, block or constructor. They are visible only within the method, constructor or block. As you exit from the method or block then the scope of a local variable is destroyed.
2. You cannot access from outside the method, constructor or block.
3. You can not change their values from outside.
Let's see example program of local variables.
Program source code 1:
    package localVariables; public class School { // Declaration of Instance variables. public String name="John"; // Declaration of constructor. School(){ int id=1234; System.out.println("Id of Student: " +id); } // Declaration of User-Defined method. public void mySchool(){ // Declaration of Local Variables. String schoolName="RSVM"; System.out.println("Name of School: " +schoolName); } public void mySchool1(){ System.out.println("Name of School: " +schoolName)// Not possible because local variable cannot access from outside the method or constructor or block. } public static void main(String[] args) { // Create the object of class 'School'. School sc=new School(); sc.mySchool(); } }
    Output: Id of Student: 1234 Name of School: RSVM
In the above program, If you use the local Variable schoolName outside the mySchool() method, it will give the compilation error.
Program source code 2:
    package localVariables; public class School { // Declaration of Instance variables. public String name="John"; // Declaration of a constructor. School(){ int id=1234; } // Declaration of a method. public void mySchool(){ // Declaration of Local Variables inside the method. String schoolName="RSVM"; } public static void main(String[] args) { // Create the object of class 'School'. School sc=new School(); // Calling the local Variables from outside the method and constructor. System.out.println("Name of School: " +schoolName); // compilation error. System.out.println("Id of Student: " +id); // compilation error.

Memory Allocation of Local Variable


When the method starts, the memory for the local variable is allocated. When the method is completed, the memory of the local variable is released.
For example:
    void m1() // Memory allocated when the method starts. { int a=30; // Local variable. int b=40; // Logic here. } // Memory released when the method is completed.

Stored Memory of Local variables


Local variables are stored in stack memory. Consider the above example. When the main method calls the method m1(), a frame will be created in the stack memory for the method m1(). After creating a frame for method m1, a variable 'a' in method m1 is created in the frame of the stack memory. See the below picture.
Naming convention for variables in Java.

Instance Variables in Java


➲ The variables which are declared inside the class but outside the body of the method, construction or any block are called instance variables. They are available for the entire class methods, constructors, and blocks. It is also called non-static variables because it is not declared as static.
➲ Instance variables are created when an object is created using the keyword 'new' and destroyed when the object is destroyed.
➲ We can also use access specifiers for instance variables. If you do not specify any modifiers, the default access modifiers will be used which can be accessed in the same package only.
➲ It is not necessary to initialize the instance variable.

Let's take a simple example program.
Program source code 3:
    package instanceVariables; class Test{ // Declare Instance variables inside the class not inside the method, constructor or block. int a=30; int b=40; // This method is called Static method. public static void main(String[] args) // main method. { // This area is called static area. So you can access the instance variable by using an object reference variable. // Creating an object of the class Test. Test t=new Test(); System.out.println(t.a); // Access instance variable using object reference variable 't'. System.out.println(t.b); // Access instance variable using object reference variable 't'. } // Instance method. void m1() // This method is called user-defined method. { // This area is called Instance Area. So we can access directly the instance variable without creating the object. System.out.println(a); //Direct access. System.out.println(b); //Direct access. } }
    Output: 30 40

Scope of Instance variables in Java


➲ The scope of Instance variables is inside the class. They are visible for all the methods, constructors and blocks in the class. Therefore, All the methods, constructors, and blocks inside the class can access instance variables. Normally, it is recommended to make these variables private in the class. However, the visibility of instance variables for the subclasses can be given with the use of access modifiers.
➲ In the user-defined method (instance method), the instance variables can be accessed directly by calling the variable name inside the class.
➲ Within static methods and different class, instance variables should be called using object reference variable like this:
       ObjectReference.VariableName.
Consider the above example program, two methods are defined. First is the main method(called static method) and second is the user-defined method. In the main method, the instance variables 'a' and 'b' have been accessed using the object reference variable 't.a' and 't.b' respectively. However,  in the user-defined method, they have been accessed directly.

Memory allocation of Instance Variables in Java


1. Instance variables are also the variables of the object which are commonly known as field or object variable. When an object is created for a class, the memory is allocated for the instance variables and destroyed when the object is destroyed.
2. Each instance(object) of a class has its own copy of each variable. That is instance variables have their own separate copy of instance variable. If one object changes the value of a variable, it does not affect the value of other instance variables.

Let us take one more example to understand these points.
Program source code 4:
    package instanaceVariable; public class Marks { // Declare the instance variable inside the class. int phyMarks=80; public static void main(String[] args) { // Create the two objects of the class 'Marks'. Marks m1 =new Marks(); Marks m2=new Marks(); // Call the variables using object m1 and m2. int pMarks1=m1.phyMarks; int pMarks2=m2.phyMarks; System.out.println("Marks in Physics: " +pMarks1); System.out.println("Marks in Physics: " +pMarks2); /* If we change the value of instance variable using object reference m2, the value of object m1 variable will not change. Only the value of instance variable calling by using object m2 will change. This shows that they have their own copy of instance variable.*/ m2.phyMarks=90; System.out.println("After changing the value of instance variable using object m2 "); System.out.println("Marks in Physics: " +m1.phyMarks); System.out.println("Marks in Physics: " +m2.phyMarks); } }
    Output: Marks in Physics: 80 Marks in Physics: 80 After changing the value of instance variable using object m2. Marks in Physics: 80 Marks in Physics: 90
Thus, you can change the value of instance variables by using an object.


Stored memory of Instance variables in Java


When we make any program, each program has its own memory known as Run time Data Area which is allocated by JVM(Java Virtual Machine). JVM uses two memory "Stack" and "Heap" memory for storing data-type. When we create an object using the new keyword, their related object variables and properties are stored in memory. 

All instance variables are stored in PermGen space(Permanent Generation space) of heap memory. If the variables are primitive type then variable and its value both are stored as a name-value pair in the permgen. but if the variable is user-defined(object) then its reference is stored in PermGen but actually, it is stored in Young/old generation of heap memory.

Static Variables in Java


➲ The variable which is declared with the static modifier is called static variable. A static variable is also called class variable because they are associated with the class. 
➲ Static variables are always declared inside the class but outside of any methods, constructors or blocks.
Program source code 5:
    package scientecheasy; class Test{ // Declaration of static variables. static int a=400; static int b=500; // Static method or main method. public static void main(String[] args){ // Static area. So we can call a Static variable or static method by using the class name. System.out.println(Test.a); // Test is the name of class. System.out.println(Test.b); Test t=new Test(); // Creating the object of class Test. t.m1; } // Instance method. void m1(){ // Instance area System.out.println(Test.a); System.out.println(Test.b); } }
    Output: 400 500 400 500
In the above program, we must call method m1 by creating the object of the class in static area. otherwise, it will not print output. 
➲ Static variable will get the memory only once. If anyone changes the value of the static variable usingthe class name, it will replace the previous value and display changed value. This is because it is constant for every object created.
Let us consider one example.
Program source code 6:
    package scientecheasy; class College{ // Static variable static String collegeName="PIET"; // static method public static void main(String[] args){ // Both will display 'PIET' System.out.println(College.collegeName); // Suppose anyone changes the value of a static variable using the class name. In this case it will display changed value. College.collegeName="RSVM"; System.out.println(College.collegeName); } }
    Output: PIET RSVM

Scope of Static variable in Java


The scope of a static variable is within the class. All the methods, constructors, and blocks inside the class can access static variables by using the class name like this:
     ClassName.VariableName.
The visibility of the static variable is similar to the instance variable. However, the static variable must be declared as public so that it can be available for users of the class.

Memory Allocation of Static variables in Java


Memory allocation for static variables happens only once when the dot class is loaded into the memory and it is destroyed when dot class unloaded into the memory.

Stored memory of Static variables in Java


All the static variables are stored in PermGen space of heap memory.

Final words
We hope that this article has covered almost all the important topics related to Variables in Java. We have also learned types of variables & Scope in Java with example programs that are very important to learn the basic in Core Java. You practice all programs discussed in this tutorial.