Variables in Java

What is a Variable in Java?

Variable is a data container that stores the data. Every variable has a data type that tells which types of data it can hold. Basically variable is a memory location of the data.

Types of variables:

There are 3 types of variables.

  1. Local Variables
  2. Instance Variables
  3. Static Variables

1. Local Variables

Local Variables are a variable that are declared inside the body of a method.

2. Instance Variables

A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static. It is called instance variable because its value is instance specific and is not shared among instances.

3. Static Variables

A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

Let’s see 2 examples to clear the type of the variable. It will be more clear when we will discuss the OOP concepts.

Example 1:

public class Main {
    static String bandName="XYZ"; //static variable
        public static void main(String[] args) {
            Human human=new Human();
            human.canSing("Rahim");
            human.canPlayGuitar("Karim");
            System.out.println("Both are from "+bandName+" band");
            System.out.println("Both live in "+human.location);
        }
    
    }
    class Human{
        String location="Mirpur"; //instance variable
         public void canSing(String name){
             int age=20; //local variable
             System.out.println(name+" can sing song. His age is "+age);
        }
    public void canPlayGuitar(String name){
        int age=22; //local variable
        System.out.println(name+" can play guitar. His age is "+age);
    }
}
Output:
Rahim can sing song. His age is 20
Karim can play guitar. His age is 22
Both are from XYZ band
Both live in Mirpur

Example 2:

public class Main {
    static String bandName="XYZ"; //static variable
    public static void main(String[] args) {
        int a=10;
        int b=20;
        int res=a+b;
        System.out.println("Result is "+res);
    }

}
Output: Result is 30
about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *