What Are Variables?
Swipe to show menu
In Java, programs often need to store information so they can use it later. So far, you've only used values directly in code, like:
System.out.println("Hello!");
This works for simple programs, but real applications need a way to remember information instead of rewriting it again and again.
A variable is a named container for storing data.
In Java, every variable has three important parts: a type, a name, and a value. The type tells Java what kind of data can be stored, the name is how we refer to the variable, and the value is the actual data stored inside.
You can think of it like a box:
- The label on the box is the name of the variable;
- The type defines what kind of items the box is allowed to hold;
- The value is what we actually put inside the box.
For example:
int age = 25;
intis the type;ageis the name;25is the value.
So we are saying: create a box called age, allow it to store whole numbers, and put 25 inside it.
Once a variable is created, we can use it anywhere in our program.
Notice that we did not use quotation marks around age. That's important because:
"age"is treated as plain text;agerefers to the variable itself.
So this:
System.out.println("age");
prints:
age
Because Java treats it as text instead of a variable.
Variables can also change while the program runs:
Main.java
12345678910package com.example; public class Main { public static void main(String[] args) { int age = 25; age = 30; System.out.println(age); } }
This is why they are called variables — their value can vary during execution.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat