Lesson 6: Variables and Primitive Data Types
A variable is a container that holds a value. In Java, every variable must have a defined type.
Declaring and Initializing Variables
Variables are declared by specifying the type, followed by the name, and optionally initialized with a value.
java // Declaration (Type and Name) int studentCount;
// Initialization (Assigning a value) studentCount = 25;
// Declaration and initialization in one line double price = 19.99;
Java's 8 Primitive Data Types
These types store simple values directly in memory.
| Type | Category | Size (bits) | Default Value | Range Example |
|---|---|---|---|---|
byte | Integer | 8 | 0 | -128 to 127 |
short | Integer | 16 | 0 | |
int | Integer (Most Common) | 32 | 0 | Approx. +/- 2 Billion |
long | Integer | 64 | 0L | Very large numbers |
float | Floating Point | 32 | 0.0f | Single precision |
double | Floating Point (Most Common) | 64 | 0.0d | Double precision |
boolean | Logical | 1 | false | true or false only |
char | Character | 16 | '\u0000' | Single Unicode character |
Examples
java int population = 1500000; long universeTime = 31556952000L; // Note the 'L' suffix for long boolean isLoggedIn = true; char grade = 'A'; // Single quotes for char double pi = 3.14159; float smallPi = 3.14f; // Note the 'f' suffix for float
Note: When defining integer literals, Java defaults to int. When defining floating-point literals, Java defaults to double. You must use L or l for long and f or F for float if the value exceeds the default range or type.