blog

Home / DeveloperSection / Blogs / Types Of Variables

Types Of Variables

Anonymous User 857 31-Aug-2018

TYPES OF VARIABLES

On the basis of type of value representation variables are classified into two types:

• Primitive

• Reference

Primitive variables: it can be used to represent primitive values e.g. int x=10;

Reference variables: it can be used to refer objects. e.g. Student s=new Student();

Based on the purpose and position of declaring all variables are divided into three types:

• instance variable

• static variable

• local variable

Instance variable:

If the value of a variable is varied from object to object such type of variables is called instance variable.

For every object, a separate copy of instance variable will be created.

The scope of instance variables is exactly the same as of the objects.

For the instance variable, it is not required to perform initialization explicitly. JVM will provide default values.

e.g.

class example{

String s;
int x;
Boolean b;
Public static void main (string[] args)
{
example t=new example();
System.out.println(t.s);
System.out.println(t.x);
System.out.println(t.b);
}
Output:
null
0
false

Static variables:

If the value of a variable is not varied from object to object then it is never recommended. To declare that variable at we have to declare such type of variables at class level by using the static modifier.

In case of static variable single copy will be created at the class level and a copy will be shared by all objects of that class.

• Static variables will be created at the time of class loading and destroy at the time of class unloading. hence  the scope of the static variable is exactly the same as the scope of a class

• Static variables can be accessed by using class name or object reference.

e.g.

class example{

static int x=10;
{
      Public static void main (string[] args)
{
        System.out.println(example.x);
        System.out.println(x);
     }

Local variables:

   To meet temporary requirements of the programmer sometimes we have to create variables inside method or block or constructor such type of variables are called local variables.

It is also known as stack variables or automatic variable or temporary variables. local variables will be stored inside a stack.

The scope of the variable blocks in which it is declared.

e.g.

class test{

public static void main(string[] args)
{
int x;
System.out.println(“hello”);
}
}



Updated 31-Aug-2018
I am a content writter !

Leave Comment

Comments

Liked By