Java Variables (with examples)

You use a variable when you need to store a value and refer to it elsewhere in the code.

In the example below, the two variables are highlighted.

String username = enterUsername();
String password = enterPassword();
if (login(username, password)) {
    System.out.println("Welcome " + username + "!");
} else {
    System.out.println("Invalid username/password");


To use a variable you must first declare it. When you declare a variable you specify

This code

int maxLength = 100;


From here on, let maxLength represent an integer (int). Initialize it with value 100.

If you try to use a variable that hasn't been declared (e.g. if you misspell a variable name) the compiler will complain and say something like "Identifier amxLength not found."

Multiple variables

You can declare multiple variables at once with the same type:

int i, j, l;
boolean y = true, n = false;

Most style guides however, recommend against this.

Variable names…


You must choose a type for each variable. There's no such thing as an untyped variable in Java. The type must be respected throughout the code. This code would give you a compiler error:

int i;
i = true; // Can't store a boolean value in an integer variable

Types come in two shapes:

See Java: Primitives vs Objects and References for further details.

Here are some examples, including all 8 primitive types:

byte b;      // integers, −128–127
short s;     // integers, ±32 thousand
int i;       // integers, ±2 billion
long l;      // integers, ±9 quintillion
float f;     // reals, ~6 digits precision
double d;    // reals, ~15 digits precision
boolean z;   // true or false
char c;      // character

Person p;    // References to a Person objects
Car v;       // References to a Car objects

Which numeric type to choose?

For integers, use int unless you have reasons to use something else. Common exceptions: Unix timestamps and database IDs typically require long.

For reals, use double unless you have reasons to use something else. Common exceptions: Use BigDecimal if you want to avoid rounding errors, for instance when dealing with currency.


If you need to store, say 10 integers (but don't want to create 10 variables) you can use an array, or list. See Java Arrays (with examples) and Java: Array vs ArrayList (and other Lists).

For more information on the Java type system, see separate article: Types in Java.


If you for instance declare a variable in one method, you can't access that same variable in another method. Each variable has a scope; a section of code where it's accessible.

The scope is delimited by { and }.

    void method() {
scope of d
        double d;
        if (…) {
scope of i
            int i;
} else {
scope of s
            String s;
        i = 17; // Error: i is out of scope


Be the first to comment!