AP CSA Unit 1 Notes: Building Programs with Variables, Types, and Expressions in Java
Why Programming? Why Java?
What programming is
Programming is the process of writing precise instructions that a computer can follow to solve problems. Those instructions form a program, which takes inputs (data), performs computations or decisions, and produces outputs (results).
At a deeper level, programming is about creating a clear, repeatable process. If you can describe a method for solving a problem step by step, you can usually translate that method into code. This is why programming shows up in so many fields: it’s a way to automate thinking.
Why programming matters (especially in AP CSA)
In AP Computer Science A, you’re not just learning to “make code run.” You’re learning how to:
- Model real information using data
- Choose appropriate data types so the computer stores and interprets that information correctly
- Combine data using expressions to compute new results
- Update stored values as a program progresses
Variables and data types are foundational because everything else in Java builds on them. If you can’t reliably predict what a variable contains or what a line of code changes, debugging and reasoning about programs becomes guesswork.
Why Java?
Java is a general-purpose programming language that’s widely used in industry and education. AP CSA uses Java because it balances a few important goals:
- Strong typing: Java forces you to be explicit about what kind of data a variable holds (like
intvsdouble). This reduces ambiguity and helps you learn precision. - Object-oriented programming (OOP): Java is designed around objects and classes. AP CSA’s broader goal is to teach OOP concepts, and Java supports them naturally.
- Readable, structured syntax: Java’s syntax is strict, which can feel unforgiving at first—but that strictness trains you to write unambiguous code.
A helpful mental model: Java is like a very strict teacher. It won’t “guess what you meant.” That’s annoying early on, but it builds good habits.
Java programs run on a JVM (why that matters conceptually)
Java code is typically compiled into bytecode, which runs on the Java Virtual Machine (JVM). You don’t need to master the JVM for AP CSA, but the key takeaway is: Java aims for consistent behavior across computers, which makes its type rules and numeric behavior predictable.
Exam Focus
- Typical question patterns:
- Explain what a line of code does (often focusing on how variables store and change values).
- Predict the output of a short code segment.
- Choose the best data type for a described piece of information.
- Common mistakes:
- Treating Java like it will “figure it out” (it won’t): Java requires correct types and syntax.
- Confusing Java (a language) with the computer’s underlying hardware; Java’s rules are defined by the language.
Variables and Primitive Data Types
Variables: what they are
A variable is a named storage location in memory that holds a value. You use variables to remember information so you can use it later, update it, and combine it with other values.
In Java, variables have:
- A type (what kind of data it can hold)
- A name (how you refer to it)
- A value (the actual data stored right now)
You can think of a variable like a labeled box: the label is the variable name, the type is the kind of thing the box is allowed to hold, and the value is what’s inside.
Declaring and initializing variables
Declaration tells Java the variable’s type and name:
int score;
At this point, score exists, but if it’s a local variable (inside a method), you cannot use it until you assign it a value.
Initialization gives it its first value:
int score = 0;
It’s common to declare and initialize in one line.
Primitive data types: what they are
A primitive type is a built-in, basic data type that stores a simple value directly (not an object). In AP CSA Unit 1, you’ll frequently use int, double, and boolean. You may also see char.
Here are Java’s primitive types:
| Category | Type | What it stores | Example |
|---|---|---|---|
| Integer | byte, short, int, long | whole numbers | int n = 42; |
| Floating-point | float, double | decimal approximations | double x = 3.14; |
| Character | char | a single Unicode character | char c = 'A'; |
| Boolean | boolean | true/false | boolean ok = true; |
int
int stores whole numbers (positive, negative, or zero). It’s the default choice for counting and indexing.
double
double stores decimal numbers, but an important truth is that most decimals are stored as approximations in binary. That’s why calculations like 0.1 + 0.2 might not equal exactly 0.3.
boolean
boolean stores true or false. It’s central for decision-making (later units), but you’ll start using it early for conditions and logical results.
char
char stores a single character in single quotes, like 'A' or '7'. A char is not the same as a String.
Reference types vs primitives (important context)
A reference type variable doesn’t store the “whole value” directly; it stores a reference (think: a pointer/address-like value) to an object. In Unit 1, the most common reference type is String.
int,double,boolean,charare primitives.Stringis an object type.
Why this matters: primitives and objects behave differently with methods and with equality (you’ll explore that more later). Even now, you should notice that you can call methods on a String (like length()), but you cannot call methods on an int.
Naming rules and conventions
Java has strict rules for identifiers (variable names):
- Must start with a letter,
_, or$(by convention, start with a letter) - Can contain digits after the first character
- Cannot be a reserved word like
intorclass
Conventions (these help readability and are expected on AP-style code):
- Use camelCase for variables:
studentCount,totalPrice - Choose meaningful names:
minutesis better thanm
Constants with final
A constant is a variable whose value should not change after initialization. In Java, you use final:
final int DAYS_IN_WEEK = 7;
By convention, constants are written in ALLCAPSWITH_UNDERSCORES.
Examples (with explanation)
If you’re tracking a shopping cart, you might store:
int itemCount = 3; // whole number count
double totalCost = 19.98; // money-like value (still approximate)
boolean hasCoupon = false; // yes/no state
Here, int fits itemCount because you can’t have 3.5 items. double fits totalCost because prices include cents.
Common “type meaning” confusion
A very common beginner mistake is using double “because it’s more precise” even when the value is a count. This can make later logic harder (and introduces rounding issues). Prefer the type that matches the concept.
Exam Focus
- Typical question patterns:
- Select the most appropriate type (
intvsdoublevsboolean) for a variable in a scenario. - Identify whether a given assignment is legal (type-compatible) or causes a compile-time error.
- Determine what values are stored after declarations and initializations.
- Select the most appropriate type (
- Common mistakes:
- Using a variable before it’s initialized (especially local variables).
- Mixing up
charandString(single quotes vs double quotes). - Assuming
doublestores decimals exactly (it often doesn’t).
Expressions and Assignment Statements
Expressions: what they are
An expression is code that produces a value. That value could be a number, a boolean, a character, or something else.
Examples of expressions:
4 + 5(produces9)x * 2(produces a number based onx)count > 10(producestrueorfalse)
Expressions matter because programs are mostly about computing values from other values.
Operators you’ll use early
Java includes standard arithmetic operators:
+addition-subtraction*multiplication/division%remainder (modulus)
And comparison operators (produce boolean):
==,!=,<,<=,>,>=
Assignment statements: what they do
An assignment statement stores a value into a variable using =.
int x = 10;
x = 25;
Important: In Java, = does not mean “equals” like in math. It means “take the value on the right and store it in the variable on the left.”
A key rule: the left side must be a variable (a storage location). The right side can be any expression.
How evaluation works (right side first)
In:
x = x + 3;
Java evaluates the right side using the old value of x, then stores the result back into x.
This line is meaningful in programming (increase x by 3), even though it would look “wrong” in algebra.
Operator precedence (how Java decides the order)
Java follows a consistent order of operations. Early on, the most important precedence idea is:
*,/,%happen before+,-- Parentheses override precedence
So:
int result = 2 + 3 * 4; // 14, not 20
Integer division (a major AP CSA pitfall)
If both operands of / are integers, Java performs integer division, which discards the decimal part (it does not round; it truncates toward zero).
int a = 7 / 2; // 3
int b = 1 / 2; // 0
int c = -7 / 2; // -3
If at least one operand is a double, Java performs floating-point division:
double x = 7 / 2.0; // 3.5
This matters constantly in AP questions because a single .0 can change the entire result type.
Remainder % (modulus) and why it’s useful
a % b gives the remainder when dividing a by b.
Common uses:
- Determine even/odd:
n % 2 == 0 - Get the last digit:
n % 10 - Wrap values in a range (like clock arithmetic)
Example:
int n = 27;
int lastDigit = n % 10; // 7
String concatenation with +
The + operator also concatenates strings. If either side of + is a String, Java converts the other side to a string and joins them.
String msg = "Score: " + 10; // "Score: 10"
A common surprise is that evaluation happens left to right:
System.out.println("Total: " + 2 + 3); // "Total: 23"
System.out.println(2 + 3 + " total"); // "5 total"
The first line becomes string concatenation as soon as Java sees a String on the left.
Worked example: tracing assignments
Consider:
int x = 5;
int y = x * 2;
x = x + 1;
int z = x + y;
System.out.println(x + "," + y + "," + z);
Step-by-step:
- Start:
x = 5 y = x * 2uses currentx(5), soy = 10x = x + 1updatesxto 6z = x + yuses newx(6) andy(10), soz = 16- Output:
6,10,16
Exam Focus
- Typical question patterns:
- Trace a sequence of assignments and report final variable values.
- Predict output involving integer division,
%, and string concatenation. - Determine the type/value of an expression (especially
intvsdouble).
- Common mistakes:
- Assuming
/always produces a decimal (it doesn’t with two ints). - Misreading
=as a symmetric equality statement instead of “store the right into the left.” - Forgetting that
"text" + 2 + 3becomes"text23"due to left-to-right evaluation.
- Assuming
Casting and Ranges of Variables
Range: every numeric type has limits
Because a computer stores numbers using a fixed number of bits, each numeric primitive type has a range (minimum and maximum values it can represent).
Java’s integer types have fixed sizes:
| Type | Bits | Range (inclusive) |
|---|---|---|
byte | 8 | -128 to 127 |
short | 16 | -32,768 to 32,767 |
int | 32 | -2,147,483,648 to 2,147,483,647 |
long | 64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
char | 16 | 0 to 65,535 |
For floating-point:
floatuses 32 bits (about 7 decimal digits of precision)doubleuses 64 bits (about 15–16 decimal digits of precision)
You usually don’t need exact double max/min values for AP CSA, but you do need to understand that floating-point values are approximate and can involve rounding.
Overflow and why it matters
Overflow happens when a calculation produces a value outside the type’s range. For integer types in Java, overflow “wraps around” in a way that can produce surprising results.
Example idea (not something you’re expected to memorize numerically): if an int is already at its maximum and you add 1, it becomes a negative number.
This matters because Java won’t automatically warn you at runtime for integer overflow—you just get a wrong-looking value.
Casting: converting between types
Casting is the process of converting a value from one type to another.
There are two broad categories:
- Widening conversion (usually automatic): going from a smaller or “narrower” type to a wider one, like
inttodouble. - Narrowing conversion (requires an explicit cast): going from a wider type to a narrower one, like
doubletoint.
Widening (implicit) conversions
Java will automatically convert when it’s safe in the sense of “won’t lose the kind of information,” although floating-point conversions can still lose precision.
int count = 7;
double avg = count; // becomes 7.0
This is common in mixed arithmetic: if you combine an int and a double, the int is promoted to double and the result is double.
Narrowing (explicit) conversions
When converting double to int, Java requires you to be explicit because you might lose the fractional part.
double price = 19.99;
int dollars = (int) price; // 19
Important detail: casting from double to int truncates toward zero. It does not round to the nearest integer.
Casting in expressions (controlling division behavior)
A classic AP CSA use of casting is to force floating-point division.
Suppose you want the average of two integers:
int a = 1;
int b = 2;
double avg1 = (a + b) / 2; // integer division first: 1
double avg2 = (a + b) / 2.0; // 1.5
double avg3 = (double) (a + b) / 2; // 1.5
What’s happening:
- In
avg1,(a + b)isint,2isint, so/is integer division. - In
avg2,2.0isdouble, so Java performsdoubledivision. - In
avg3, casting makes the numerator adouble, so the division becomes floating-point.
char and numeric behavior (a common surprise)
A char stores a Unicode code value under the hood. This means you can do arithmetic with char values, though you should be careful.
char c = 'A';
int code = c; // 65
char next = (char) (c + 1); // 'B'
For AP CSA, the big idea is not memorizing codes, but recognizing that char is a numeric type in Java and can be cast to/from int.
What can go wrong: losing information
Casting can lose information in two main ways:
- Dropping decimals:
(int) 3.99becomes3 - Overflow/wraparound when casting large values into smaller types
Because AP CSA questions often ask you to predict results, you must pay attention to the types involved at each operation.
Exam Focus
- Typical question patterns:
- Predict the result and type of an expression mixing
intanddouble. - Determine what a casted value becomes (especially
(int)casting adouble). - Identify when integer overflow could occur conceptually.
- Predict the result and type of an expression mixing
- Common mistakes:
- Believing casting rounds (it truncates toward zero).
- Forgetting that
(a + b) / 2does integer division when all parts areint. - Assuming
doublearithmetic is always exact (it’s approximate).
Compound Assignment Operators
What compound assignment is
A compound assignment operator updates a variable by combining its current value with another value in a single, shorter statement.
For example, instead of:
x = x + 5;
you can write:
x += 5;
Compound assignments matter because they are extremely common in real code (especially in loops you’ll see later), and AP CSA expects you to read them fluently.
Common compound assignment operators
These are the most common:
+=add and assign-=subtract and assign*=multiply and assign/=divide and assign%=remainder and assign
Example:
int x = 10;
x -= 3; // x is now 7
x *= 2; // x is now 14
How compound assignment really works
Conceptually:
x op= ybehaves likex = x op y
But there’s a subtle type detail: compound assignment includes an implicit cast to the left-hand variable’s type.
Example:
int x = 5;
x += 2.7; // allowed; behaves like x = (int)(x + 2.7)
System.out.println(x); // 7
If you tried the non-compound version:
int x = 5;
x = x + 2.7; // compile-time error: x + 2.7 is a double
So for AP-style reasoning, remember:
x += someDoublecan compile even ifxis anint- The result is truncated to fit into
x
Increment and decrement (++ and --)
Java also has increment and decrement operators:
x++increasesxby 1x--decreasesxby 1++xand--xdo the same update, but can behave differently inside larger expressions
In AP CSA, you often see them as standalone statements:
int count = 0;
count++; // count is now 1
count--; // back to 0
Prefix vs postfix (when it matters)
When used inside a larger expression:
- Postfix
x++evaluates to the old value, then increments - Prefix
++xincrements first, then evaluates to the new value
Example:
int x = 3;
int a = x++; // a = 3, x = 4
int y = 3;
int b = ++y; // y = 4, b = 4
AP questions sometimes test whether you can trace these accurately. A good habit is to slow down and do it step-by-step: write the old value, then apply the update.
Worked example: compound assignment and integer division
int x = 7;
x /= 2;
System.out.println(x);
Because x is an int, x /= 2 performs integer division: 7 / 2 becomes 3. Output is 3.
If you instead had:
double x = 7;
x /= 2;
System.out.println(x);
Now x is double, so the result is 3.5.
What goes wrong: overusing ++ inside expressions
It’s possible to write confusing code like:
int x = 1;
int y = x++ + ++x;
This is legal, but it’s hard to read and easy to mis-trace. AP CSA tends to keep code readable, but you should still be prepared to trace prefix vs postfix carefully if it appears.
Exam Focus
- Typical question patterns:
- Rewrite or interpret updates like
total += amountorcount++. - Trace code that uses
++/--in assignments and output statements. - Predict results of
/=and%=with integers.
- Rewrite or interpret updates like
- Common mistakes:
- Forgetting integer division still applies inside
/=when the variable isint. - Mixing up prefix and postfix in expressions (
x++vs++x). - Not noticing that
+=can hide a narrowing conversion (truncation) when types differ.
- Forgetting integer division still applies inside