Menu

Java Variables: Declaration, Assignment, and Scope Explained

How variables work in Java - declaring with a type, assigning values, naming rules, the var keyword, constants with final, and the scope rules that decide where a variable lives.

This page includes runnable editors - edit, run, and see output instantly.

What a Variable Is

A variable is a named box that holds a value. In Java every variable has a fixed type - decided when you declare it - and that type never changes. This is what makes Java statically typed: the compiler knows the type of every variable before the program runs, and it will refuse to compile code that puts the wrong kind of value in a box.

A declaration has three parts: the type, the name, and (usually) an initial value.

Read int age = 30; as "make an int called age and put 30 in it". The semicolon ends the statement, just like the comments page showed every statement does.

Declaring Now, Assigning Later

You can split a declaration from its first assignment. The type comes once, at the declaration; after that you assign with just the name and =:

One rule that trips up beginners: you must assign a value to a local variable before you read it. The compiler tracks this and rejects code that reads an uninitialized local:

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

This is a feature, not an annoyance - it catches a whole class of bugs before the program ever runs.

Naming Rules and Conventions

Java enforces a few hard rules, then layers conventions on top. The rules: a name may contain letters, digits, _, and $, but cannot start with a digit, cannot be a reserved keyword (like int or class), and is case-sensitive (age and Age are two different variables).

The conventions everyone follows:

  • Variables and methods use camelCase: firstName, totalScore.
  • Constants use UPPER_SNAKE_CASE: MAX_USERS.
  • Names should describe the value: count, not c; userEmail, not x.

Clear names are not decoration - they are how your future self reads the code. totalPrice = itemCount * pricePerItem is self-explanatory in a way t = c * p never will be.

Type Safety: The Box Keeps Its Type

Because the type is locked in at declaration, you cannot drop a value of the wrong type into a variable. This catches mistakes at compile time:

int age = 30;
age = "thirty";   // compile error: incompatible types - String cannot become int

Assigning across number types follows widening rules - a smaller type flows into a larger one automatically, but not the reverse. We will cover that fully on the data types and type casting pages; for now, just know the compiler is watching.

The var Keyword

Since Java 10 you can write var instead of the type and let the compiler infer it from the value on the right:

var is not dynamic typing - name is just as much a String as if you had written String name, and you still cannot later assign an int to it. It only saves typing. The catch: var needs an initializer to infer from, so var x; is illegal, and it works only for local variables - never for fields, method parameters, or return types. Use it where the type is obvious from the right-hand side; spell the type out when it adds clarity.

Constants with final

When a value should never change after it is set, mark it final. Any attempt to reassign it becomes a compile error:

final communicates intent ("this is a fixed value") and lets the compiler guard it for you. Reach for it whenever a value is conceptually a constant - rates, limits, configuration keys - so an accidental reassignment is caught instead of silently shipping a bug.

Variable Scope

A variable exists only inside the block - the { ... } - where it is declared, and it dies at the closing brace. This is its scope. A variable declared inside a for loop or if block is invisible outside it:

Both i and square belong to the loop and vanish when it ends; total is declared in the outer block, so it survives. The practical takeaway: declare each variable in the smallest block that needs it. Narrow scope means fewer names competing for your attention and fewer chances to misuse a value far from where it was set.

Next: Data Types

Every variable on this page started with a type - int, double, String, boolean. The next page breaks down Java's data types in detail: the eight primitives, how big each one is, the difference between primitives and objects, and which type to reach for when.

Frequently Asked Questions

How do you declare a variable in Java?

Write the type, then a name, then optionally assign a value: int age = 30;. The type (int) is fixed for the life of the variable; the name (age) is how you refer to it. You can split it into a declaration and a later assignment - int age; age = 30; - but you must assign a value before you read a local variable.

What is the var keyword in Java?

Since Java 10, var lets the compiler infer a local variable's type from the value you assign: var name = "Ada"; makes name a String. It is still statically typed - the type is fixed at compile time, not dynamic. var only works for local variables with an initializer, never for fields, parameters, or an uninitialized declaration.

How do you make a constant in Java?

Add the final keyword: final double PI = 3.14159;. Once assigned, a final variable cannot be reassigned - the compiler rejects any attempt. By convention constants are written in UPPER_SNAKE_CASE so they stand out from ordinary variables.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED