variables and data types
What is a Variable?
A variable is a named container used to store data in memory. In Java, every variable must be declared with a specific type before it can be used — this is what makes Java a statically typed language. Once a variable's type is set, it cannot hold a different type of data later.
int age = 25;
String name = "Alice";
double price = 19.99;Primitive Data Types
Java has 8 built-in primitive types. These are not objects — they store raw values directly in memory, which makes them fast and memory-efficient.
| Type | Size | Example | Use Case |
|---|---|---|---|
byte | 1 byte | byte b = 100; | Small numbers, saving memory |
short | 2 bytes | short s = 5000; | Slightly larger whole numbers |
int | 4 bytes | int x = 100000; | Default choice for whole numbers |
long | 8 bytes | long big = 15000000000L; | Very large whole numbers |
float | 4 bytes | float f = 5.75f; | Decimal numbers, less precision |
double | 8 bytes | double d = 19.99; | Default choice for decimal numbers |
char | 2 bytes | char c = 'A'; | A single character |
boolean | 1 bit | boolean isReady = true; | True/false values |
Note: Notice theLafter the long literal and thefafter the float literal — Java requires these suffixes so the compiler knows exactly which type you mean.
Reference Types
Anything that isn't a primitive is a reference type — this includes String, arrays, and any object created from a class. Reference variables store the memory address of an object, not the object's value directly.
String greeting = "Hello there";
int[] numbers = {1, 2, 3, 4, 5};Declaring vs Initializing
You can declare a variable without giving it a value right away, and assign the value later:
int score; // declaration
score = 100; // initialization
// or combine both:
int score = 100;Constants with final
If a value should never change after it's set, mark it with the final keyword. By convention, constants are named in uppercase with underscores.
final double PI = 3.14159;
final int MAX_USERS = 100;Type Casting
Sometimes you need to convert one type into another. Java supports two kinds of casting:
Widening (Implicit) Casting
Converting a smaller type to a larger type happens automatically — no data is lost.
int myInt = 9;
double myDouble = myInt; // int -> double automaticallyNarrowing (Explicit) Casting
Converting a larger type into a smaller one must be done manually, since it can lose precision.
double myDouble = 9.78;
int myInt = (int) myDouble; // becomes 9, decimal part is droppedNaming Rules for Variables
- Must begin with a letter,
$, or_(never a digit) - Cannot be a reserved keyword (like
classorint) - Case-sensitive:
ageandAgeare different variables - Convention: use camelCase for variable names, e.g.
firstName,totalPrice
Coming up next: Now that you can store data, let's learn how to manipulate it using Java's operators.