</>
Skip to content
Java lessons (7/47)

Java — Variables

What is a variable?

A variable is a named container that stores a value. You declare one, give it a type and a name, and assign a value:

int age = 25;
String name = "Ada";
double price = 9.99;
boolean isStudent = true;

Every variable in Java has a type — the kind of data it holds. This type is fixed at compile time. You can't store text in an int or a number in a String without explicit conversion.

Declaration and initialization

You can declare a variable first and assign later:

int score;
score = 95;
System.out.println(score);  // 95

Or combine them:

int score = 95;

Using a variable before assigning a value gives a compile error:

int score;
System.out.println(score);  // error: variable score might not have been initialized

Java catches this at compile time — it prevents you from using garbage values that some languages allow through.

Type matters

int whole = 42;
double decimal = 42.0;
String text = "42";

All three represent "42" but in different types. You can't mix them freely:

int result = whole + decimal;    // warning — double assigned to int
String mix = text + whole;       // works — "4242" (concatenation)
String math = text + decimal;    // "42.0" (not math!)

The last two show Java's string concatenation rule: when one operand is a String, + joins text rather than adding numbers. This trips up every beginner at least once.

Naming rules

Java enforces strict naming rules:

int age = 25;        // valid
int _count = 0;      // valid (starts with underscore)
int $total = 100;    // valid (starts with $)
int 2ndPlace = 3;    // ERROR: can't start with a digit
int my-name = 5;     // ERROR: dash means minus operator
int class = "x";     // ERROR: class is a reserved word

Beyond the rules, follow conventions:

  • camelCase for variables and methods: studentCount, getAge()
  • PascalCase for classes: StudentRecord
  • UPPER_SNAKE_CASE for constants: MAX_USERS
  • Descriptive names: totalPrice beats tp
// Bad
int x = 25;
String s = "Ada";
boolean f = true;

// Good
int studentAge = 25;
String studentName = "Ada";
boolean isEnrolled = true;

Final variables — constants

The final keyword locks a variable so it can't be reassigned:

final double PI = 3.14159;
final String greeting = "Hello";

PI = 3.0;  // ERROR: cannot assign a value to final variable PI

Use final for values that shouldn't change — mathematical constants, configuration values, anything that represents a fixed fact.

Java convention: constants use UPPER_SNAKE_CASE.

final int MAX_LOGIN_ATTEMPTS = 3;
final double TAX_RATE = 0.08;
final String DATABASE_URL = "jdbc:mysql://localhost/mydb";

Variable scope

A variable's scope is the region of code where it's accessible:

public static void main(String[] args) {
    int outer = 10;          // scope: entire main method

    if (outer > 5) {
        int inner = 20;      // scope: only inside this if block
        System.out.println(outer);  // works
        System.out.println(inner);  // works
    }

    System.out.println(outer);  // works
    System.out.println(inner);  // ERROR: inner is out of scope
}

Variables declared inside a block {} exist only within that block. When the block ends, the variable vanishes. This prevents accidental reuse of temporary values.

Instance vs local variables

There are two kinds of variables you'll encounter:

public class Counter {
    int count = 0;          // instance variable — belongs to the object

    public void increment() {
        count++;            // accessible here
    }

    public void reset() {
        int temp = 0;       // local variable — exists only inside reset
        count = temp;       // works, but temp is gone after this method ends
    }
}

Instance variables live as long as the object does. Local variables live only during the method call. This distinction becomes crucial once you start working with classes.

Default values

Instance variables get default values when you don't assign one:

TypeDefault
int0
double0.0
booleanfalse
String (and all objects)null

Local variables have no defaults — you must initialize them explicitly before use.

Type inference with var

Java 10 introduced var for local variables when the type is obvious:

var name = "Ada";        // Java infers String
var age = 25;            // Java infers int
var items = new ArrayList<String>();  // Java infers ArrayList<String>

The type is still fixed — name is always a String. var just saves you from typing it when it's clear from context. Don't use var when the type isn't obvious:

var result = calculateSomething();  // bad — what type is result?

Mini Practice

  1. Declare variables for a book: title, author, pages, price, and whether it's available
  2. Print each variable with a descriptive label using println
  3. Create a final constant for the speed of light and use it in a calculation
  4. Try reassigning a final variable — read the compile error
  5. Use var to declare three variables with different types — verify their types with your IDE

Next: the data types Java provides →

Related Topics

Frequently Asked Questions about Variables

What is Variables in Java?

Variables is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in Java?

Variables is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.