AP Computer Science A

Unit: Primitives and Casting


1. Primitive Data Types

Primitive data types in Java store simple values directly in memory. They are not objects and do not have methods.

Common Primitive Types (AP CSA Focus)

Type Size Example Values Notes
int 32-bit -5, 0, 42 Most commonly used for whole numbers
double 64-bit 3.14, -0.5, 2.0 Default type for decimals
boolean Logical true, false Only two possible values
char 16-bit 'A', '7', '$' Single character, uses single quotes
AP Exam Tip: The AP CSA exam mainly focuses on int, double, boolean, and char.

2. Declaring and Initializing Variables

Declaration

int number;
double price;
boolean isValid;
char letter;

Initialization

int number = 10;
double price = 5.99;
boolean isValid = true;
char letter = 'A';

3. Arithmetic with Primitives

Integer Arithmetic

When both operands are int, the result is also an int. Decimal values are truncated.

int result = 7 / 2;   // result is 3

Double Arithmetic

If at least one operand is a double, the result is a double.

double result = 7 / 2.0;   // result is 3.5

4. Casting (Type Conversion)

Casting is the process of converting a value from one data type to another.

5. Implicit Casting

Implicit casting happens automatically when converting a smaller type to a larger type.

int x = 5;
double y = x;   // y becomes 5.0

6. Explicit Casting

Explicit casting is required when converting a larger type to a smaller type.

double x = 5.9;
int y = (int) x;   // y becomes 5
Important: Casting from double to int truncates the decimal value (does not round).

7. Casting in Expressions

int a = 5;
int b = 2;

double result1 = a / b;          // 2.0
double result2 = (double) a / b; // 2.5

8. Casting with char

char c = 'A';
int value = c;          // 65
char next = (char)(value + 1);  // 'B'

9. Common Errors to Avoid

10. AP-Style Practice Question

int x = 10;
int y = 3;
double result = (double) x / y;

Answer: 3.3333333333333335