Different Types of Variables in Java: Based on our usage there are three different types of variables. They are
1.Local Variables
2.Instance Variables or global variables.
3.Static Variable.
1.Local variable : A variable declared within a method is called as local variable. Local variable life span is active until it is within the method.
Local Variable Example in Java
1 2 3 4 5 6 7 8 9 10 11 |
public class localVariableExample{ public void method1() { int age = 10; System.out.println(“The age is ” + age); } public static void main(String args[]) { localVariableExample lv= new localVariableExample(); lv.method1(); } } |
OUTPUT :
java local variable example
In the above program age is an local variable, which scope lies within method1. If we try to access the age without accessing the method. Java compiler will throw an syntactical error. Because we need to create an object of that class and access the methods which contains variables.
2.Global variables or instance variables : A variable declared within a class but outside the method, constructor, block is called as Global variables.
Global Variable Example in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class globalVariableExample{ String name ; int age; public void method1() { int age = 20; System.out.println(“The age after age declaration ” + age); } public static void main(String args[]) { globalVariableExample lv= new globalVariableExample(); System.out.println(“The age before intializing ” + age); lv.method1(); } } |
OUTPUT :
java global variable example
The value is 0 because the default value of integer is zero. Since we did not declare the variable with any value we are getting zero. However after declaration we are getting 20.
3.Static Variable : A static variable is declared with the keyword as static and its within class level however outside a method, constructor, block.
We can access the variables without creating an object. Using classname with variablename we can access the variables.
Static Variable Example in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class classA{ static int age; static String name; public static void display() { System.out.println(“The value of String is:”+name); } } public class staticvariableExam{ public static void main(String args[]) { System.out.println(“the value of age in classA is:”+classA.age); classA.display(); } } |
OUTPUT :