exampracticeonline.com
Variables

Java Variables

Variables are the identifier of the memory location, which used to save data temporarily for later use in the program.

Each java variable has a specific type, which determines its memory and the data that can be stored in that variable.

During execution of a program, values can be stored in a variable, and the stored value can be changed.

In Java programming, it is necessary to declare the variable before being used.

How to declare variables?

We can declare variables in java like this:

int age = 18;

In above example we have used below terms:

int => datatype
age => variable name
18 => variable value

What is datatype?

Type of data that can be stored in this variable.

What is variable name?

Name given to the variable that is used for variable access.

What is variable value?

It is the initial value stored in the variable.

Data types of variables in Java

There are three types of variables in java

  1. local variable 
  2. instance variable 
  3. static variable 

1. Local Variables

Local Variables are declared inside the body of a method or inside a block or inside a constructor is called local variable.

  • The scope of these variables exists only within the method or block in which the variable is declared. We can't access these variable outside that method or block.
  • Local variables created when method or block execute and these variables get destroyed after completion of method or block.
  • Initialisation of Local variable is mandatory. If we don't declare local variable and try to get access then we get compile time exception with message "The local variable may not have been initialized".

Example: 

package com.test;

public class LocalVariable {
	public static void main(String[] args) {
		LocalVariable lv = new LocalVariable();
		lv.getAge();	
	}
	private int getAge() {
		int age = 18;
		System.out.println("age: "+age);
		return age;
	}
}

Output: 

age: 18

2. Instance Variables

Instance variables are defined without the static keyword .They are declared in a class outside any method, constructor or block.. They are Object specific and are known as instance variables.

  • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
  • Initialisation of Instance Variable is not Mandatory. Its default value depends on data type. like if we have int instance variable then it's value would be it's default value 0.
  • Instance variables are created per object.If we have two object then two instance variables will create.
  • Instance variable can be accessed only by creating objects.
  • Instance variables can't be use in static block without object. It will throw compile time exception "Cannot make a static reference to the non-static field ".

Example: 

package com.test;

public class InstanceVariable {
	
	int age1 = 18; // instance variable 
	int age2; // instance variable default value would be 0 as per int data type
	
	public static void main(String[] args) {
		InstanceVariable iv = new InstanceVariable();
	        iv.getAge();
	        // System.out.println("age1: "+age1); // Compile time exception Cannot make a static reference to the non-static field age1
	}
	private void getAge() {
                System.out.println("age1: "+age1);
                System.out.println("age2: "+age2);
	}

}

Output:

age1: 18
age2: 0

3. Static Variables

Static variables are defined with the static keyword .They are declared in a class outside any method, constructor or block.It cannot be local. 

  • Static variables are also known as Class variables. Because Static variables get memory while class is loading.
  • Static variables are declared in a class, these variables are created when an class is loading.
  • Initialisation of Static variable is not mandatory. It's default value depends on data type. like if we have int Static variable then it's value would be it's default value 0.
  • Static variable have only one copy per class irrespective of how many objects we have created.If we have two object but we have only Static variable and share among all the instances of the class.
  • Static variables can be accessed by creating objects or by using class name.
  • Static variables can be use in static or non static block.
  • Memory allocation for static variable happens only once when the class is loaded in the memory.

Example: 

package com.test;

public class StaticVariable {

    static int age1 = 18; // static variable 
    static int age2; // static variable default value would be 0 as per int data type
    
    public static void main(String[] args) {
    	StaticVariable iv = new StaticVariable();
        iv.getAge();
        System.out.println("age1 in static block: "+age1); // no compile time exception
    }
    private void getAge() {
        System.out.println("age1 in non static block: "+age1);
        System.out.println("age1 with class name: "+StaticVariable.age1); //access with class name
        System.out.println("age2: "+age2);
    }

}

Output:

age1 in non static block: 18
age1 with class name: 18
age2: 0
age1 in static block: 18

Example for types of variables in Java

package com.test;

public class VariablesExample {

	int age=18; //instance variable  
	static int data=1000; //static variable  
	
	void method(){  
		int index=100; //local variable
		System.out.println("value of local variable :"+index);
	}  
	public static void main(String[] args) {
		VariablesExample obj = new VariablesExample();
		
		// Instance variable can't access in static block directly. They can use by object reference
		// System.out.println("value of instance variable :"+age); // Compile time exception Cannot make a static reference to the non-static field age
		System.out.println("value of instance variable :"+obj.age);
		
		// static variable can be access in static or non-static block directly without creating object
		System.out.println("value of static variable without object :"+data);
		
		// static variable can be access in static or non-static block directly with class name also 
		System.out.println("value of static variable with class name:"+VariablesExample.data);
		
		// local variables can't access outside method
		// System.out.println("value of local variable :"+index); // Compile time exception index cannot be resolved to a variable
		
		// local variables can be access within the method 
		obj.method();
	}

}

Output: 

value of instance variable :18
value of static variable without object :1000
value of static variable with class name:1000
value of local variable :100