Skip to main content

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

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...