Variables in Java

Variables in Java

Variables in Java are containers for storing data values. Unlike some languages, Java is statically typed, so you must declare the type of each variable.

Declaring Variables

Basic Syntax

Syntax
dataType variableName = value;

Examples

VariableDeclaration.java
public class VariableDeclaration {
    public static void main(String[] args) {
        // Different ways to declare variables
        
        // Declaration with initialization
        int age = 25;
        String name = "John Doe";
        double salary = 50000.50;
        boolean isStudent = true;
        
        // Declaration without initialization
        int score;
        score = 100;
        
        // Multiple declarations
        int x = 10, y = 20, z = 30;
        
        // Final variable (constant)
        final double PI = 3.14159;
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
    }
}

Variable Naming Rules

  1. Must start with a letter, underscore (_), or dollar sign ($)
  2. Can contain letters, digits, underscores, and dollar signs
  3. Cannot start with a digit
  4. Cannot use Java keywords
  5. Case sensitive (name and Name are different)
NamingExamples.java
// Valid variable names
int myVariable;
int _variable;
int $variable;
int variable123;

// Invalid variable names
// int 123variable;  // starts with digit
// int class;        // keyword
// int my-variable;  // hyphen not allowed

Variable Scope

Variables have different scopes based on where they’re declared:

ScopeExample.java
public class ScopeExample {
    // Instance variable (class-level)
    static int globalVar = 10;
    
    public static void main(String[] args) {
        // Local variable in main method
        int localVar = 20;
        
        System.out.println(globalVar);  // Accessible
        System.out.println(localVar);   // Accessible
        
        if (true) {
            int blockVar = 30;          // Block scope
            System.out.println(blockVar);
            System.out.println(localVar); // Accessible
        }
        
        // System.out.println(blockVar);  // Error: not accessible here
    }
}

Learn about Java data types to understand what types of data you can store in variables.

Last updated on