Back to course

Variables and Primitive Data Types (int, boolean, char, double)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

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.

TypeCategorySize (bits)Default ValueRange Example
byteInteger80-128 to 127
shortInteger160
intInteger (Most Common)320Approx. +/- 2 Billion
longInteger640LVery large numbers
floatFloating Point320.0fSingle precision
doubleFloating Point (Most Common)640.0dDouble precision
booleanLogical1falsetrue or false only
charCharacter16'\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.