Scientech Easy Variables & their Scope in Java | Instance, Local & Static | Scientech Easy

Thursday, June 21, 2018

Variables & their Scope in Java | Instance, Local & Static

java variables,scope of variables in java,java variable declaration,instance variable,static variables in java,types of variables in java,local variables in java

Variables in Java

Variables are the memory locations reserved for storing values. The size of the memory reserved depends on the data type. For example, If I write int x=20, variable name is x which stores the value 20 in a location of memory. where int is a 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. In  Java, all the variables must be declared before they can be used.
JAVA

Variable Declaration in Java

 We can declare a variable in Java by using the 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.
we will discuss data type in next tutorial. So you do not worry about so much. It is very easy.

How to initialize the value 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 called 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 then 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;
 Variables name should contain blank spaces.
     For example 
                            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:
Instance Variables.
Local Variables.
Static Variables.

Instance Variables

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.
➝ We can also use access modifiers for instance variables. If you do not specify any modifiers then the default access modifiers will be used which can be accessed in same package only.
➝ It is not necessary to initialize the instance variable.
Let us understand with simple example:
Program 1:


    class Test{ // Declaration of 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 instance variable by using an object. // Creating the object of the class Test. Test t=new Test(); System.out.println(t.a); // Access instance variable using object 't'. System.out.println(t.b); // Access instance variable using object 't'. } // Instance method. void m1() // This method is called user-defined method. { // This area is called Instance Area. // So You can access directly 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

The scope of Instance variables is inside the class. All the methods, constructors, and blocks inside the class can access instance variables. In the above example, two methods are defined First is the main method(static method) and second is the user-defined method. In the main method, you can access by using the object
Inthe user-defined method (instance method), You can access directly.

Memory allocation of Instance Variables

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 then memory is allocated for the instance variables and when the object is destroyed then memory acllocation for instance variables are also destroyed.
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 variable then it does not affect the value of other instance variables.

Let us take one more example to understand these points.
Program 2:

    package instanaceVaribable; public class Marks { // Declare the instance variable inside the class. int phyMarks=80; // Static method. public static void main(String[] args) { // TODO Auto-generated method stub // 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 m2 then 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

When we make any program then each program has its own memory called Runtime Data Area which is allocated by JVM(Java Virtual Machine) in which two "Stack" and "Heap" memory is used for storing data-type. When we create an object using new keyword then its related object variable and properties are stored in memory. So where instance variables are stored in the 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.
we will discuss whole details in the memory management tutorial.

Local Variables

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 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 are used with local variables.

Scope of Local Variables

➝ When the local variable is initialized inside a method, constructor or block then their scope only remains within the method, block or constructor.  That is they are visible only within the method or block. As you exit from the method or block then the scope of a local variable is destroyed.
 You cannot access from outside the method, constructor or block.
➝ You can not change their values from outside.
Let us understand all these points taking  examples of the local variable:
Program 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 and cannot use access modifers. 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(); // We are calling method 'mySchool' using object sc. 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 then it will give the compilation error.
Program 2:


    package localVariables; public class School { // Declaration of Instance variables. public String name="John"; // Declaration of constructor. School(){ int id=1234; } // Declaration of method. public void mySchool(){ // Declaration of Local Variables and cannot use access modifers. String schoolName="RSVM"; } public static void main(String[] args) { // Create the object of class 'School'. School sc=new School(); // using local Variable outside the method or constructor. System.out.println("Name of School: " +schoolName); // compilation error. System.out.println("Id of Student: " +id); // compilation error.
A local variable is not eyuivalent to instance variable.
A local variable cannot be static.

Memory allocation of Local Variable

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

Stored memory of Local variables

Local variables are stored in stack memory. Consider the above example. when the main method call the method m1 then a frame will be created from the method m1 in the stack Java and the variable 'a' in method m1 will also be created in the frame of the stack. see below image.

local variables

Static Variables

The variables which are declared with static modifier are called static variables. Static variables are also called class variables because they are associated with the class. 
Static variables are always declared inside the class but outside any methods, constructors or blocks
Let's taking one simple example to understand these points.
Program 1:

    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. // You can call Static variable or static method by using 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 m1 method by creating the object of 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  using 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 2:


    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 change the value of static variable using class name. In this case it will display changed value. College.collegeName="RSVM"; System.out.println(College.collegeName);
    Output: PIET RSVM

Scope of Static variables

The scope of static variable is within the class. All the methods, constructors, and blocks inside the class can access static variables by using the class name.

Memory Allocation of Static variables

Memory allocation for static variables happen 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

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

Final words:
I hope this article will help you to understand about the tutorial 'Variables & their scope in Java'. Instance, Local, and Static variables are very important to learn the basic in Core Java. You can not skip this and practice all programs discussed in this tutorial.

Popular