Java Variables

A variable is a named container that stores a value in a program. Think of it like a labeled box — the label is the variable name, and whatever is inside the box is the variable's value. Variables allow programs to store, retrieve, and change data during execution.

Declaring a Variable

In Java, a variable must be declared before it can be used. A declaration specifies the data type and the name of the variable.

dataType variableName;

Example:

int age;         // declared but not yet assigned a value
String name;     // declared but not yet assigned

Assigning a Value

A value is assigned to a variable using the assignment operator =.

age = 20;
name = "Alice";

Declaring and Assigning in One Line

It is common (and preferred) to declare a variable and assign its value in a single statement:

int age = 20;
String name = "Alice";
double price = 9.99;
boolean isActive = true;

Types of Variables in Java

Java has three types of variables based on where they are declared:

1. Local Variables

A local variable is declared inside a method or a block of code. It only exists while that method or block is running. Local variables must be initialized (given a value) before they are used — Java does not give them a default value automatically.

public class LocalVariableDemo {
    public static void main(String[] args) {
        int score = 95;   // local variable
        System.out.println("Score: " + score);
    }
}

2. Instance Variables

An instance variable is declared inside a class but outside any method. Each object (instance) of the class gets its own copy of these variables. They are initialized automatically with default values if not assigned explicitly.

public class Student {
    String name;    // instance variable
    int age;        // instance variable

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Bob";
        s1.age = 18;
        System.out.println(s1.name + " is " + s1.age + " years old.");
    }
}

3. Static Variables (Class Variables)

A static variable is declared with the static keyword inside a class but outside any method. Unlike instance variables, there is only one copy of a static variable shared among all objects of the class.

public class Counter {
    static int count = 0;   // static variable – shared by all objects

    public static void main(String[] args) {
        count++;
        count++;
        System.out.println("Count: " + count);   // Output: Count: 2
    }
}

Variable Naming Rules

When naming variables in Java, the following rules must be followed:

  • The name must begin with a letter, underscore _, or dollar sign $.
  • The name cannot start with a digit.
  • Spaces are not allowed in variable names.
  • Java reserved keywords cannot be used as variable names.
  • Variable names are case-sensitive: total and Total are different variables.

Variable Naming Convention (Best Practices)

Java developers follow the camelCase convention for variable names — the first word is in lowercase, and each subsequent word starts with an uppercase letter:

int studentAge = 21;
double accountBalance = 1500.50;
boolean isEmailVerified = false;
String fullName = "John Doe";

Constants – Final Variables

When a variable's value should never change after it is assigned, it is declared with the final keyword. Such variables are called constants. By convention, constant names are written in ALL_CAPS with underscores separating words.

final double PI = 3.14159;
final int MAX_STUDENTS = 50;

System.out.println("PI = " + PI);
// PI = 3.14159; // This would cause a compile-time error

Multiple Variable Declaration

Multiple variables of the same type can be declared in a single statement:

int x = 5, y = 10, z = 15;
System.out.println(x + y + z);   // Output: 30

Default Values of Variables

Instance variables and static variables get default values if not assigned. Local variables do not get defaults — they must be initialized before use.

Data TypeDefault Value
int, short, byte, long0
float, double0.0
char'\u0000' (null character)
booleanfalse
String (and all objects)null

Complete Example

public class VariableDemo {

    // Instance variables
    String city = "New York";
    int population = 8000000;

    // Static variable
    static String country = "USA";

    public static void main(String[] args) {

        // Local variables
        int temperature = 72;
        double humidity = 65.5;
        boolean isSunny = true;

        System.out.println("City: " + new VariableDemo().city);
        System.out.println("Country: " + country);
        System.out.println("Temperature: " + temperature + "°F");
        System.out.println("Humidity: " + humidity + "%");
        System.out.println("Sunny: " + isSunny);
    }
}

Output:

City: New York
Country: USA
Temperature: 72°F
Humidity: 65.5%
Sunny: true

Summary

  • A variable stores data that can be used and changed during program execution.
  • Variables must be declared with a data type before use.
  • There are three kinds: local variables, instance variables, and static (class) variables.
  • Use the final keyword to create constants whose values cannot change.
  • Follow camelCase naming convention for variables and ALL_CAPS for constants.
  • Local variables must be initialized before use — they have no default value.

Leave a Comment

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