Variables & Types
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
- → int — Whole numbers:
int age = 25; - → double — Decimal numbers:
double price = 9.99; - → boolean — True or false:
boolean isActive = true; - → char — Single characters:
char grade = 'A'; - → String — Text (not a primitive, but used like one):
String name = "Alice";
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.
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
- → Declaration —
int count;creates a variable with type and name. - → Initialization —
count = 0;assigns an initial value. - → Combined —
int count = 0;does both at once. - → final — Marks a variable as a constant that cannot be reassigned.
- → Naming convention — Variables use
camelCase, constants useUPPER_SNAKE_CASE.
Quiz
Create one variable of each primitive type (int, double, boolean, char, String) and print all of them with descriptive labels using System.out.println().