variables in java with source code example

Java has different set of variables. Which will represent the value is called as variable in java. Based on the type of value represented by a variable, that variable is divided into 2 types.
1.     Primitive Variable
2.     Reference Variable

Primitive Variable: Can be used to represent primitive values.
Ex: int x = 10;

Reference Variable: Can be used to refer objects.
Ex: Employee emp = new Employee();

Based on the purpose and position of declaring the variables are divided into 3 types.
1.     Instance Variable
2.     Static Variable
3.     Local Variable

1. Instance Variable:
  • If the value of the variable is varied from object to object such type of variables are called instance variable.
  • For every object a separate copy of instance variable will be created.
  • The scope of instance variable is exactly same as the scope of the objects. Because instance variables will be created at the time of objects creation and destroy at the time of object destruction.
  • Instance variables will be stored as the part of objects.
  • Instance variables should be declared inside the class directly. But outside of the method or block or constructors.
  • Instance variables cannot be accessed from static area directly we can access by using objects reference.
  • But from instance area we can access instance members directly.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package com.javatbrains.variable;

public class Test {
   int x = 10;
   public static void main(String[] args) {
     //Cannot make a static reference to the non-static field x
     //System.out.println(x);
     Test t = new Test();
     System.out.println(t.x);
   }
   public void m1(){
     System.out.println(x);
   }
}

  • Above program represents the non-static variable accessing in static method is possible or not.
  • First print statement will give you the compilation error. Because accessing non-static method inside the static method is not possible.
  • For instance variable it is not required to perform initialization explicitly, JVM will provide default values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.javatbrains.variable;

public class Test1 {
   String s;
   int i;
   boolean b;
   public static void main(String[] args) {
     Test1 t = new Test1();
     //Below line will print null
     System.out.println(t.s);
     //Below line will print 0
     System.out.println(t.i);
     //Below line will print false
     System.out.println(t.b);
  }
}

  • Instance variables also known as Object level variables (or) attributes.
 2. Static Variable:
  • If the value of a variable is not varied from object to object. Then it is not recommended to declare that variable at object level. We have to declare such type of variables at class level by using static modifier.
  • In the case of instance variables for every object a separate copy will be created. But in the case of static variable single copy will be created at class level and copy will be shared by all objects of that class.
  • Static variables will be created at the time of class loading and destroy will be done by class destroying.
  • Static variable accessing scope will be as the scope of the class.
Note: Now will see the steps of class execution,
Java Test
1.     start JVM
2.     Create main thread
3.     Locate Test.class
4.     Load Test.class //Static variables creation
5.     Execute main() method of Test class
6.     unload Test.class //Static variables destruction
7.     Destroy main thread
8.     shutdown JVM
  • Static variable should be declared with in the class directly, but outside of the any block or method or constructor with static modifier.
  • Static variables should be accessed by using class name or by using object reference, but recommended to use class name.
  • Within the same class even class name is not required to use class name also we can access directly.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.javatbrains.variable;

public class StaticTest {
   static int x = 10;
   public static void main(String[] args) {
     System.out.println(x);
   }
   //direct accessing static variable
   public void m1(){
     System.out.println(x);
   }
}

  • Static variables are created at the time of class loading. I.e. Program beginning. Hence we can access from both class and instance areas directly.
  • For the static variables it is not required to perform initialization explicitly, compulsory JVM will provide default values.
  • Static variables will be stored in method area. Static variables also known as “class level variables” or “fields”.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.javatbrains.variable;

public class StaticTest1 {
   int x = 10;
   static int y = 20;
   public static void main(String[] args) {
     StaticTest1 st1 = new StaticTest1();
     st1.x = 123;
     st1.y = 321;
     StaticTest1 st2 = new StaticTest1();
     System.out.println(st2.x+"......."+st2.y);
  }
}

  • If we perform any changes on instance variables these changes won’t be reflected for the remaining objects. Because of every object separate copy of instance will be there.
  • But if we have performed any of the changes for static variables these changes will be reflected for all objects, because we are maintaining a single copy.
3. Local Variable:
  • To meet temporary requirement of the program sometimes we have to create variables inside the method or block or constructor. Such types of variables are called as local variables.
  • Local variables also known as stack variables or Automatic variables or temporary variables.
  • Local variables will be stored inside a stack.
  • The local variables will be created while executing the block in which we have declared it and destroyed once the block completed. Hence the scope of local variable is exactly same as the block in which we declared it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.javatbrains.variable;

public class LocalTest {

   public static void main(String[] args) {
     int i = 0;
     for(int j=0;j<4;j++){
       i = i+j;
     }
      //j can not be resolved to a variable
      System.out.println(i+" "+j);
   }
}

  • In the above example j can not to be resolved to a variable compilation error will be there. To resolve for that, you have to define j variable outside the for loop as like below,
1
2
3
4
5
int j;
  
for(j=0;j<4;j++){
  i = i+j;
}
  • For the local variables JVM will not provide any default values, compulsory we should perform initialization before using the variable.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.javatbrains.variable;

public class LocalTest1 {

   public static void main(String[] args) {
          //initialize value
      int x;
      System.out.println(x);
  }
}

Note:
  • It is not recommended to perform initialization of local variables inside logical blocks there is no generate executions of these blocks at run-time.
  • It is highly recommended to perform initialization for the local variables at the time of declaration, at least with default values.
  • The only applicable modifier for local variable is final. If we used any other modifiers, we will get errors at compile time.

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example