AP Computer Science A · Unit 1: Using Objects & Methods
1.2 Variables and Data Types
Primitive Data Types
Java has 8 primitive types, but AP CSA focuses on three: int (whole numbers), double (decimal numbers), and boolean (true/false). Primitives store actual values directly in memory, not references. Each variable must be declared with a type before use, like `int x;` or `double y = 3.5;`.
Declaring and Initializing Variables
A declaration states a variable's type and name: `int score;`. Initialization assigns it a value: `score = 100;`. You can combine both: `int score = 100;`. Variable names must follow Java naming rules — start with a letter, no spaces, and are case-sensitive.
Casting Between Types
Casting converts one data type to another. Widening (int → double) happens automatically. Narrowing (double → int) requires explicit casting, like `(int) 7.9`, which truncates (not rounds) the decimal part, giving 7. Mixing int and double in expressions produces a double result unless cast.
Key terms
- Primitive data type
- A basic data type (int, double, boolean) that stores its value directly in memory, not as a reference.
- Declaration
- Specifying a variable's type and name, e.g., int x; — no value assigned yet.
- Initialization
- Assigning a value to a variable, e.g., x = 5;
- Casting
- Converting a value from one data type to another; narrowing casts (like double to int) require explicit syntax and truncate decimals.
- Widening vs. Narrowing conversion
- Widening (int→double) happens automatically; narrowing (double→int) requires explicit casting and loses the decimal part.
Try an AP-style question
Which is a primitive type in Java?
- String
- ArrayList
- Scanner
- double
Show the answer
D. int, double, boolean are primitives.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.2 free in APrep