Variables: Boxes That Hold Values

What is a variable?

A variable is a named box that holds a value, so you can use it later.

Think of it like this: Imagine a box with a label. The label says age and inside is the number 21. In Java the box also has a type printed on it, like “whole numbers only”. You can't put anything else in that box.

Creating a variable

In Java you write the type, then the name, then = and the value:

public class Main {
    public static void main(String[] args) {
        int age = 21;
        String name = "Asha";
        System.out.println(name);
        System.out.println(age);
    }
}

Output

Asha
21
  • int means the box holds a whole number.
  • String means the box holds text. (Notice the capital S.)

= does not mean “equals” like in maths. It means “put this value in the box”. This is called assigning.

Joining text and variables

Use + to stick text and variables together in one line:

public class Main {
    public static void main(String[] args) {
        String city = "Pune";
        int temperature = 31;
        System.out.println("It is " + temperature + " degrees in " + city);
    }
}

Output

It is 31 degrees in Pune

Changing a variable

Once a box exists, you can put a new value in it. Don't write the type again:

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

In score = score + 5, Java first works out the right side (25 + 5 = 30), then stores 30 in the box.

The type can't change

An int box only takes whole numbers. Putting text in it is a compile error:

public class Main {
    public static void main(String[] args) {
        int age = 21;
        age = "twenty";
    }
}

Output (the program does not compile)

Main.java:4: error: incompatible types: String cannot be converted to int
        age = "twenty";
              ^

Naming rules

AllowedNot allowedWhy
userNameuser nameNo spaces
score22scoreA name can't start with a digit
totaltotal-priceOnly letters, digits, _ and $
myClassclassJava's own keywords are reserved

Tip: Java programmers write names in camelCase: start small, and give every new word a capital letter, like totalPrice or numberOfStudents.

HOME LABS COMMUNITY DASHBOARD