Table of contents
Introduction
Variables are like a cup that holds something. Variables are used to store the information and hold the data in the memory. Variables should be declared with the data type. The data type defines what type of data can variable hold, and how much memory is allocated for the variable. Variable declared as
public int num1;
public is the access modifier, int is the data type, and num1 is the variable name. Variables can be declared and initialized at the same time.
public int num1=0;
Types of Variables
There are three types of variables.
Local
Local variables are those that can be declared in the method, constructor, block, and the other methods do not know that variables exist. Local variables can only use the final keyword all the other keywords like access modifiers even static is not applicable. Local variables are implemented at the stack level internally. There is no default value for local variables, so local variables should be declared and should initial value before use. These variables are created and destroyed with the method, constructor, or block.
Example
public class Book {
public static void main(String[] args) {
// TODO Auto-generated method
final float pi=3.14; // local varibale
System.out.println("pi is a local variable") ;
}
}
Instance
Instance variables are declared inside the class but outside the method, constructor, and block. Access modifiers can be given for instance variables. Instance variables have the default value for numbers: 0 for objects: null and for the boolean: false. Instance variables can be called by the object name .instanceVariableName. These variables are created or destroyed with the objects.
Example
public class Book {
public int instanceVariable;
public static void main(String[] args) {
// TODO Auto-generated method
Book obj = new Book();
System.out.println(obj.instanceVariable);
}
Output
0
The output will be zero because the Instance variables have default values.
Static
Static variables load with the class in the memory and it happens once. To access these variables we don't need the object we directly access these variables using the class name.variableName. Static variables have only one copy. Static variables are loaded before any objects or any static methods.
Example
public class Book {
public static String staticVariable=;
public static void main(String[] args) {
// TODO Auto-generated method
System.out.println(Book.staticVariable);
}
}
Output
null