Variables

VARIABLES

Variables are called named memory locations. It provides named storage that our programs can manipulate.
The above diagram shows a RAM block. Each cell in a RAM is stores the data and has got its own address. Here the addresses are 2000,2001,2002....... and data are 10, 256,25 etc. When we declare a variable it points to one of its memory locations that means it represents one of the addresses of the RAM.

There are three types of variables:-
1. LOCAL - These type of variables are declared inside a function. They can be accessed only inside the block of the function. These variables do not have any default value thus they need to be declared and initialized before use.For example:-

//PROGRAM TO SHOW LOCAL VARIABLES
class Localvar
{
      public static void main(String args[])
      {
          int a=5;    //local variables
          System.out.println(a);
      }
}

//OUTPUT
5

2. INSTANCE - These type of variables are declared inside a class but outside a method. These variables have a larger scope than the local variables. They can have an access specifier to show that they can be used from other classes too. 


//PROGRAM TO SHOW INSTANCE VARIABLES

class Instancevar

{

      int a=5;    //instance variables

      public void main(String args[])
      { 
            System.out.println(a);
      }
}

//OUTPUT
5



Note:- Right click on the file that you see in the above image. select new Instancevar(). Click on ok.
Right click on the above object and then select void main(String args[]).
Then type {} in the box and click on ok.

3. STATIC - These type of variables are also declared inside a class but outside a method. These variables have a larger scope than the local variables. They are declared static.

//PROGRAM TO SHOW STATIC VARIABLES
class Staticvar
{
      static int a=5;    //static variables
      public static void main(String args[])
      { 
            System.out.println(a);
      }
}

//OUTPUT
5


-----------------------------------------------------------------------------------------------------------------------
Question--> What is the difference between static and instance variables?
Answer-->In case of instance variables, every object has a copy of each variable. Thus any changes made to the copy will not have any effect on the instance variable.
For static variables, it happens that there is only one variable being shared by all the objects. Thus any changes made to the copy will change the original value too.




    Comments

    Popular Posts