Java Foundations

Lesson 2 of 7

Variables and Types

Java has two fundamentally different kinds of types: primitives, and objects. Mixing them up is one of the most common early confusions.

Primitives

int xp = 0;
double ratio = 0.5;
boolean loggedIn = true;
char grade = 'A';
xp += 10;

Primitives store their value directly, are fixed-size, and are not objects, they have no methods, can't be null, and are always passed by value.

Objects

Everything else, starting with String, is an object, a reference to data living on the heap:

String name = "Ada";
Integer boxedXp = 10;    // the "boxed" object version of int
name = null;              // objects CAN be null, primitives cannot

String looks like a primitive in everyday use (you can write "hello" directly), but it's really an object under the hood, with methods like .length() and .toUpperCase().

Type inference with var

Modern Java lets the compiler infer a local variable's type from its initializer:

var count = 5;          // inferred as int
var name = "Ada";        // inferred as String

var is purely a compile-time convenience, Java is still 100% statically typed underneath, count is genuinely an int forever, the compiler just saved you from typing it twice.

PrimitiveObject
Examplesint, double, boolean, charString, Integer, any class
Can be nullNoYes
Has methodsNoYes
StoredDirectly, on the stackReference to the heap

📝 Variables and Types Quiz

Passing score: 70%
  1. 1.Which of these can be set to null?

  2. 2.Using var still means the variable is statically typed, the compiler just infers the type instead of you writing it.

  3. 3.A type like int or boolean that stores its value directly and is never null is called a ____.