Lesson 3 of 25

Variables & Data Types

Primitive Data Types

Java has 8 primitive data types. Each has a fixed size and stores a specific kind of value.

Example
// Integer types
byte smallNum = 127;           // 8-bit (-128 to 127)
short medNum = 32000;          // 16-bit
int number = 2_000_000;        // 32-bit (most common)
long bigNum = 9_000_000_000L;  // 64-bit (note the L)

// Floating point
float price = 9.99f;           // 32-bit (note the f)
double pi = 3.14159265;        // 64-bit (default)

// Other
boolean isActive = true;       // true or false
char letter = 'A';             // single character (single quotes)

Reference Types and Strings

Reference types include classes, arrays, and interfaces. Strings are the most commonly used reference type.

Example
// String (reference type, not primitive)
String name = "Alice";
String greeting = "Hello, " + name; // concatenation

// String methods
int len = name.length();           // 5
String upper = name.toUpperCase(); // "ALICE"
char first = name.charAt(0);      // 'A'
boolean starts = name.startsWith("Al"); // true

// Type casting
int x = 10;
double y = x;          // implicit (widening)
int z = (int) 3.14;    // explicit (narrowing) → 3

// var keyword (Java 10+)
var count = 42;        // inferred as int
var text = "hello";    // inferred as String