Pages

Types of Variables

What are the Types of Variables?

Below are Types of variables available in Java:
  1. Instance Variable
  2. Static (or) Class Variable
  3. Local Variable
Instance Variable:
  • It is a variable that will be declared outside of any method, constructor, or block in a class.
  • While declaring it should not use a static modifier.
  • The instance variable can be accessed by using an object.
Static Variable:
  • It is also known as Class Variable.
  • It is a variable that will be declared using a static modifier outside of any method, constructor, or block in a class.
  • A static variable can be directly accessed by using className (no need to create an object)
  • The default value of the Integer static variable is Zero and for String static variable is null.
Local Variable:
  • It is a variable that will be declared within a method, constructor, or block in a class.
  • Scope of a local variable will be defined to its block, method or constructor
  • final is the only modifier that can be applied to the local variable.
  • A local variable must be initialized before they can be used
Types of Variables
Types of Variables in Java
Demo on Types of Variables in Java:

public class TypesOfVariables {
    //Instance Variable
    int instanceVar;
    //Static Variable
    static String staticVar;
    static int j;

    public void method1() {
        final int a = 100; //local variable
        int b = 20;
        System.out.println(a);
    }

    public static void main(String args[]) {
        int a = 1001;//local variable 
       TypesOfVariables tov = new TypesOfVariables();
        System.out.println("Value of Instance variable=" + tov.instanceVar);
        System.out.println("Value of static variable=" + tov.staticVar);
        System.out.println("Value of static variable using class name =" + TypesOfVariables.staticVar);
        System.out.println("Value of static variable using class name =" + TypesOfVariables.j);
        tov.method1();
        System.out.println("Value of local variable=" + a);
    }
}
Output:
Types of Variables
Types of Variables

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.