Sunday, 29 January 2017

VARIABLE AND TYPES OF VARIABLES IN JAVA

Variable is a named memory location used to store data temporarily. During program execution we can modify that data. A variable can be created by using datatype.We can create two types of variables –

1. Primitive variables – these variables are created by using primitive data types.
2. Referenced variable – these variable are created by sign referenced data types.

The difference between primitive and referenced variables is primitive variables store data directly where as reference variables store reference of the object and, not direct value.

Program to show the procedure for creating primitive and referenced variables –
class Example{
          int x=10;
          int y=20;
}
public class Demo {
          public static void main(String[] args) {
                   int p =50;
                   int q=m1();
                   String s1="Rakesh";
                   String s = new String("Rakesh");
                   Example e = new Example();
          }
          static int m1()
          {
                   return 50;
          }
}

Limitations –
It can store only single value at a time. If we assign a new value, old value is replaced with new value. It means it returns the last modified value. So, If we modify primitive variable previous value is replaced with new value. If we modify referenced variable previous object’s reference is replaced with new objects reference and now this reference variable refers to this new object.


Types of variables – Based on class scopes, variables are divided into three types –

1. Local variables –
  • ·        Local variables are declared in methods, constructors or blocks.
  • ·        Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • ·        Access modifiers cannot be used for local variables.
  • ·        Local variables are visible only within the declared method, constructor or block.
  • ·        Local variables are implemented at stack level internally.
  • ·        There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the use.


Example –
public class Demo1 {
          public void age()
          {
                   int age=0;
                   age = age+27;
                   System.out.println("My age is : "+age);
          }
          public static void main(String[] args) {
                   Demo1 d = new Demo1();
                   d.age();
          }
}

Output –
My age is : 27


