Java Variables

Variables in Java 

A variable in java is the name given to a memory location. This is the basic unit of storage in a program.

  • The stored value in a variable can be changed during program execution process or compilation.

  • A variable is only a name in java given to a memory location, all the operations done over the variable effects that memory location.

  • In Java programming, all the variables must be declared before they can be used.

How to declare a variables in java?
It is quite simple.

  1. datatype: Type of data (datatype like int,char,float) that can be stored in this variable.
  2. variable_name: write a name given to the variable.
  3. value: It is the initial value stored in the variable (As per your requirement according dataype any value).

Examples:

double simpleInterest; //Declaring float variable
int time = 5, speedLimit = 10; //Declaring and Initializing integer variable
char alpha = 'r'; // Declaring and Initializing character variable

Types of variables : 

It is very important for the biginner. When you are working in java you should know which type of variables declare.

There are three types of variables in Java:

  • Local Variables
  • Instance Variables
  • Static Variables

Now we learn about each one of these variables in detail.

  1. Local Variables: If a variable defined within a block or method or constructor is called local variable.
     
    • These variables are created when the control entered in block or the function is called and destroyed after exiting from the block or when the call returns from the function.
    • The scope of these variables exists only within the method, constructor or block in which the variable is declared. i.e. we can access these variable only within that method, constructor or block.

    Sample Program 1:

    public class TestLocalVariable{
        public void myAge(){   //local variable age
    
            int age = 0;
            age = age + 5;
            System.out.println("Age is : " + age);
    
        }
    
        public static void main(String args[]){
    
            TestLocalVariable obj = new TestLocalVariable();
    
            obj.myAge();
    
        }
    
    }
     
    Output:
    
    Age is : 5
    

    In the above program the variable age is local variable to the method myAge(). If we use the variable age outside myAge() method, the compiler will produce an error. Variable age is valid with in the method.

  2. Instance Variables:
    Instance variables are class level non-static variables and are declared in a class outside any method, constructor or block.

     

    • An instance variables are declared in a class. These variables are created when an object created of the class and destroyed when the object is destroyed.
    • Unlike local variables, we may be use access specifiers for instance variables or If we do not specify any access specifier then the default access specifier will be used.

    Sample Program:

    import java.io.*;
    
    class Score{  
    
        //These variables are instance variables.
        //These variables are in a class and are not inside any function
    
        int ramScore;
        int rahulScore;
    }
    
    class ScoreTest{
    
        public static void main(String args[]){   //first object
    
            Marks obj1 = new Marks();
            obj1.ramScore= 50;
            obj1.rahulScore= 80;
            //second object
    
            Marks obj2 = new Marks();
            obj2.ramScore= 80;
            obj2.rahulScore= 60;
    
            //displaying marks for first object
            System.out.println("Marks for first object:");
    
            System.out.println(obj1.ramScore);
    
            System.out.println(obj1.rahulScore);
    
         
    
            //displaying marks for second object
    
            System.out.println("Marks for second object:");
    
            System.out.println(obj2.ramScore);
    
            System.out.println(obj2.rahulScore);
    
        }
    
    }
     
    Output:
    
    Marks for first object:
    50
    80
    Marks for second object:
    80
    60
    

    As you can see in the above program the variables, ramScorerahulScore, instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of instance variable.

  3. Static Variables:

    Static variables are also known as Class variables but the difference is that static variables are declared using the static keyword.
     
    • These variables are declared similarly as instance variables but the major difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
    • Unlike instance variables, we can only have sngle copy of a static variable per class irrespective of how many objects we create.
    • Static variables are created at start of program execution and destroyed automatically when execution ends.

    It's quite interesting in java to access static variables, we did not need to create any object of that class, we can simply access the variable by the class name:

    class_name.variable_name;

    Sample Program:

    import java.io.*;
    
    class OfficeEmployee{
    // static variable salary
       public static double salary;
       public static String name = "Rajeev";
    
    }
    
    public class EmpDemo{
    
         public static void main(String args[]) {       
    
          //accessing static variable without object        
    
          OfficeEmployee.salary = 1000;
    
          System.out.println(OfficeEmployee.name + "'s average salary:" +           OfficeEmployee.salary);
    
       }     
    
    }
     
    output:
    
    Harsh's average salary:1000.0
    

Instance variable Vs Static variable

  • We can only have one copy of a static variable per class irrespective of how many objects we create whereas each object will have its own copy of instance variable
  • In case of static, changes will be reflected in other objects as static variables are common to all object of a class.Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable..
  • We can access instance variables through object references and Static Variables can be accessed directly using class name as we see in above program.
  • Syntax for static and instance variables:
    class Example
        {
            static int a; //static variable
            int b;        //instance variable
        }

Related Articles

post a comment