Primitive Types
in Java
Master the four essential building blocks: int, double, boolean, and char to store and manipulate data at the most fundamental level.
What Are Primitive Types?
In Java, every piece of data has a type that tells the compiler what kind of value it holds and how much memory to reserve. Primitive types are the simplest, most fundamental data types built directly into the language: they are not objects and have no methods.
Why Primitives Matter
The Four AP Primitives
Declaring and Initializing
A variable declaration tells Java what type and name to use. Initialization gives it a value. You can do both in one line:
The int Type
An int stores a 32-bit signed integer. Its range is from \( -2^{31} \) to \( 2^{31} - 1 \), which is approximately -2.1 billion to +2.1 billion.
The double Type
A double stores a 64-bit floating-point number using the IEEE 754 standard. It can represent extremely large or small values with decimal precision, but it is not perfectly precise.
boolean and char
Primitive vs. Reference Types
| Primitive | Reference (Object) | |
|---|---|---|
| Stores | The actual value | A memory address |
| Default value | 0, false, or '\u0000' | null |
| Memory | Stack (fixed size) | Heap (variable size) |
| Has methods? | No | Yes |
| Examples | int, double, boolean, char | String, ArrayList, Scanner |
Casting Between Types
Integer Arithmetic Rules
Choosing the Right Type
Example: Temperature Converter
Convert Fahrenheit to Celsius using the formula \( C = \frac{5}{9}(F - 32) \):
Example: Grade Calculator
Calculate a student's average and determine if they pass:
Example: Clock Arithmetic
The modulus operator \( % \) is essential for cyclic patterns like clocks, days, and array wrapping:
Common Mistakes
Summary Table
| Property | int | double | boolean | char |
|---|---|---|---|---|
| Size | 32 bits | 64 bits | 1 bit (logical) | 16 bits |
| Example | 42 | 3.14 | true | 'Z' |
| Default | 0 | 0.0 | false | '\u0000' |
| Division | Truncates | Keeps decimals | N/A | N/A |
| Literal form | 42 | 3.14 | true / false | 'A' |
Question 1 of 5
What is the value of \( \texttt{result} \) after this code runs?
int result = 17 / 5;
Question 2 of 5
Which declaration is incorrect Java syntax?
Question 3 of 5
What is the output of System.out.println(result)?
double result = 1 / 4 + 0.5;
Question 4 of 5
What does \( x % 10 \) evaluate to when \( x = 237 \)?
Question 5 of 5
What is the value of \( y \) after this code executes?
double x = 9.7; int y = (int) x;