☕ Java

Variables & Types

Lesson 2 of 5 ~5 min

Variables are named containers that store data values. In Java, every variable has a type that determines what kind of data it can hold. Because Java is statically typed, you must declare the type of a variable before using it.

Understanding variables and types is fundamental to writing Java programs. Every piece of data — numbers, text, true/false values — needs to be stored in a properly typed variable.

Primitive types

Declaring and initializing variables

Java requires you to declare a variable's type before assigning a value. You can declare and initialize in one step, or do them separately. Once a variable is declared, you can reassign it — but only with a value of the same type.

Editor
Java
Output

Try it

Change the variable values on the left and watch the output update. Try assigning a decimal to int and see what happens.

Type casting

When you need to convert a value from one type to another, Java supports type casting. There are two kinds: widening (automatic, safe) and narrowing (manual, may lose data).

// Widening cast (automatic) — no data lost
int myInt = 9;
double myDouble = myInt;    // int → double: 9.0

// Narrowing cast (manual) — may lose precision
double myDouble2 = 9.78;
int myInt2 = (int) myDouble2; // double → int: 9

System.out.println("Widened: " + myDouble);   // 9.0
System.out.println("Narrowed: " + myInt2);     // 9

The final keyword

Use the final keyword to declare a constant — a variable whose value cannot be changed after assignment. This is a best practice for values that shouldn't be modified.

final double PI = 3.14159;
final String APP_NAME = "Archon";

// This would cause a compile error:
// PI = 3.0;  // ❌ Cannot assign to final variable

System.out.println("PI = " + PI);           // 3.14159
System.out.println("App: " + APP_NAME);     // Archon

Key concepts

Quiz

Which keyword declares a constant in Java?
Challenge

Create one variable of each primitive type (int, double, boolean, char, String) and print all of them with descriptive labels using System.out.println().