Course outline · 0% complete

0/29 lessons0%

Course overview →

Primitive types

lesson 2-1 · ~7 min · 4/29

Quiz

Warm-up from lesson 1-2: you declared `int year = 1995;`. What does the compiler do if a later line says year = "hello"?

The primitives

In Python every number is a flexible object; Java instead offers fixed-size boxes and asks you to pick one. The payoff is speed and predictability — an int is always exactly 32 bits, so the compiler knows precisely how much memory a million of them need and exactly which CPU instruction adds them. Choosing the type is a real engineering decision: pick a box too small and values overflow (databases full of user IDs have crossed the int limit at real companies).

Java has eight built-in primitive types, simple values stored directly in memory. Four cover almost everything you write:

TypeHoldsExample
intwhole numbers up to about ±2.1 billionint age = 21;
doubledecimal numbersdouble price = 3.5;
booleantrue or falseboolean open = true;
charone character, in single quoteschar grade = 'A';

The others are long (huge whole numbers, write 9000000000L), short and byte (small numbers, rare), and float (less precise decimal, rare).

Declare once with the type, reassign without it. Names use camelCase by convention: totalScore, not total_score.

Code exercise · java

Run this to see one variable of each core primitive type printed with a label.

Reassignment and inference

Once declared, a variable can take new values of the same type:

int score = 10;
score = 25;      // fine, still an int

Declaring the same name twice in one scope is an error. Java also lets you write var score = 10; and infer the type from the right side, like Python but locked in at compile time. In this course we write the explicit type so you always see it.

Note the difference from Python: True/False become lowercase true/false, and single quotes are only for char, never for strings.

Code exercise · java

Your turn. Declare an int named steps set to 8500, a double named miles set to 4.2, and a boolean named goalMet set to true. Print three lines: `steps: 8500`, `miles: 4.2`, `goalMet: true`.

Overflow: the limits are real

An int uses 32 bits, which buys the range -2,147,483,648 to 2,147,483,647. Go past the edge and the value wraps around to the far end of the range — no error, no warning, just a silently wrong number. This is called overflow, and it is why the choice between int and long matters:

int big = 2147483647;      // the maximum int
big + 1                     // -2147483648 (wrapped!)
long safe = 2147483647L + 1L;  // 2147483648, long has room

Famous real-world case: systems that counted milliseconds or video views in an int broke at 2.1 billion. Rule of thumb: counts of things a human enters fit in int; timestamps, IDs, and anything that grows forever get long.

Code exercise · java

Run this and watch the maximum int wrap around to a large negative number when 1 is added, while the long version has room to spare.