Variables In Java

Variables in java like a glass in which you can store water, milk, etc. In technical terms, a variable is a memory or name that is used to store any data type value. If you declare a variable you must write data type before the variable name.

In Java, there are various types of data types like String, int, char, float, double, etc. If you assign the value to the variable then you can change the value at any time.

Syntax:

type variableName = value;

Declaration

int a;
String s;

Initialization

a=45;
s="Study4Geeks"

Declaration & Initialization

variables-in-java

Example:

public class S4G {
	public static void main(String args[]){
		int num=45;
		System.out.println("Number is "+num);
    }
}

output:

Number is 45

In, above example, int is a data type and 45 is the value that assigns to the variable num.

Types Of Variables

There are three types of variables:

  • Instance
  • Static
  • Local
Types-Of-Variables

Instance Variable

An instance variable is always declared outside of the method body or constructor and within the class. Instance variables are global variables that mean you can access anywhere within the class.

In this, memory is allocated when the object is created and it will release the memory when the object will be destroyed. It always stores in heap memory and here has the default value.

Example:

public class S4G {
	String name="Study4Geeks"; // Instance variable
	void myMethod() {
		System.out.println(name);
	}
	public static void main(String args[]){
		new S4G().myMethod();
    }
}

output:

Study4Geeks

Static Variable

A static variable is similar to the Instance variable. It also declared outside of the method body or constructor and within the class but declares with the static keyword. Memory is allocated when you run the program.

Example:

public class S4G {
	static String name="Study4Geeks"; // static variable
	void myMethod() {
		System.out.println(name);
	}
	public static void main(String args[]){
		new S4G().myMethod();
    }
}

output:

Study4Geeks

Local Variable

A local variable is a variable in which always declare within the method body or constructor. The scope of the locale variable should be within the block. It can not be accessed outside of the block.

Memory is allocated when a method or constructor is executed and it will destroy when going outside of the block. It always stores in stack memory and here does not have any default value that means if you write int num; then num can not be directly used. See the example for better clarity.

Example:

public class S4G {
	S4G(){
		int num=78; // local variable
		int num2;
	//	int total=num+num2; this line will give the error.
		System.out.println(num);
	}
	public static void main(String args[]){
		new S4G();
    }
}
output: 78
Do you know?
Variables In Java This article is contribute by Study4Geeks If you want share your knowledge on Study4Geeks then go to login section.