BCA / B.Tech 6 min read

What is a variable?

Meaning of Variable (Java)

Variable in Java: A variable is a storage area used to store data. This data can be changed during the execution of the program.

Types of Variables

Variables are divided into two main types based on their scope (Limit):

Global Variable

A global variable is a variable that is declared inside a class but outside any specific method. It can be accessed throughout the entire class.

Example:

In the code below, count is a global variable that can be accessed in all methods.


public class Example {
    static int count = 10; // Global variable
    public static void displayCount() {
        System.out.println("Count is: " + count); // Can access count
    }
    public static void updateCount() {
        count = 20; // Can change the value of the global variable
    }
    public static void main(String[] args) {
        displayCount(); // output: Count is: 10
        updateCount();
        displayCount(); // output: Count is: 20
    }
}

        

Here, count is accessed in both displayCount() and updateCount() methods because it is a global variable.

Local Variable

A local variable is a variable that is declared inside a method or block. It can only be used within that method or block and is not valid outside of it.

Example:

In the code below, num is a local variable that can only be accessed inside the showNumber() method.


public class Example {
    public static void showNumber() {
        int num = 5; // Local variable
        System.out.println("Number is: " + num); // output: Number is: 5
    }
    public static void main(String[] args) {
        showNumber();
        // System.out.println(num); // This will give an error because num is a local variable and cannot be accessed in main
    }
}

        

Here, num can only be accessed within the showNumber() method, and trying to access it in the main() method will result in an error.