Remember Things
Declare and use variables (int, double, boolean).
We'll cover the following...
Let’s teach your Java programs how to remember things. In this lesson, you’ll store values using variables, give them names, and reuse them whenever you need.
Goal
You’ll aim to:
Declare and assign variables.
Use types:
int
,double
,boolean
.Print and reuse values.
The illustration above shows a variable named age
, assigned an integer value of 20, with a memory address of 0x5656
.
Declare a variable
Time to assign an integer value to a variable and see what it prints:
public class Main {public static void main(String[] args) {int age = 20;System.out.println("You are " + age + " years old.");}}
int
is used for whole numbers like 10, 20, or 100.
Great! You just created and printed your first variable.
More types
Let’s explore the double
and boolean
data types. A double
stores decimal
numbers, while a boolean holds either true or false.
public class Main {public static void main(String[] args) {double price = 4.99; // decimalboolean isSunny = true; // true or falseSystem.out.println("Price: $" + price);System.out.println("Sunny today? " + isSunny);}}
In Java, you must always tell the computer what type of value a variable will store. This is called static typing.
Well done! You’ve successfully declared and initialized both a double
and a boolean
variable.
Reassign variables
Let’s reassign the integer value 21
to the age
variable below.
public class Main {public static void main(String[] args) {int age = 20;age = 21;System.out.println("Next year: " + age);}}
You can change a variable’s value anytime—just assign a new one.
Well done! You’ve successfully reassigned the integer variable with the value 21
.
Mini challenge
Make a program that stores:
Your height in feet (as a
double
)Whether you like pizza (
boolean
)A message that prints both together
public class Main {public static void main(String[] args) {//Write your code here:}}
If you’re stuck, click the “Show Solution” button.
You did it! Another challenge complete—nice work.
Variable types recap
int
→ whole numbersdouble
→ decimalsboolean
→ true or falseString
→ text (coming next!)
What’s next?
Next up: how to store and work with text using String
variables.