AI Hints
Home›Java Tutorial›Variables, Primitive Types, int and long
Java · Lesson 10 of 120

Variables

Named boxes for values.

⏱ 2 min read▶ Video at 12:39🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A variable is a named box that holds a value. You give it a name, and a type, and then you can use it, and change it, whenever you like.

  • A named box
  • With a type
  • Use it, change it

Making a variable

First comes the type, which says what kind of value the box holds. Then the name. Then an equals sign, and the starting value. And a semicolon ends the line.

keyvalue
intthe type: whole numbers
cupsthe name
= 3the starting value
;end of statement

Create, use, change

Int cups is a whole number, three. String drink holds text. We use both inside println. Then we give cups a new value, five, with no type this time, because the box already exists. Cups equals cups plus one, adds one to it. Run it. Three cups, then five, then six.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int cups = 3;
        String drink = "tea";
        System.out.println(cups + " cups of " + drink);

        cups = 5;
        System.out.println(cups + " cups of " + drink);
        cups = cups + 1;
        System.out.println("Now " + cups);
    }
}
Output
3 cups of tea
5 cups of tea
Now 6

Java checks your types

Here, age is an int. Then we try to put text inside it. Run it. Java stops before running anything. A box made for numbers can't hold text. This check is one of Java's biggest strengths.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int age = 30;
        age = "thirty";
    }
}
Output
Main.java:4: error: incompatible types: String cannot be converted to int
        age = "thirty";
              ^
1 error
error: compilation failed

Give it a value first

Here, score is declared, but never given a value. Then we try to print it. Run it. Java says score might not have been initialised. You must put something in the box, before you read it.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int score;
        System.out.println(score);
    }
}
Output
Main.java:4: error: variable score might not have been initialized
        System.out.println(score);
                           ^
1 error
error: compilation failed

Summary

A variable has a type, a name, and a value. Java checks that every value fits its type, before running anything. Next, Java's built in types.

Key takeaways
  • type name = value;
  • Change it any time
  • Types are checked
Next up: Primitive Types — the eight simple types