variable in java

In JAVA, Variables can be Termly defined as to reserve memory space to store the values. These variables can easily be initialized at the time of declaration or later on whenever needed on the type of variable.

Types Of Variables in JAVA:

There are 3 types of variables in JAVA:

1. Local Variable
2. Instance variable
3. Class Variable/Static variable.

Local variable:

  • These are also called as a stack variable. Because they exist in computer stack memory.
  • It is mandatory to initialize the local variable. Otherwise, you will get run time error from the compiler.
  • These can be defined inside the method, constructor or also inside block.
  • The scope or lifeline of the local variable destroyed with the end of method completed, this means that local variables cannot be used outside the method or the class.

Instance variable:

  • An instance variable in java is also known as member variable or field.
  • These are associated with object creation. As the object gets created instance variable also gets created.
  • These live on heap memory. In case, if you don’t initialize instance variable with the initial value these get default value at run time implicitly. Here default value initialed to int is 0.

Class Variable/Static Variable:

  • These are loaded and initialized when class is loaded in JVM.
  • There exists only one copy of the class variable.
  • They live on heap memory. and if variables are not initialized to some default value is assigned to them implicitly.

Examples Of Variables In JAVA: With Small program

Correct Program Code With Initialization of Local Variable:

Simply just assign the initial value to local variables in the same program. The change in output will reflect automatically the importance of this change. It’s Because of only the local variables required to initialize with some value.Class/Static and instance variable implicitly assign the null /0/ false value to these particular variable.

Class/Static and instance variable implicitly assign the null /0/ false value to this particular variable.

public class Main{
	public static int staticvariable;
	int instancevariable=10;
	public void printValue(){
		int localvariable = 10;
		System.out.println("the value of static variable \t"+staticvariable);
		System.out.println("the value of instance variable\t"+instancevariable);
		System.out.println("the value of local variable \t"+localvariable);
	public static void main(String args[]){
		Main object=new Main();

the value of static variable     0                                                                                             
the value of instance variable   10                                                                                            
the value of local variable      10 

Post Referred Website

Comments are closed.