Ch 4 · Data Types — Kinds of Values · Java
Topic 4 of 13 in Java — Complete Tutorial (Beginner) — 4 lessons.
Primitive Types and Why Type Matters
Java has a set of built-in "primitive" types for the most basic kinds of values, and you must choose the right one for each variable. The most common are int for whole numbers, double for decimals, boolean for true/false, and char for a single character. Text is handled by String, which is not a primitive but is used constantly. Because Java knows each variable's exact type, it can store data efficiently and catch type mistakes before the program runs.
Numbers: int and double
int holds whole numbers; double holds numbers with a decimal point. A very important rule trips up beginners: when you divide two int values, Java throws away the remainder and gives a whole number — 7 / 2 is 3, not 3.5! To get a decimal result, at least one value must be a double. The % (modulus) operator gives the remainder of a division, which is extremely useful for checking even/odd numbers.
boolean and char
A boolean holds only true or false — the language of decisions. Every if condition must produce a boolean. A char holds a single character written in single quotes, like 'A' or '?'. Be careful: single quotes make a char, while double quotes make a String. Booleans often come from comparisons, such as score >= 40, which Java evaluates to true or false.
Type Casting and var
Sometimes you need to convert a value from one type to another — this is called casting. Converting a double to an int requires an explicit cast (int), and it drops the decimal part. Going the other way (int to double) happens automatically because no information is lost. Modern Java also offers the var keyword, which lets Java figure out the type from the value, saving you from writing it twice — though the variable still has a fixed type.