BhauAutomation

Java Variables

In Java, variables are used to store data values. Each variable has a data type, a name, and stores a specific kind of value. Variables are fundamental building blocks of any Java program, allowing you to store, modify, and retrieve data during program execution.

📘 Topic: Core Java / Basics
Read time: 7 min
📊 Level: Beginner
📦 Focus: Data Storage
📖 Overview

What are Variables in Java?

A variable in Java is a name assigned to a memory location that stores data. It allows a program to refer to values dynamically rather than using raw literals. Variables make code readable, reusable, and easier to maintain.

📝 Example:
int age = 25;
String name = "John";
double salary = 45000.50;
boolean isActive = true;

System.out.println("Employee Name: " + name + ", Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Active Status: " + isActive);
🔧 Types

Types of Variables in Java

📍 Local Variables Declared inside a method, constructor, or block. Accessible only within that scope. Must be initialized before use.
📦 Instance Variables Declared inside a class but outside any method. Each object has its own copy. Default values are provided.
⚡ Static Variables Declared using the static keyword. Shared by all objects of the class. Also known as class variables.

📊 Variable Types Comparison

Type Scope Default Value Keyword
Local Variable Inside method/block No default (must initialize) None
Instance Variable Inside class, outside method Yes (0, null, false) None
Static Variable Class level Yes (0, null, false) static
📝 Complete Example:
public class VariablesExample {
    // Instance Variable
    int instanceVar = 100;
    
    // Static Variable
    static int staticVar = 200;
    
    void show() {
        // Local Variable
        int localVar = 50;
        System.out.println("Local Variable: " + localVar);
    }

    public static void main(String[] args) {
        VariablesExample obj1 = new VariablesExample();
        VariablesExample obj2 = new VariablesExample();
        
        obj1.show();
        
        // Accessing instance variable (object-specific)
        System.out.println("Instance Var (obj1): " + obj1.instanceVar);
        System.out.println("Instance Var (obj2): " + obj2.instanceVar);
        
        // Changing instance variable of obj1 only
        obj1.instanceVar = 300;
        System.out.println("After change - obj1: " + obj1.instanceVar);
        System.out.println("After change - obj2: " + obj2.instanceVar);
        
        // Accessing static variable (shared)
        System.out.println("Static Var: " + staticVar);
        System.out.println("Static Var via obj1: " + obj1.staticVar);
        System.out.println("Static Var via obj2: " + obj2.staticVar);
        
        // Changing static variable affects all objects
        staticVar = 500;
        System.out.println("Static Var after change: " + staticVar);
    }
}
📏 Naming Rules

Rules for Declaring Variables in Java

Variable names must start with a letter, underscore (_), or dollar sign ($)

Cannot contain spaces or special symbols (@, #, %, etc.)

Must be declared before use

Java is case-sensitive (age and Age are different)

Cannot use Java keywords as variable names (int, class, static, etc.)

Variable names should be meaningful and descriptive

📝 Valid & Invalid Variable Names:
// Valid variable names
int age = 25;
int _count = 5;
int $value = 10;
int studentName = "Amit";
int totalMarks = 480;

// Invalid variable names (will cause compilation error)
// int 1stNumber = 10;     // Cannot start with digit
// int my-name = "John";   // Cannot contain hyphen
// int class = 5;          // Cannot use keyword
// int @value = 20;        // Cannot contain special char
📝 Declaration

Variable Declaration and Initialization

In Java, you must declare a variable before using it. You can declare multiple variables of the same type in a single line.

📝 Declaration Syntax:
// Single variable declaration
dataType variableName;

// Declaration with initialization
dataType variableName = value;

// Multiple variable declarations
dataType var1, var2, var3;

// Multiple declarations with initialization
dataType var1 = value1, var2 = value2, var3 = value3;

// Examples
int count;
int number = 100;
int a, b, c;
int x = 10, y = 20, z = 30;

String name = "BhauAutomation";
double price = 99.99;
boolean isAvailable = true;
🎯 Scope

Variable Scope in Java

The scope of a variable defines where it can be accessed within a program. Java has several levels of scope:

📝 Scope Examples:
public class ScopeExample {
    static int classVar = 100;  // Class/Static scope
    
    int instanceVar = 200;       // Instance scope
    
    void method() {
        int localVar = 300;      // Local scope (method level)
        
        if (true) {
            int blockVar = 400;  // Block scope (inside if block)
            System.out.println(blockVar); // Accessible
        }
        // System.out.println(blockVar); // Error! Not accessible outside block
    }
}
🏆 Best Practices

Best Practices for Java Variables

Use meaningful and descriptive variable names (camelCase)

Keep variable scope as small as possible

Always initialize variables before using them

Use constants (static final) for values that don't change

Avoid using single-letter variable names except for loop counters

Group related variable declarations together

📝 Good Naming Examples:
// Good variable names
String studentName = "Amit Kumar";
int totalMarks = 485;
double averagePercentage = 97.5;
boolean isEligible = true;

// Loop counter (acceptable single letter)
for (int i = 0; i < 10; i++) { }

// Constants (UPPER_SNAKE_CASE)
static final int MAX_STUDENTS = 100;
static final String COMPANY_NAME = "BhauAutomation";