Java Variables
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. Variable is a name of memory location. There are three types of variables
in java: local, instance and static.
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.
Variable: 10
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is called an instance variable because its value is instance-specific and is not shared
among instances.
import java.io.*;
public class IntVar
{
//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public IntVar()
{
this.name = "Deepak";
}
public static void main(String[] args)
{
// Object Creation
IntVar obj = new IntVar();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
}
Output:
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
class Student {
//static variable
static int age;
}
public class StaticVariableExample{
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.age = 24;
s2.age = 21;
Student.age = 23;
System.out.println("S1\'s age is: " + s1.age);
System.out.println("S2\'s age is: " + s2.age);
}
}
Output: