×
DocsConsole

DocsConsole

Java Variables Tutorial

By | | Updated : 2019-06-23 | Viewed : 211 times

Java Variables Tutorial

Java Variable Introduction:

In Java Programming, we should use the Program for manipulating the different data types. Here data types mean int, long, string and so on. To manipulate data programmatically, we should store data in some memory location. So, Variable will do the same. Variables are containers to hold the different data types as in memory. But here Variable does not exactly contain the data. The variable contains the data location means it refers to the memory location.So, we can quickly access the data by using the variable for manipulation.

For a better explanation of how the variable works in the Java language, Please consider the below-given example

Java Variable example code
String instanceVariable = "Variable Value";

In program execution, Java will create a String type of data as memory. After the creation of memory, Java will assign the memory location to the instanceVariable variable. So, we can easily access the data by using the instanceVariable variable. Please see the below-given diagram for the same.

How Java variable will work

Types of Java Variables

Based on the scope of variables, the variables have been categorized as in three ways. Those are categorized as

    Variables Types:

  • 1. Instance Variables

  • 2. Static Variables

  • 3. Local Variables

1. Instance Variables

A variable defined in the class and outside of the method/block/constructor, is called as instance variable. The instance variable is not static variable.Its time for defining the Instance variable. Let’s define a variable in the Java class as given below.

Example for Java Instance Variable
package com.docsconsole.tutorials.Java12;

public class InstanceVariableExample {

	String instanceVariable = "Instance Variable Value";

	public static void main(String[] args) {
		InstanceVariableExample instVarExmpObj  = new InstanceVariableExample();
		System.out.println("Inside of main method" + instVarExmpObj.instanceVariable);
	}

}

Here, the instanceVariable variable has defined outside of the main method as an instance variable. The Instance variable will be created in the object area. So, this variable will be created while object creation and destroyed while object destroys. Hence, the scope of the instance variable is equal to the Object/Instance scope. The language variable is an example of an instance variable. Here we have used object reference variable and “.” dot operator for accessing the instance variable.

When will we go for Instance Variable?

If need separate copy of data for each object, then the instance variable will be the right option. Please look into below given example for more explanation.

Another Example for Java Instance Variable
package com.docsconsole.tutorials.Java12;

import java.lang.String;

public class InstanceVariableExample {

	public String instanceVariable = "instanceVariable";

	public static void main(String[] args) {

		InstanceVariableExample instVarExmpObj = new InstanceVariableExample();
		instVarExmpObj.instanceVariable = "instanceVariable modified";// Variable value has been changed with instVarExmpObj object
		System.out.println(instVarExmpObj.instanceVariable);
		InstanceVariableExample instVarExmpObj1 = new InstanceVariableExample();
		System.out.println(instVarExmpObj1.instanceVariable);// Variable value will be shown as initial value
	}
}

If you see the above code snippet, we have modified the variable instanceVariable by using the object called instVarExmpObj. But when we accessing the same value with object instVarExmpObj1, the variable value was not changed. Note: JVM assigns default values into the Instance variables. So explicitly not needed for assigning the values.

Instance Variable can be preceded with different types of keywords as shown below.

Example for Java Instance Variable
package com.docsconsole.tutorials.Java12;

import java.lang.String;

public class InstanceVariableExample {

	public String instanceVariable1 = "instanceVariable1";
	String instanceVariable3 = "instanceVariable3";
	protected String instanceVariable2 = "instanceVariable2";
	private String instanceVariable4 = "instanceVariable4";
	transient String instanceVariable5 = "instanceVariable5";
	volatile String instanceVariable6 = "instanceVariable6";

	public static void main(String[] args) {

		InstanceVariableExample instanceVariableExample = new InstanceVariableExample();

		System.out.println(instanceVariableExample.instanceVariable1);
		System.out.println(instanceVariableExample.instanceVariable2);
		System.out.println(instanceVariableExample.instanceVariable3);
		System.out.println(instanceVariableExample.instanceVariable4);
		System.out.println(instanceVariableExample.instanceVariable5);
		System.out.println(instanceVariableExample.instanceVariable6);
	}
}

2.Static Variables

A variable defined with the static keyword in the class and outside of the method/block/constructor is called a static variable.

Example for Java Static Variable
package com.docsconsole.tutorials.Java12;

public class InstanceVariableExample {
	static String staticVariable = "Static Variable Value";

	public static void main(String[] args) {
		InstanceVariableExample StaticVarExmpObj = new InstanceVariableExample();
		System.out.println(InstanceVariableExample.staticVariable);
	}

}

In the above-given example, we have defended a static variable “staticVariable”. The static variable will be created while class loading and destroyed while class unloading. Unlike the instance variable, the static variable will be created only once. The static variable is also known as a class variable. Because the static variable will be created only once irrespective of objects. Static variables will be created only one copy and which is sharable for all the objects.

