Java Variables & Constants Tutorial

In this Java tutorial we learn about variables and constants and how they store temporary data while the program runs.

We discuss how to declare or initialize variables and constants, how to use them and change variable values.

Finally, we look at operands in Java, lvalues and rvalues.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a variable

A variable is a temporary data container that stores a value in memory while the application is running.

As an example, let’s consider a calculator program.

When we perform an addition for example, the app stores the result in a variable that we can use to perform any additional calculations we need.

Example:
3 + 5 = x

x * 8 = y

In the example above, the letters ‘x’ and ‘y’ store the resulting data from the arithmetic.

Variables are used all over our apps to store runtime data. When the app is closed, or the variable is no longer used by the program, the value in memory is removed.

Variable types in Java

There are three types of variables in java:

1. A local variable is defined within a function, or method. It’s local to that function’s scope.

2. An instance variable is defined within a class, but outside of a class method. It’s local to the object (an instance of a class).

3. A static variable is a non-local variable that can be shared among all instances of a class (objects).

In this tutorial, to keep things simple, we will cover local variables inside the ‘main()’ function.

We won’t cover functions in this tutorial. For the moment you don’t have to worry about the ‘main’ function or the class it’s in.

How to declare a variable in Java

To declare a variable, we specify its data type, followed by a name and a semicolon to terminate the statement.

Syntax:
 data_type variable_name;

The data type simply tells the compiler what type of value will be stored in the variable.

We cover all the data types available in Java in the lesson on Data TypesOpens up in a new page .

Example:
public class Program {

    public static void main(String[] args) {

        // variable declaration
        int num;
    }
}

In the example above, we declare a variable with the name ‘num’ that can store integers (whole numbers).

Our variable doesn’t have any data inside it yet, we just reserved space in memory for it.

How to assign a value to a variable in Java

To assign data to a variable, we specify the name of the variable, then the assignment operator = , followed by a value that matches the data type.

Syntax:
// declaration
data_type variable_name;

// assignment
variable_name = value;

We only use the data type when we’re declaring or initializing the variable, not when assigning or changing a value.

Example:
public class Program {

    public static void main(String[] args) {

        // variable declaration
        int num;

        // value assignment
        num = 5;
    }
}

In the example above, we assign the value of 5 to the variable ‘num’.

The statement reads: variable 'num' has value of 5

How to initialize a variable with a value in Java

We will often know the value we want to assign to the variable beforehand, so we can use initialization syntax to declare a variable and assign a value to it at the same time.

To do this we simply combine the declaration and assignment together.

Syntax:
 data_type variable_name = value;
Example:
public class Program {

    public static void main(String[] args) {

        // variable initialization
        int num = 5;
    }
}

In the example above, we initialize a new variable with the value of 5.

How to declare/initialize multiple variables inline in Java

We can declare or initialize multiple variables of the same type at the same time in Java.

To do this we separate each variable name with a comma. If we initialize them, we assign the value after each variable name.

Syntax:
// declaration
data_type var_name, var_name, ...;

// initialization
data_type var_name = value, var_name = value, ...;

Note that the elipses (…) only indicate that more variables can be declared/initialized this way. It’s not included in the syntax.

Example:
public class Program {

    public static void main(String[] args) {

        // inline initialization
        int x = 1, y = 2, z = 3;

        System.out.println("x: " + x);
        System.out.println("y: " + y);
        System.out.println("z: " + z);
    }
}

In the example above, we initialize three integer variables with separate values inline.

Output:
x: 1
y: 2
z: 3

How to use a variable in Java

To use a variable, we simply specify its name wherever we need to use it in our code.

Example:
public class Program {

    public static void main(String[] args) {

        // variable initialization
        int num1 = 5;
        int num2 = 3;
        int result = num1 + num2;

        // use variable
        System.out.println("5 + 3 = " + result );
    }
}

In the example above, we add the values of the ‘num1’ and ‘num2’ variables together, and store them in another variable called ‘result’.

Then we use ‘result’ in the println() function to print it to the console.

Output:
 5 + 3 = 8

How to change a variable’s value in Java

Variables in Java are mutable, which means we can change their values while the program is running (at runtime).

To change the value of a variable, we simply assign it a new one.

