Java - Thing to know before proceed - Variable Tutorial
A variable is an area in memory (storage area) to hold data. A variable is assigned with its datatype.
There are three types of variables used in java: local variable, instance variable, and static variable.
- Local Variable
- A local variable is a variable that is declared inside the body of the method, constructors, or blocks.
- This local variable can only be used or accessed inside that method, constructors, or blocks. only.
- Access modifiers cannot be used here.
- This local variable cannot be used by a method other than the method in which the local variable is declared.
- a local variable cannot be defined with the "static" keyword.
public class LocalVariable {
public void variable1() {
int a = 7;//local variable
System.out.println("Local varible a is working inside varaible1() " + a);
}
public void variable2() {
//System.out.println("Local variable of variable1() will not work under variable2() : " + a);
System.out.println("Uncomment the below Line- It show error: cannot find symbol");
}
public static void main(String args[]) {
LocalVariable v = new LocalVariable();
v.variable1();
v.variable2();
}
}
- Instance Variable
- An instance variable is a variable that is declared inside the class, but outside the method, constructors, or blocks.
- This Instance variable can be used or accessed anywhere inside the class.
- Access modifiers can be used here.
- Instance variable has a default value, for int, it is 0, for Boolean it is false
- instance variable cannot be defined with the "static" keyword.
public class InstanceVariable {
int a = 7;//Instance variable
public void variable1() {
System.out.println("Instance varible a is working inside varaible1() " + a);
}
public static void main(String args[]) {
InstanceVariable v = new InstanceVariable();
v.variable1();
}
}
- Static variable
- A static variable is a variable that is declared as static is called a static variable.
- A static variable is a variable that is declared inside the class, but outside the method, constructors, or blocks
- 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.
public class StaticVariable {
static int a = 0;//Static variable
int b=0;//Non Static Variable
public void variable1() {
a=a+1;
b=b+1;
System.out.println("Static variable a after adding 1 =" + a);
System.out.println("Non Static b variable after adding 1 =" + b);
}
public static void main(String args[]) {
StaticVariable v1 = new StaticVariable();
v1.variable1();
StaticVariable v2 = new StaticVariable();
v2.variable1();
StaticVariable v3 = new StaticVariable();
v3.variable1();
}
}