LearnFrenzy
Sign in Take a free test

Variables and Data Types · Lesson 4 of 42

Variables in Java

4 min read Updated Nov 7, 2026 Saurabh Samir

A variable is a named place in memory that holds a value. In Java every variable has a type that is fixed when you declare it – an int stays an int for its whole life. That strictness feels slow at first, but it is the reason the compiler can catch so many mistakes before your program ever runs.

In this lesson

  • Declaring, initialising and updating variables
  • Naming rules and Java conventions
  • Local type inference with var
  • Constants with final and variable scope

Declare, initialise, use

public class Main {
    public static void main(String[] args) {
        int age;              // declaration: type + name
        age = 21;             // initialisation
        double cgpa = 8.4;    // both in one line
        String name = "Ananya";
        boolean placed = false;

        age = age + 1;        // update
        System.out.println(name + " is " + age + ", CGPA " + cgpa + ", placed: " + placed);
    }
}

Output

Ananya is 22, CGPA 8.4, placed: false

Each variable: a type, a name, a value

  • age22int
  • cgpa8.4double
  • name"Ananya"String (a reference)
  • placedfalseboolean

Common mistake: using a local variable before assigning it

int total; System.out.println(total); does not compile: variable total might not have been initialized. Local variables get no default value – you must assign one first. (Fields inside a class do get defaults, as you'll see in chapter 8.)

Naming rules and conventions

The compiler enforces the rules; your team enforces the conventions.

  • Names may contain letters, digits, _ and $, but cannot start with a digit.
  • They are case-sensitive and cannot be keywords like class, int or new.
KindConventionExample
Variables and methodscamelCasetotalMarks, calculateTax()
Classes and interfacesPascalCaseStudentRecord
ConstantsUPPER_SNAKE_CASEMAX_ATTEMPTS
Packagesall lowercase, reversed domaincom.learnfrenzy.app

Choose names that explain meaning: daysUntilExam beats d. Reviewers in real projects will ask you to rename vague variables.

var: let the compiler infer the type

Since Java 10, local variables can be declared with var. The type is still fixed – the compiler simply works it out from the value on the right.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        var city = "Hyderabad";            // String
        var count = 42;                     // int
        var price = 199.99;                 // double
        var skills = new ArrayList<String>(); // ArrayList<String>
        skills.add("Java");
        System.out.println(city + " " + count + " " + price + " " + skills);
    }
}

Output

Hyderabad 42 199.99 [Java]
  • var works only for local variables with an initial value – not for fields, method parameters or return types.
  • var x = 5; x = "five"; is still an error: x is an int.
  • Use it when the type is obvious from the right-hand side; write the type out when it helps readability.

Constants with final

public class Main {
    static final double GST_RATE = 0.18;   // class constant

    public static void main(String[] args) {
        final int maxLogins = 3;            // local constant
        double price = 1000;
        System.out.println("With GST: " + price * (1 + GST_RATE));
        System.out.println("Max logins: " + maxLogins);
        // maxLogins = 5;   → error: cannot assign a value to final variable maxLogins
    }
}

Output

With GST: 1180.0
Max logins: 3

Scope: where a variable lives

A variable exists only inside the block { } where it is declared. Once the block ends, the name is gone.

public class Main {
    public static void main(String[] args) {
        int total = 0;                    // visible in the whole main method
        for (int i = 1; i <= 3; i++) {    // i lives only inside the loop
            int square = i * i;           // square too
            total += square;
        }
        System.out.println("Total: " + total);
        // System.out.println(i);   → error: cannot find symbol
    }
}

Output

Total: 14

Nested scopes

  1. Classfields such as GST_RATE – visible to all methods
  2. Methodtotal – visible from its declaration to the end of main
  3. Block (loop / if)i and square – gone when the block ends

Java also forbids declaring a second local variable with the same name inside a nested block – a safety rule that prevents confusing "shadowing" bugs.

Practice

Try it yourself

  1. Store a product name, price and quantity, then print the total bill.

    Show solution
    public class Main {
        public static void main(String[] args) {
            String product = "Notebook";
            double price = 45.5;
            int quantity = 4;
            System.out.println(product + " total: " + price * quantity);
        }
    }

    Output

    Notebook total: 182.0
  2. Swap two int variables using a temporary variable.

    Show solution
    public class Main {
        public static void main(String[] args) {
            int a = 5, b = 9;
            int temp = a;
            a = b;
            b = temp;
            System.out.println(a + " " + b);
        }
    }

    Output

    9 5

Quick check

Can you write var total; without a value?

No. var needs an initial value so the compiler can infer the type.

What does final do on a variable?

It can be assigned only once; later assignments are compile errors.

Do local variables get a default value?

No. They must be assigned before use. Only fields get defaults (0, false, null).

Summary

  • Variables have a fixed type: type name = value;
  • Use camelCase for variables, PascalCase for classes, UPPER_CASE for constants.
  • var infers local types; final makes constants; scope ends at the closing brace.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links