Java Variables


Variables are one of the most important concepts in Java programming. They act as containers that store data values which can be used and changed while the program is running. Understanding how variables work is essential for writing meaningful and efficient Java code.

What is a Variable in Java?

A variable is a named memory location used to store a value. Each variable in Java has a data type that defines the kind of value it can hold, such as numbers, characters, or text.

For example:

int age = 25;

Here,

  • int defines the data type (integer).

  • age is the variable name.

  • 25 is the value assigned to it.

You can think of a variable like a labeled box that stores information. You can open it, check what’s inside, and replace the value when needed.

Rules for Naming Variables in Java

When naming variables, there are certain rules and conventions you must follow:

  1. Variable names are case-sensitive (Age and age are different).

  2. They must start with a letter, an underscore _, or a dollar sign $.

  3. Variable names cannot start with numbers.

  4. Java keywords such as int, class, or static cannot be used as variable names.

  5. Always use meaningful names to make code easier to understand.

Examples:

int studentAge = 20;  // valid and meaningful
int a = 20;           // valid but unclear

Types of Variables in Java

Based on where they are declared and how they behave, variables in Java are classified into three main types.

1. Local Variables

Local variables are declared inside a method, constructor, or block. They are only accessible within that specific block and must be initialized before use.

Example:

public class Example {
    public static void main(String[] args) {
        int number = 10; // local variable
        System.out.println(number);
    }
}

If you try to use the variable outside the method, it will cause an error.

2. Instance Variables

Instance variables are declared inside a class but outside any method or block. They are associated with objects, meaning each object has its own copy.

Example:

public class Student {
    int rollNumber; // instance variable
    String name;    // instance variable
}

Each object created from the Student class can store its own rollNumber and name.

3. Static Variables

Static variables are shared among all objects of a class. They are declared using the static keyword and belong to the class rather than any specific object.

Example:

public class Student {
    static String schoolName = "Green Valley School"; // static variable
}

If one object changes the value of schoolName, it changes for all objects in that class.

Declaring and Initializing Variables

There are two main ways to declare and initialize variables in Java:

Separate Declaration and Initialization

int marks;
marks = 90;

Combined Declaration and Initialization

int marks = 90;

You can also declare multiple variables of the same type in one line:

int a = 5, b = 10, c = 15;

Variable Scope in Java

The scope of a variable determines where it can be accessed in a program.

  • Local variables are visible only within the method or block where they are declared.

  • Instance variables are accessible by all non-static methods of the class.

  • Static variables can be accessed using the class name.

Example:

public class Demo {
    static int count = 0; // static variable
    int number;           // instance variable

    void setNumber(int num) {
        int temp = num; // local variable
        number = temp;
    }
}

Default Values of Variables

Local variables must be initialized before use. However, instance and static variables get default values automatically depending on their data type.

Data Type Default Value
byte, short, int, long 0
float, double 0.0
char '\u0000'
boolean false
Object (like String) null

Example:

public class DefaultValues {
    int num;          // 0
    boolean flag;     // false
    String text;      // null
}

Variable Types Based on Data Type

Each variable in Java must have a data type that defines what kind of data it can store.

Examples:

int age = 22;            // integer type
double price = 199.99;   // decimal value
char grade = 'A';        // single character
boolean isPassed = true; // true or false
String name = "Aisha";   // text

Every data type has its own memory size and range.

Using Variables in Expressions

You can perform operations using variables in Java.
Example:

int a = 10;
int b = 20;
int sum = a + b;
System.out.println(sum); // Output: 30

Here, the values stored in a and b are used to calculate sum.

Final Variables in Java

If you want to make a variable constant (its value should never change), use the final keyword.

Example:

final double PI = 3.14159;

If you try to change the value of PI, Java will show a compilation error.

Variable Shadowing

When a local variable has the same name as an instance variable, the local variable temporarily “hides” or shadows the instance variable.

Example:

public class Example {
    int number = 5; // instance variable

    void display() {
        int number = 10; // local variable shadows instance variable
        System.out.println(number); // prints 10
    }
}

To access the instance variable, use this.number.

Summary of the Tutorial

Variables are the backbone of every Java program. They store and manipulate data while the program executes. Java provides three main types of variables — local, instance, and static — each serving a unique purpose. Understanding scope, initialization, and naming conventions helps you write clean and reliable code. By mastering variables, you lay a strong foundation for learning data types, operators, and expressions in Java.


Practice Questions

  1. Write a Java program that declares three integer variables, assigns values to them, and then prints their sum, difference, and product on separate lines.

  2. Create a Java program that stores a student’s name in a String variable and marks in an int variable, then prints both details together in a single output statement.

  3. Write a Java program to demonstrate the use of local, instance, and static variables in one class, and show how each type of variable behaves differently.

  4. Develop a Java program that declares a variable for the radius of a circle, assigns a value, and calculates the area using the formula area = 3.14 * radius * radius. Display the result clearly.

  5. Write a Java program that stores a person’s name, age, and height in separate variables and prints a small self-introduction message using those variables.

  6. Create a program that demonstrates two ways of initializing variables: first by declaring and initializing them separately, and second by doing both in one line.

  7. Write a Java program that includes a static variable count and increments it every time a new object of the class is created. Print the total count after creating multiple objects.

  8. Create a program that uses a final variable named PI to represent the constant value 3.14159. Try to modify its value later in the program and observe the compilation error.

  9. Write a Java program that declares variables of all basic data types such as int, double, char, boolean, and String, assigns them appropriate values, and prints all values on the screen.

  10. Develop a Java program that shows how a local variable can shadow an instance variable when both have the same name. Print both values using the this keyword to highlight the difference.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top