Java Basics

Types & Variables

Java is statically typed and compiled — every variable's type is fixed at compile time, and the compiler catches mismatches before the program ever runs.

Java 21 ✓ Beginner Friendly 2 Topics
01

Primitives & var

Java has eight primitive types that hold raw values directly, plus reference types (objects) that hold a pointer to data on the heap. Every variable must declare its type — or use var, which infers it at compile time but is still fully static.

Java — Declarations
// Explicit types — the classic style
int age = 25;
double price = 3.14;
boolean active = true;
char grade = 'A';
long big = 9_000_000_000L;   // underscores for readability, L suffix

// var — type inferred, but still static (Java 10+)
var name = "Alice";      // inferred as String
var count = 10;          // inferred as int
// var x;               // ERROR — needs an initializer to infer from

// final — a constant, cannot be reassigned
final double PI = 3.14159;
The Eight Primitives
TypeSizeExampleUsed For
byte8-bitbyte b = 100;Raw bytes, tight memory
short16-bitshort s = 1000;Rarely used directly
int32-bitint i = 42;Default whole number
long64-bitlong l = 9L;Large counts, timestamps
float32-bitfloat f = 1.5f;Rarely — precision loss
double64-bitdouble d = 1.5;Default decimal number
boolean1-bitboolean ok = true;Conditions
char16-bitchar c = 'A';Single Unicode character
var is not dynamic: unlike JavaScript, var name = "Alice" locks the type to String forever. Reassigning name = 42 is a compile error. It's inference, not flexibility.
02

Strings & Wrapper Classes

String is a class, not a primitive, and it's immutable — every "modification" creates a new object. Each primitive also has a wrapper class (Integer, Double, ...) so it can live in collections and be null.

Java — Strings & Autoboxing
String name = "Alice";
int len = name.length();           // 5
String up = name.toUpperCase();     // "ALICE" — new String, original untouched

// Text blocks (Java 15+) — multi-line strings
String json = """
    { "name": "Alice" }
    """;

// == compares references, .equals() compares content — ALWAYS use equals for Strings
String a = new String("hi"), b = new String("hi");
a == b;              // false — different objects
a.equals(b);         // true  — same content

// Autoboxing — primitive <-> wrapper, done automatically
Integer boxed = 42;      // int -> Integer
int unboxed = boxed;      // Integer -> int
== vs .equals() is the #1 Java beginner bug. == checks if two references point to the same object; .equals() checks if their contents match. For Strings and objects, almost always use .equals().

Quick Quiz

1. How many primitive types does Java have?
2. var name = "Alice"; — can you later assign name = 42?
3. To compare String contents you should use…
4. Java Strings are…
5. Integer boxed = 42; is an example of…