Example:
public class Program {

    public static void main(String[] args) {

        // variable initialization
        int num1 = 5;
        int num2 = 3;
        int result = num1 + num2;

        // use variable
        System.out.println("5 + 3 = " + result );

        // mutate variable
        result = num1 * num2;

        System.out.println("5 * 3 = " + result );

        // mutate variable
        result = -1;

        System.out.println("New value: " + result );
    }
}

In the example above, we mutate the ‘result’ variable’s value in the second arithmetic and print it to the console. Then, we mutate it again by manually assigning a new value to it.

Output:
5 + 3 = 8
5 * 3 = 15
New value: -1

We cannot mutate a variable with just any other type of value than it was declared with.

For example, we can’t assign a string value to variable above, it would raise (generate) an error.

Example:
public class Program {

    public static void main(String[] args) {

        // variable initialization
        int num = 5;

        // mutate to different type
        num = "Hello, World!";
    }
}

When we try to run the example above, the compiler raises a ‘mismatch type’ error.

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from String to int

The compiler couldn’t typecast the string into a number. We can only convert certain types into certain other types.

We discuss typecasting in the lesson on Data TypesOpens up in a new page .

What is a constant

A constant is a variable that cannot have it’s value changed during runtime.

We use constants when we do not want a value to accidentally change, like the value of Pi, or gravity.

How to initialize a constant in Java

A constant cannot be declared without a value, because a value cannot be assigned later on. There would also be no point to an empty constant.

To initialize a constant with a value, we use the final keyword in front of the data type.

Syntax:
 final data_type CONSTANT_NAME = value;

As mentioned in the Basic Syntax lessonOpens up in a new page , the convention for naming constants is uppercase words with underscores as word separators (uppercase snake).

Example:
public class Program {

    public static void main(String[] args) {

        // constant initialization
        final float PI = 3.14f;

        System.out.println("Pi: " + PI);
    }
}

In the example above, we specify that ‘PI’ is final, it cannot have its value changed at runtime.

Output:
 Pi: 3.14

If we try to mutate the constant, the compiler will raise an error.

Example:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The final local variable PI cannot be assigned. It must be blank and not using a compound assignment

Java operands: lvalues and rvalues

Java has two types of expressions, lvalues and rvalues.

The operand on the left side of the assignment operator ( = ) is the Lvalue, and the operand on the right side is the Rvalue.

Lvalue:

An Lvalue can have a value assigned to it so it’s allowed to appear either on the left or the right side of an assignment.

Example: lvalue
// lvalue (num1) may
// be on the left
int num1 = 10;

// or on the right of the =
int num2 = num1;

Rvalue:

An rvalue cannot have a value assigned to it so it may only appear on the right side of an assignment.

Example: rvalue
// rvalue (10) may only be on the right
int num1 = 10;

// and cannot be on the left
10 = 10;

Examples of common variable data types in Java

The following quick example shows some popular types of variables we can create.

Example:
public class Program {

    public static void main(String[] args) {

        // boolean
        boolean a = false;

        // byte
        byte b = 10;

        // int
        int c = 52348799;

        // float
        float d = 3.14f;

        // double
        double e = 3.14159265359;

        // char
        char f = 'U';

        // string
        String g = "Hello, World!";

        System.out.println("boolean: " + a);
        System.out.println("byte: " + b);
        System.out.println("int: " + c);
        System.out.println("float: " + d);
        System.out.println("double: " + e);
        System.out.println("char: " + f);
        System.out.println("String: " + g);
    }
}
Output:
boolean: false
byte: 10
int: 52348799
float: 3.14
double: 3.14159265359
char: U
String: Hello, World!

Summary: Points to remember

  • Variables and constants are temporary data containers that hold values while the program runs.
    • Once the data isn’t used anymore, or the program quits, they are destroyed.
  • We declare/initialize variables and constants with specific types.
    • Only that type of value is allowed to be assigned unless typecasted.
  • To declare/initialize multiple variables of the same type, we separate them with a comma.
  • A constant can only be initialized, and uses the final keyword in front of the type.
  • Values stored in variables are mutable.
  • Values stored in contants are immutable.
  • To use a variable or constant, we refer to its name wherever we need to in our code.