Skip to content
Laviyx Learn

Try

Java course menu

Java Variables: Declaring, Initializing, var and Naming

Learn Java variables: declaring and initializing them, changing values, local variable type inference with var, why Java requires initialization before use, naming conventions, and swapping two variables.

Beginner8 min readUpdated
On this page

A variable is a named place that holds a value. Java is statically typed: every variable has a type that is fixed when you declare it, and the compiler checks that you only store matching values in it.

Declaring and initializing#

Write the type, the name and (usually) a starting value:

Java
public class Main {
    public static void main(String[] args) {
        int age = 21;
        double price = 49.99;
        char grade = 'A';
        boolean isMember = true;
        String name = "Asha";

        System.out.println(name + " is " + age);
        System.out.println("Price: " + price + ", grade: " + grade);
        System.out.println("Member: " + isMember);
    }
}
Output
Asha is 21
Price: 49.99, grade: A
Member: true

Giving a variable its first value is called initialization. You can also declare first and assign later:

Java
int count;
count = 10;

Java checks initialization for you#

Using a local variable before it has a value is a compile error, not a run-time surprise:

Java
public class Main {
    public static void main(String[] args) {
        int total;
        total = total + 10;   // error: variable total might not have been initialized
    }
}

This rule (called definite assignment) prevents a whole class of bugs that C and C++ allow.

Changing a variable#

Assign a new value with =. The type stays the same:

Java
public class Main {
    public static void main(String[] args) {
        int score = 10;
        System.out.println(score);

        score = 25;
        System.out.println(score);

        score = score + 5;
        System.out.println(score);
    }
}
Output
10
25
30

score = score + 5 calculates the right side first, then stores the result. The short form is score += 5; see Operators.

Assigning a value of the wrong type does not compile:

Java
public class Main {
    public static void main(String[] args) {
        int count = 3;
        count = "three";   // error: incompatible types: String cannot be converted to int
    }
}

var: let the compiler infer the type#

Since Java 10, local variables can be declared with var. The compiler infers the type from the initial value:

Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        var items = 3;                         // int
        var weight = 2.5;                      // double
        var city = "Pune";                     // String
        var names = new ArrayList<String>();   // ArrayList<String>
        names.add(city);

        System.out.println(items * weight + " " + names);
    }
}
Output
7.5 [Pune]

The variable is still strongly typed: after var items = 3; you cannot store a String in items. var only works for local variables that are initialized on the same line. It shines with long type names; for simple values, writing int or String is often clearer.

Declaring several variables#

Java
int width = 4, height = 3;

One declaration per line is usually easier to read.

Naming variables#

Use camelCase: start with a lowercase letter, and capitalize each following word (totalPrice, studentCount). Choose names that describe the value:

UnclearClear
xprice
n2studentCount
tmppreviousBalance

Short names like i and j are fine for loop counters.

Swapping two variables#

Java
public class Main {
    public static void main(String[] args) {
        int a = 1;
        int b = 2;

        int temp = a;
        a = b;
        b = temp;

        System.out.println(a + " " + b);
    }
}
Output
2 1

Common mistakes#

Practice#

Practice exercise

Create variables for a product: its name ("Notebook"), its price (45.5) and the quantity in a cart (4). Print the total cost, then increase the quantity by 2 and print the new total.

Show solution
Java
public class Cart {
    public static void main(String[] args) {
        String product = "Notebook";
        double price = 45.5;
        int quantity = 4;

        System.out.println(product + ": " + price * quantity);

        quantity += 2;
        System.out.println(product + ": " + price * quantity);
    }
}
Output
Notebook: 182.0
Notebook: 273.0

A double multiplied by an int gives a double, which Java prints with .0.

Key takeaway#

Finished this lesson?