No announcement
 

Variables

In the previous chapter, we learned about data types. A data type represents the value of a particular type, like an integer value or char value. A variable is used to store values.

There are three types of variables: Local Variable, Instance Variable, Static/Class Variable.

  1. Local Variable
    A local variable is declared in block, constructor or method. The scope of local variable is within the particular block, constructor or method. Access modifiers cannot be used for local variables.
  2. Instance Variable
    An Instance variable is declared in a class outside block, constructor or method and are non-static.
  3. Static/Class Variable
    Static variables are declared similar to instance variable, but using static keyword.

Example:

VariablesDemo.java

package com.codingnous.tutorial;

public class VariablesDemo {

	// Instance variable
	float omega = 0.5671432f;

	// Static/class variable
	static double pi = 3.141592653589793;

	public static void main(String[] args) {
		// Class object for accessing instance variable
		VariablesDemo ve = new VariablesDemo();

		// Local variable
		int sum = 24000;

		// Lets print value of all the variables
		System.out.println("Local variable value: " + sum);
		System.out.println("Instance variable value: " + ve.omega);
		System.out.println("Static/class variable value: " + pi);
	}

}

Output
Local variable value: 24000 Instance variable value: 0.5671432 Static/class variable value: 3.141592653589793