Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 201 ยท Variables and Types

Variables

Learn how Java variables work - declaring them with a type, initializing and reassigning values, naming them well, definite assignment rules and a first look at scope.

A variable is a named place in memory that holds a value. Variables let a program remember things: a player's score, the price of an item, the name someone typed in. Instead of repeating a value everywhere, you store it once under a meaningful name and refer to it by that name.

Java is statically typed: every variable has a type that is fixed when you declare it, and the compiler makes sure the variable only ever holds values of that type. This lesson shows how to declare, initialize and change variables, the rules the compiler enforces (including one that catches a whole class of bugs before your program runs), and a first look at where a variable can be used.

Declaring and initializing a variable

To create a variable, write its type, then its name, then optionally = and a starting value:

Java
int quantity = 3;

This single line does two things:

  • Declaration: int quantity creates a variable named quantity that can hold an int (a whole number).
  • Initialization: = 3 gives it its first value.
Java Variables in a small receipt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each variable here has a different type, chosen to match the kind of value it holds. These are the types you'll use most at the start:

Type Holds Example
int whole numbers, about ยฑ2.1 billion int age = 36;
long very large whole numbers long population = 8_100_000_000L;
double decimal numbers double price = 24.99;
boolean true or false boolean isOpen = false;
char a single character, in single quotes char grade = 'A';
String text, in double quotes String city = "Lima";

The first five (and three more) are primitive types, built into the language and written in lowercase. String is a class, which is why it starts with a capital letter. The difference matters more than it seems, and Primitive Data Types explains it in depth.

Declaring several variables at once

You can declare several variables of the same type in one statement, separated by commas:

Java
int width = 1920, height = 1080;
double x, y, z;      // three variables, none initialized yet

Watch out for one trap: in int a, b = 5; only b is initialized. The = 5 belongs to b alone. For clarity, most Java style guides recommend one declaration per line.

Assigning new values

The assignment operator = stores a new value in an existing variable. You don't repeat the type, because the variable already exists:

Java Changing a variable's value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Java, = means "store", not "is equal to". That's why lives = lives + 5 makes sense: Java first evaluates the right side using the current value (2 + 5), then stores the result (7) back into lives. To compare two values, Java uses a double equals sign, ==, which you'll meet in Comparison and Logical Operators. Shortcuts like += and ++ are covered in Assignment and Increment Operators.

Assignment copies the value

When you assign one primitive variable to another, Java copies the value. The two variables are independent afterwards:

