Java Basics

Java Variables

Learn about variables in Java — declaration, initialization, types of variables, scope, and naming rules with practical examples.

What is a Variable?

A variable is a named container that stores a value in memory. Think of it as a labeled box where you can put, retrieve, and change data.

java
int age = 25;           // 'age' is a variable storing the value 25
String name = "Arjun";  // 'name' is a variable storing the text "Arjun"

Declaring Variables

In Java, you must declare a variable before using it. Declaration tells the compiler:

  1. The type of data the variable will hold
  2. The name of the variable
java
// Syntax: dataType variableName;
int count;           // Declaration
count = 10;          // Initialization (assigning a value)

// Or combine both:
int count = 10;      // Declaration + Initialization

Multiple Declarations

java
// Declare multiple variables of the same type
int x, y, z;
int a = 1, b = 2, c = 3;

// Each type needs its own declaration
String firstName = "Arjun";
int age = 22;

Types of Variables

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

1. Local Variables

  • Declared inside a method, constructor, or block
  • Created when the method is called, destroyed when it exits
  • Must be initialized before use (no default value)
java
public class LocalExample {
    public static void main(String[] args) {
        int score = 95;       // Local variable
        String grade = "A+";  // Local variable
        System.out.println(grade + ": " + score);
    }
    // score and grade do NOT exist outside main()
}

2. Instance Variables (Non-Static Fields)

  • Declared inside a class but outside any method
  • Each object gets its own copy
  • Have default values (0, 0.0, false, null)
java
public class Student {
    // Instance variables
    String name;           // default: null
    int age;               // default: 0
    boolean isEnrolled;    // default: false

    public void display() {
        System.out.println(name + ", Age: " + age);
    }
}
java
// Each object has its own copy
Student s1 = new Student();
s1.name = "Arjun";
s1.age = 22;

Student s2 = new Student();
s2.name = "Priya";
s2.age = 20;

3. Static Variables (Class Variables)

  • Declared with the static keyword
  • Shared across all objects of the class (one copy per class)
  • Can be accessed using the class name
java
public class Student {
    static int totalStudents = 0;  // Shared by all
    String name;                    // Per object

    public Student(String name) {
        this.name = name;
        totalStudents++;  // Incremented for every new student
    }
}
java
Student s1 = new Student("Arjun");
Student s2 = new Student("Priya");
System.out.println(Student.totalStudents); // Output: 2

Comparison Table

FeatureLocalInstanceStatic
Declared inMethod/BlockClass (no static)Class (with static)
ScopeWithin methodWithin objectAcross all objects
Default valueNone (must initialize)Yes (0, null, false)Yes (0, null, false)
MemoryStackHeap (with object)Method area
AccessDirectlyThrough objectThrough class name

Variable Naming Rules

Must Follow (Compiler Rules)

  • Can contain letters, digits, underscores (_), and dollar signs ($)
  • Must begin with a letter, _, or $ (not a digit)
  • Cannot be a Java keyword (int, class, public, etc.)
  • Case-sensitive (ageAge)

Should Follow (Conventions)

  • Use camelCase: firstName, totalAmount, isActive
  • Use meaningful names: studentAge instead of sa
  • Constants in UPPER_SNAKE_CASE: MAX_VALUE, PI
java
// ✓ Valid variable names
int age = 25;
String firstName = "Arjun";
double _salary = 50000.0;
int $count = 10;
int totalStudentCount = 150;

// ✗ Invalid variable names
// int 2ndPlace = 2;       // Cannot start with digit
// int my-var = 10;        // Hyphens not allowed
// int class = 5;          // 'class' is a keyword

Constants (final variables)

Use the final keyword to create variables whose values cannot be changed after initialization:

java
final double PI = 3.14159;
final int MAX_USERS = 1000;
final String COMPANY = "BigXStar";

// PI = 3.14;  // ✗ Compile error: cannot assign a value to final variable

Type Inference with var (Java 10+)

From Java 10 onwards, you can use var to let the compiler infer the type:

java
var name = "Arjun";    // Compiler infers String
var age = 25;           // Compiler infers int
var price = 99.99;      // Compiler infers double
var active = true;      // Compiler infers boolean

// var x;               // ✗ Error: cannot infer without initialization

Note: var can only be used for local variables. It cannot be used for instance/static variables, method parameters, or return types.

Variable Scope

Scope determines where a variable is accessible:

java
public class ScopeDemo {
    static int classLevel = 100;  // Accessible everywhere in this class

    public static void main(String[] args) {
        int methodLevel = 50;     // Accessible only in main()

        if (true) {
            int blockLevel = 25;  // Accessible only in this if-block
            System.out.println(classLevel);  // ✓
            System.out.println(methodLevel); // ✓
            System.out.println(blockLevel);  // ✓
        }

        System.out.println(classLevel);  // ✓
        System.out.println(methodLevel); // ✓
        // System.out.println(blockLevel); // ✗ Error: not accessible here
    }
}

Practical Example

java
public class BankAccount {
    // Instance variables
    String accountHolder;
    double balance;

    // Static variable
    static int totalAccounts = 0;
    static final double MIN_BALANCE = 500.0; // Constant

    public BankAccount(String holder, double initialDeposit) {
        this.accountHolder = holder;
        this.balance = initialDeposit;
        totalAccounts++;
    }

    public void deposit(double amount) {
        // Local variable
        double newBalance = balance + amount;
        balance = newBalance;
        System.out.printf("Deposited ₹%.2f. New balance: ₹%.2f%n", amount, balance);
    }

    public void displayInfo() {
        System.out.printf("Account: %s | Balance: ₹%.2f%n", accountHolder, balance);
    }

    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("Arjun", 10000);
        BankAccount acc2 = new BankAccount("Priya", 25000);

        acc1.deposit(5000);
        acc2.deposit(3000);

        acc1.displayInfo();
        acc2.displayInfo();

        System.out.println("Total accounts: " + BankAccount.totalAccounts);
        System.out.println("Minimum balance: ₹" + BankAccount.MIN_BALANCE);
    }
}

Output:

Deposited ₹5000.00. New balance: ₹15000.00
Deposited ₹3000.00. New balance: ₹28000.00
Account: Arjun | Balance: ₹15000.00
Account: Priya | Balance: ₹28000.00
Total accounts: 2
Minimum balance: ₹500.0

Summary

  • Variables are named containers that store data in memory
  • Java has three types: Local, Instance, and Static variables
  • Variables must be declared with a type before use
  • Use camelCase for variables and UPPER_SNAKE_CASE for constants
  • Use final to create constants that cannot change
  • Java 10+ supports var for local variable type inference
  • Variable scope is determined by where it is declared (block, method, or class)