2. Instance variables –
  • ·        Instance variables are declared within a class, but not outside a method, constructor or any block.
  • ·        When a space is allocated for an object in the heap, a slot for each instance variable value is created.
  • ·        Instance variable are created when an object is created with the use of the keyword “new” and destroyed when the object is destroyed.
  • ·        Instance variable hold values that must be referenced by more than one method, constructor or block, or essential parts of an object. So, that the state may be present throughout the class.
  • ·        Instance variables can be declared in class level before or after use.
  • ·        Access modifiers can be given for Instance variables. The instance variables are visible for all methods, constructors and blocks in the class. Normally, it is recommended to make these variables private(access level), however visibility for subclasses can be given for these variables with the use of access modifiers.
  • ·        Instance variables have default values. For numbers the default value is 0, Booleans it is false and object reference it is null. Values can be assigned during the declaration or within the constructor.
  • ·        Instance variable can be accessed directly by calling the variable name inside the class. However within static methods and different classes (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.


Example –
public class Demo2 {
          // this instance variable is visible for any child class
          public String name;
          // age variable is visible in Demo2 class only
          private int age;
          // The name variable is assigned in the constructor
          public Demo2(String Dname)
          {
                   name=Dname;
          }
          // The age is assigned a value
          public void setAge(int Dage)
          {
                   age=Dage;
          }
          // This method displays the record
          public void display()
          {
                   System.out.println(name+" your age is : "+age);
          }       
          public static void main(String[] args) {
                   Demo2 d = new Demo2("Rakesh");
                   d.setAge(26);
                   d.display();
          }
}

Output –
Rakesh your age is : 26


3. class/static variables –
  • ·        Class variables also known as static variables are declared with the static keyword in a class. Variables are not allowed to declare inside a method (or) block (or) constructor.
  • ·        There would be only one copy of each class variable per class, regardless of how many objects created from it.
  • ·        Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.
  • ·        Static variables are stored in static memory. It is rare to use static variables other than declared final and are used as either public or private constants.

Example –
public class Demo3 {
          // salary variable is a private static variable
          private static double salary;
          //DEPARTMENT is a constant
          public static final String DEPARTMENT="IT";
          public static void main(String[] args) {
                   salary = 1000;
                   System.out.println(DEPARTMENT+"'s avaerage salary is : "+salary);
          }
}

Output –
IT's avaerage salary is : 1000.0


Local variable and its rules –
  • ·        Local variable can’t be accessed from another method, because its scope is restricted only within its method, and also we cannot guarantee variable creation, since that method may or may not be called. It leads to CE : “cannot find symbol”.
  • ·        Local variable should not be accessed without initialization. It leads to CE : “variable might not have been initialized”.
  • ·        Local variable must be accessed only after its creation because method execution is a sequential execution from top to bottom. If we access it before its creation statement, It leads to CE : “cannot find symbol”.



Final variables – The class or local variables that has final keyword in its definitions is called as final variable.


Final instance variable – If the value of a variable is valid from object to object, then such type of variables are called instance variables. For every object a separate copy of instance variable will be created. For the instance variable, we are not required to perform initialization explicitly, jvm will always provide default values.

Example –
public class Demo4 {
          int x;
          public static void main(String[] args) {
                   Demo4 d = new Demo4();
                   System.out.println("x : "+d.x);
          }
}

Output –
x : 0

Note – If an instance variable is declared as final then jvm doesn’t provide any default values, we must perform the initialization explicitly, though we use that variable or not.

Final static variable – If the value of a variable isn’t valid from object to object, then such type of variables should be declared with a static modifier. In the case of instance variables, for every object a separate copy will be created but in the case of static variables a single copy will be created at class level and shared by every object of that class. For the static variable, jvm will provide default values and aren’t required to perform initialization explicitly.

Example –
public class Demo4 {
          static int x;
          public static void main(String[] args) {
                   System.out.println("x : "+x);
          }
}

Note – If we are performing initialization anywhere else, we will get compilation error as can’t assign a value to final variable x.

public class Demo4 {
          final int x;
          {
                   x=10;
          }
          public static void main(String[] args) {
                   System.out.println("x : "+x);
          }
}

Note – If the static variable is declared as final then we must provide initialization explicitly, whether we are using or not, otherwise we will get compile time error.

public class Demo4 {
          static final int x;
          public static void main(String[] args) {
                   System.out.println("x : "+x);
          }
}


Final local variable – Sometimes to meet temporary requirements of the programmer we have to declare a variable inside a method, block or constructor then such types of variables are called local variables. For the local variables jvm does not provide any default values, we have to perform initialization explicitly before using that variable.

Example –
public class Demo4 {
          public static void main(String[] args) {
                   int x;
                   // CE: The local variable may not have been initialized
                   System.out.println("x : "+x);
          }
}


Formal parameters – The formal parameters of a method simply acts as a local variable, hence we can declare a formal parameter as final, but if we declare formal parameter as final, then within the method we can’t perform reassignment if done so we will get compile time error.

Example –
public class Demo4 {
          public static void m1(final int x,final int y)
          {
                   // x=100;   //CE
                   // y=200;  //CE
                   System.out.println(x+"::"+y);
          }
          public static void main(String[] args) {
                   m1(10,20);
          }
}

Output –
10::20


Static modifiers – Static modifiers are applicable for variables and methods. We can’t declare a top level class as static, but inner class can be declared as static. In the case of instance variables for every object a separate copy will be created, but in the case of static variables a single copy at class level and shared by every object of that class.

Example –
public class Demo4 {
          int x=10;
          static int y=20;
          public void m1()
          {
                   System.out.println(x);
                   System.out.println(y);
          }
          public void m2()
          {
                   System.out.println(y);
          }
          public static void main(String[] args) {
                   Demo4 d = new Demo4();
                   d.m1();
                   d.m2();
          }
}

Note – We can access static variables from both instance and static access directly.


Transient variable – The class level variable that has transient keyword in its definition is called as transient variable.

Example –
public class Test{
          static transient int x=10;
          transient int y=20;
          static void m1()
          {
                   //transient int r = 30; //CE
          }

Note – In local method variables we can access only final variables, other modifiers are not allowed, as it leads to CE. We declare variable as transient, to intimate jvm that we do not want to store variable value in a file in object serialization. As, local variable is not a part of object, declaring it as transient is illegal.


Volatile variable – The class level variable that has volatile keyword in its definition is called volatile variable. Local variable cannot be declared as volatile. It leads to CE : illegal start expression

public class Demo4 {
          static volatile int x=10;
          volatile int y=10;
          public static void main(String[] args) {
                   Demo4 d = new Demo4();
                   volatile int z=10; //CE: Illegal modifier for parameter z, only final is permitted           
          }
}

Note – We declare variable as volatile to inform jvm that we do not want to modify variable value concurrently by multiple threads. If we declare variable as volatile, multiple threads are allowed to change its value in sequence one after the other.


No comments:

Post a Comment