Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn What Are Variables? | Variables and Data Types
Introduction to Java

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;
  • int is the type;
  • age is the name;
  • 25 is 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;
  • age refers 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

Main.java

12345678910
package 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.

question mark

What parts does a Java variable consist of?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 1
some-alt