Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Variables & Primitive Types · Lesson 24 of 28

Variables

A free lesson from Swipe Coding · Java, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
Variables are how your program remembers things — let's give data a name. 📦

A variable is a named container that stores a piece of data your program can work with and change while it runs. In Java, every variable must have a declared type, so the compiler always knows what kind of data it is allowed to hold.

int age = 25;
System.out.println(age);
Declaring an int variable named age, giving it the value 25, and then printing it.
🤖
Notice how this pattern reads almost like a sentence: type, name, value. 🔤

The general pattern for declaring and initializing a variable is: type name = value;. Here, int is the type, age is the name, and 25 is the value assigned with the = operator. You don't have to assign a value right away — you can declare a variable first and give it a value later, as long as you assign something before you try to use it.

🤖
Naming rules feel picky at first, but they make code predictable. 📛

Variable names in Java must start with a letter, an underscore (_), or a dollar sign ($) — never a digit — and cannot be one of Java's reserved keywords (like class or int). Names are case-sensitive, so score and Score are two different variables. By convention, Java developers write variable names in camelCase: the first word is lowercase, and each following word starts with a capital letter, e.g. totalScore or firstName.

Fill in the blank

In Java, variable names conventionally use ____, where the first word is lowercase and every following word starts with a capital letter, such as totalScore.

A variable can also be reassigned: given a new value after it was already initialized. The new value simply replaces the old one — the old value is gone. The new value must still be compatible with the variable's declared type, since Java is statically typed and never lets a variable suddenly hold a different kind of data.

int lives = 3;
lives = lives - 1;
System.out.println(lives); // 2
Reassigning a variable using its own current value is a very common pattern, for example when tracking a changing score or a countdown.
Quick check

What happens when you reassign a variable that already has a value?

True or false

Once you declare a variable's type, you must write that type again every time you assign it a new value.

Keep your streak going in Swipe Coding

Swipe through every level of Java on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.

Get the Swipe apps →