Java Copies are independent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The swap shows why: if you wrote left = right; right = left;, both would end up as 2, because the first line overwrites left before its old value is saved. (Object variables behave slightly differently, because they hold references. You'll see what that means in Classes and Objects.)

A variable's type never changes

Once declared, a variable keeps its type for its whole life. Assigning a value of an incompatible type is a compile error, and so is declaring the same name twice in the same method:

Java Type rules (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports three errors:

  • incompatible types: String cannot be converted to int on line 3.
  • incompatible types: possible lossy conversion from double to int on line 4. Storing 7.5 in an int would lose the .5, so Java refuses to do it silently. You can force it with a cast, (int) 7.5, as shown in Type Casting and Conversion.
  • variable score is already defined in method main() on line 5. To change a variable, assign to it; don't declare it again.

Going the other way is fine: double d = 7; works, because every int fits into a double without losing information.

This strictness is one of Java's biggest strengths. In a large program, you always know what kind of value a variable holds, and the compiler catches type mix-ups before a single user sees them.

Naming variables

Variable names follow the identifier rules from Java Keywords and Identifiers: letters, digits, _ and $, no leading digit, no keywords, case-sensitive. On top of the rules, follow the conventions every Java developer expects:

  • Use camelCase: start lowercase and capitalize each following word, as in unitPrice, maxRetries or firstName.
  • Choose names that say what the value means: elapsedSeconds instead of t, customerCount instead of n2.
  • Include units when they matter: timeoutMillis, distanceKm, priceInCents.
  • Name boolean variables like yes/no questions: isOpen, hasDiscount, canRetry.
  • Single letters are fine for short-lived values with an obvious meaning, like a loop counter i or coordinates x and y.

A good name often makes a comment unnecessary. Compare int d = 7; // days until delivery with int daysUntilDelivery = 7;.

Definite assignment: no uninitialized reads

You can declare a local variable (one declared inside a method) without giving it a value right away. But Java won't let you read it until it definitely has one. The compiler proves this before running anything, a rule called definite assignment:

Java Might not have been initialized (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports variable bonus might not have been initialized on line 9. You can see that points > 3 is true here, but the compiler reasons about every possible path, and on the path where the condition is false, bonus never gets a value. Add an else branch that assigns bonus = 0; and the program compiles, because now every path assigns it.

Many languages would quietly give bonus some leftover value, or a special "undefined" value, and let the bug surface later. Java turns it into a compile error with the exact line number.

Note: Definite assignment applies to local variables. Fields, which are variables declared directly in a class rather than inside a method, get automatic default values instead: 0 for numbers, false for boolean, and null for objects such as String. You'll work with fields in Fields and Instance Methods.

Declaring a variable without a value is useful exactly in situations like the one above, where the value depends on a decision. Otherwise, initialize variables right where you declare them, and declare them as close as possible to where they're first used.

A first look at scope

A variable exists only inside the block where it's declared, from the point of declaration to the block's closing brace }. That region is the variable's scope. Outside it, the name simply doesn't exist:

Java Block scope (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports cannot find symbol for discount on line 11. Delete that line and the program prints Inside: 85 and Outside: 85. Notice that the inner block can use total, because blocks nest: code inside a block sees the variables of all the blocks around it.

Two more scope rules worth knowing early:

  • Inside a method, you can't declare a variable with the same name as one that's still in scope. Declaring int total = 2; inside the inner block above would fail with variable total is already defined in method main(). This prevents a whole category of confusing bugs.
  • Once a block ends, its name is free again, so two separate blocks (for example, two loops one after the other) can each declare their own i.

You'll use these rules constantly with if statements and loops, whose bodies are blocks. Variable Scope covers scope in full, including method parameters, fields and shadowing.

Preview: var and final

Two keywords change how you declare variables, and each gets its own lesson:

  • var lets the compiler infer the type from the initial value: var quantity = 3; declares an int. The variable is still statically typed; you just don't write the type. See Local Variable Type Inference with var.
  • final makes a variable unchangeable after its first assignment: final double TAX_RATE = 0.2;. Assigning it again is a compile error. See Constants and final.
Java
var city = "Lima";          // city is a String
final int maxPlayers = 4;   // can never be reassigned
// maxPlayers = 5;          // error: cannot assign a value to final variable maxPlayers

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int a = 4; int b = a; a = 9; IO.println(b);

    int b = a; copies the value 4 into b. Changing a afterwards doesn't affect b, because primitive variables hold independent copies of their values.
  2. 2. Which line fails to compile?

    Storing a double in an int could lose information, so Java reports possible lossy conversion from double to int. An int fits safely into a double, so the first line is fine.
  3. 3. In int x, y = 10;, which variables are initialized?

    The = 10 belongs to y only. Reading x before assigning it gives variable x might not have been initialized.
  4. 4. Why does this fail? int bonus; if (vip) { bonus = 5; } IO.println(bonus);

    Definite assignment checks every path. If vip is false, nothing assigns bonus, so reading it is a compile error. An else branch that assigns it fixes the problem.
  5. 5. A variable is declared inside an if block. Where can you use it?

    A local variable's scope runs from its declaration to the closing brace of the block that contains it. After the block ends, the name no longer exists.

Summary

  • A variable is a named, typed storage location: int quantity = 3; declares and initializes it.
  • Assign a new value with = (no type): quantity = 5;. = means "store", and == compares.
  • Assigning one primitive variable to another copies the value; swapping needs a temporary variable.
  • A variable's type is fixed: incompatible values, lossy conversions and duplicate declarations are compile errors.
  • Use camelCase, meaningful names, units where helpful, and question-like boolean names.
  • Definite assignment: a local variable must certainly have a value before it's read. Fields get default values instead.
  • A variable's scope is the block where it's declared; inner blocks can see outer variables, but not the other way around.

Next: Primitive Data Types, where you'll explore all eight primitive types, their sizes and ranges, and how to write their values.