Note: The recommendable approach for Accessing the static variable is Class Name. We can access the variable by using object reference also which is not recommendable. Please see the below-given example.

Recommendable Approach For Accessing Static Variable
package com.docsconsole.tutorials.Java12;

public class StaticVariableExample {
	static String staticVariable = "Static Variable Value";

	public static void main(String[] args) {
		StaticVariableExample StaticVarExmpObj = new StaticVariableExample();
		System.out.println("Inside of main method" + StaticVariableExample.staticVariable);	// recommended
		System.out.println("Inside of main method" + StaticVarExmpObj.staticVariable); 		// not recommended
	}

}

The static variable will be created only once and will be shareable for all the objects.

Please go through the below-given example for verifying the static variable is shareable or not.

The static variable is shareable
package com.docsconsole.tutorials.Java12;

public class StaticVariableExample {
	static String staticVariable = "Static Variable Value";

	public static void main(String[] args) {
		
		StaticVariableExample StaticVarExmpObj = new StaticVariableExample();
		System.out.println("Variable Value @Before modification " + StaticVarExmpObj.staticVariable);
		StaticVarExmpObj.staticVariable = "Static Variable Value is modified"; // Value has been changed
		StaticVariableExample StaticVarExmpObj1 = new StaticVariableExample();
		System.out.println("Variable Value @After modification " + StaticVarExmpObj.staticVariable);
		System.out.println("Variable Value @After modification " + StaticVarExmpObj1.staticVariable);
		
	}

}

Here we have created the two objects. We modified the static variable by using StaticVarExmpObj object.If you see the output of the static variable at the end of the program, the changed values will be printed for both objects.

A static variable can be accessed from the instance area and static area. But instance variable cannot be accessed from the static area. Please see the below-given example.

A static variable can be accessed directly from the instance area and static area whereas instance variable can be accessed directly only from the instance area. But it is not accessible from static area. Directly access means not required to use the object reference or Class name for accessing. Please see the below-given example.

Instance variable cannot be accessed directly from the static area
package com.docsconsole.tutorials.Java12;

public class VariableExample {
	
	static String staticVariable 	= "Static Variable Value";
	String instanceVariable 	= "Instance Variable Value";
	
	// static block
	static {
		System.out.println("static variable inside of static block ->" + staticVariable);
		//System.out.println("instance variable inside of static block" + instanceVariable); // will give compile error.
	}
	
	// instance block
	{
		System.out.println("static variable inside of instance block ->" + staticVariable);
		System.out.println("instance variable inside of instance block ->" + instanceVariable);
	}

	public static void main(String[] args) {

		VariableExample varExmpObj  = new VariableExample();
		System.out.println("static variable inside of main method ->" + staticVariable);
		//System.out.println("instance variable inside of main method ->" + instanceVariable); // will give compile error.

		varExmpObj.instanceMethod();

	}

	// instance method
	public void instanceMethod() {

		System.out.println("static variable inside of instanceMethod method ->" + staticVariable);
		System.out.println("instance variable inside of instanceMethod method ->" + instanceVariable);

	}
}

If you observe, we have accessed all variables without Class Name and Object References. Execute the above program, it will print the output in the console successfully. Now, uncomment commented coded lines in the static area then you will get the error. This means the instance variable cannot be accessed from a static block/method directly. But static variables can be accessed from the static area and nonstatic area also.

3.Local Variables

A variable defined inside of the method/block/constructor of class is called a local variable.

Local Variable Example
package com.docsconsole.tutorials.Java12;

public class LocalVariableExample {

	public static void main(String[] args) {
		LocalVariableExample locVarExmp = new LocalVariableExample();
		int addtionValue = locVarExmp.addition(5, 5);
		System.out.println("The sum value is"+ addtionValue);
	}

	public int addition(int a, int b) {
		int sum = 0;
		sum = a + b;
		return sum;
	}

}

In the above given example, we have created two local variables. One is addtionValue in the main method and second one is sum in addition method. So, Local variable scopes is equal to scope of method/block/constructor. The Local Variable will be created at the time method/block/constructor execution and will be destroyed once method execution is completed. These variable values will be created in the stack.

JVM will not assign any default value into the Local Variable. Its required to assign value manually. If it is not assigned any value before using Local Variable then we will get compile time error. Please observe the below given you can understand the scenario.

Local variable should be assigned before using it
package com.docsconsole.tutorials.Java12;

public class LocalVariableExample {

	public static void main(String[] args) {

		LocalVariableExample locVarExmp = new LocalVariableExample();
		int addtionValue = locVarExmp.addition(5, 5);
		System.out.println("The sum value is" + addtionValue);

	}

	public int addition(int a, int b) {
		int sum;
		// System.out.println(sum); // remove and and check the result
		sum = a + b;
		return sum;
	}

}

If you execute the above program with removing of commented code, then it will give some compile error.

Leave A Reply