Compound Assignment Operators

Emily Wilson
14 min read
Listen to this study note
Study Guide Overview
This AP Computer Science A study guide covers primitive types and operators, control flow (if, for, while loops, boolean expressions), the String class (methods, concatenation), classes and objects (constructors, methods, inheritance, polymorphism), arrays (basics, traversing), ArrayLists (methods, traversing), 2D arrays, and recursion. It includes practice questions and emphasizes code tracing, exam tips, and common mistakes to avoid.
#AP Computer Science A: Ultimate Study Guide 🚀
Hey there, future AP Computer Science A rockstar! This guide is designed to be your best friend the night before the exam. We'll break down the key concepts, offer memory aids, and give you the confidence you need to ace this test. Let's do this! 💪
#1. Primitive Types and Operators
#1.1. Data Types
- int: Whole numbers (e.g., -3, 0, 42). 💡
- double: Decimal numbers (e.g., -3.14, 0.0, 2.718). 💡
- boolean:
true
orfalse
. 💡
Remember: int
and double
are numeric types, while boolean
is for logical values. These are your building blocks!
#1.2. Arithmetic Operators
+
(addition),-
(subtraction),*
(multiplication),/
(division),%
(modulo - remainder). 💡- Integer division truncates (e.g.,
5 / 2
is2
). - Modulo gives the remainder (e.g.,
5 % 2
is1
).
PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) is your best friend for order of operations. Remember it!
#1.3. Compound Assignment Operators
+=
,-=
,*=
,/=
,%=
combine an operation and assignment.x += 5
is the same asx = x + 5
. Super handy! 💡
#1.4. Increment and Decrement Operators
++
increments by 1,--
decrements by 1. * Post-increment (x++
): Returns the original value ofx
, then increments.- Pre-increment (
++x
): Incrementsx
, then returns the new value.
For the AP exam, you'll mostly see the post-increment (x++
) and post-decrement (x--
) operators. Focus on how they change the value after the current statement.
#1.5. Code Tracing
-
Follow code line by line, tracking variable changes. Use trace tables if it helps!
-
Pay close attention to how compound assignment and increment/decrement operators modify variables.
Practice Question
#Multiple Choice Questions
-
What is the value of
x
after the following code executes?int x = 5; x += 3; x--;
- 6
- 7
- 8
- 9 Answer: 7
-
What is the value of
y
after the following code executes?int y = 10; y /= 2; y %= 3;
- 0
- 1
- 2
- 3 Answer: 2
#Free Response Question
- Consider the following code segment:java\nint a = 12;\nint b = 5;\nint c = 0;\na -= b;\nb = 2;\nc = a % b;\na += c;\nb = a - b;\nc = b;\n``` \n\n(a) What are the final values of a, b, and c? Show your work by tracing the code.", "answer": "(a) \n a -= b; // a = 12 - 5 = 7\n b = 2; // b = 5 * 2 = 10\n c = a % b; // c = 7 % 10 = 7\n* a += c; // a = 7 + 7 = 14\n* b = a - b; // b = 14 - 10 = 4\n* c *= b; // c = 7 * 4 = 28\n\nFinal values: a = 14, b = 4, c = 28\n", "scoring": { "a": "1 point for correct value of a, 1 point for showing work", "b": "1 point for correct value of b, 1 point for showing work", "c": "1 point for correct value of c, 1 point for showing work" } } }
</div>
## 2. Control Flow <a id='control-flow'></a>
### 2.1. `if` Statements
* Execute code blocks based on conditions.
* `if (condition) { /* code */ }`
* `if (condition) { /* code */ } else { /* code */ }`
* `if (condition1) { /* code */ } else if (condition2) { /* code */ } else { /* code */ }`
### 2.2. `for` Loops
* Repeat code a specific number of times.
* `for (initialization; condition; update) { /* code */ }`
* Example: `for (int i = 0; i < 10; i++) { /* code */ }`
### 2.3. `while` Loops
* Repeat code while a condition is true.
* `while (condition) { /* code */ }`
* Be careful of infinite loops! ⚠️
### 2.4. Boolean Expressions
* Combine conditions using `&&` (AND), `||` (OR), `!` (NOT).
* `true && true` is `true`, `true && false` is `false`.
* `true || false` is `true`, `false || false` is `false`.
* `!true` is `false`, `!false` is `true`.
<div data-custom-tag="memory_aid">
Remember **AND** only returns true if **both** conditions are true. **OR** returns true if **at least one** condition is true. **NOT** reverses the boolean value.
</div>
<div data-custom-tag="common_mistake">
Be careful with the difference between `=` (assignment) and `==` (equality check) in conditions. Using `=` in an `if` statement will cause a compilation error.
</div>
### 2.5. Short-Circuit Evaluation
* For `&&`, if the first condition is false, the second isn't evaluated.
* For `||`, if the first condition is true, the second isn't evaluated.
<div data-custom-tag="practice_question">
## Multiple Choice Questions (MCQ)
### Question 1
What will be printed by the following code? `int x = 5; if (x > 3) { System.out.print("A"); } else { System.out.print("B"); }`
* A
* B
* AB
* Nothing
**Answer:** A
### Question 2
How many times will the following loop execute? `for (int i = 0; i < 7; i += 2) { System.out.print(i); }`
* 3
* 4
* 7
* 8
**Answer:** 4
## Free Response Question (FRQ)
### Question
Write a method `countEven` that takes an integer array `arr` and returns the number of even numbers in the array. For example, if `arr` is `{1, 2, 3, 4, 5, 6}`, the method should return `3`.
**Answer:**java\npublic int countEven(int[] arr) {\n int count = 0;\n for (int num : arr) {\n if (num % 2 == 0) {\n count++;\n }\n }\n return count;\n}\n```
",
"scoring": {
"initialization": "1 point for initializing the count variable",
"loop": "1 point for correct `for` or `while` loop structure",
"conditional": "1 point for correct conditional statement to check for even numbers",
"increment": "1 point for incrementing the count correctly",
"return": "1 point for returning the correct count"
}
}
}
#3. String Class
#3.1. String Basics
- Strings are sequences of characters.
- Created using double quotes:
String str = "Hello";
- Strings are immutable (cannot be changed after creation).
#3.2. String Methods
length()
: Returns the number of characters.substring(int start, int end)
: Returns a substring fromstart
(inclusive) toend
(exclusive).indexOf(String str)
: Returns the index of the first occurrence ofstr
.equals(String other)
: Checks if two strings have the same content (case-sensitive).compareTo(String other)
: Compares two strings lexicographically (dictionary order).
Remember: Strings are objects, so you must use .equals()
to compare their content, not ==
.
#3.3. String Concatenation
-
Use
+
to combine strings. -
Example:
String message = "Hello, " + name + "!";
Practice Question
#Multiple Choice Questions
Question 1: What is the output of the following code? String s = "Computer"; System.out.println(s.substring(2, 5));
Options:
- mpu
- omp
- put
- mput Answer: mpu
Question 2: Which of the following correctly compares two strings str1
and str2
for equality?
Options:
- str1 == str2
- str1.equals(str2)
- str1.compareTo(str2) == 0
- str1.equalsIgnoreCase(str2) Answer: str1.equals(str2)
#Free Response Question
Question: Write a method reverseString
that takes a String str
and returns its reversed version. For example, if str
is "hello", the method should return "olleh".
**Answer:**java\npublic String reverseString(String str) {\n String reversed = "";\n for (int i = str.length() - 1; i >= 0; i--) {\n reversed += str.charAt(i);\n }\n return reversed;\n}\n```
",
"scoring": {
"initialization": "1 point for initializing the reversed string",
"loop": "1 point for correct for
loop structure (going backwards)",
"character_access": "1 point for accessing the characters correctly",
"concatenation": "1 point for concatenating the characters to the reversed string",
"return": "1 point for returning the reversed string"
}
}
}
</div>
## 4. Classes and Objects <a id='classes-objects'></a>
### 4.1. Classes
* Blueprints for creating objects.
* Contain data (fields/instance variables) and behavior (methods).
* Example:
```
java
public class Dog {
private String name;
private int age;
public Dog(String name, int age) { ... }
public void bark() { ... }
}
```
### 4.2. Objects
* Instances of a class.
* Created using the `new` keyword: `Dog myDog = new Dog("Buddy", 3);`
### 4.3. Instance Variables
* Data associated with each object.
* Declared inside the class but outside any method.
* Use `private` for encapsulation (data hiding).
### 4.4. Constructors
* Special methods used to initialize objects.
* Have the same name as the class.
* No return type (not even `void`).
### 4.5. Methods
* Define the behavior of objects.
* Can have parameters and return values.
* Example: `public void bark() { System.out.println("Woof!"); }`
### 4.6. `this` Keyword
* Refers to the current object.
* Used to distinguish between instance variables and parameters with the same name.
<div data-custom-tag="key_point">
Classes are like cookie cutters, and objects are the cookies. Each object has its own set of instance variables.
</div>
<div data-custom-tag="practice_question">
## Multiple Choice Questions
### Question 1
**Question:** Which keyword is used to create an object of a class?
**Options:**
* class
* object
* new
* instance
**Answer:** new
### Question 2
**Question:** What is the purpose of a constructor?
**Options:**
* To create a class
* To initialize an object
* To define methods
* To declare variables
**Answer:** To initialize an object
## Free Response Question
### Question
**Question:** Create a class `Rectangle` with the following:
* Instance variables: `width` (int) and `height` (int)
* Constructor: Takes `width` and `height` as parameters and initializes the instance variables.
* Method: `getArea()` that returns the area of the rectangle.
**Answer:**java\npublic class Rectangle {\n private int width;\n private int height;\n\n public Rectangle(int width, int height) {\n this.width = width;\n this.height = height;\n }\n\n public int getArea() {\n return width * height;\n }\n}\n```
",
"scoring": {
"instance_variables": "1 point for declaring instance variables correctly",
"constructor": "1 point for creating a constructor that initializes the instance variables",
"getArea_method": "1 point for creating the `getArea` method",
"return_value": "1 point for returning the correct area",
"encapsulation": "1 point for using private instance variables"
}
}
}
#5. Arrays
#5.1. Array Basics
- Ordered collections of elements of the same type.
- Fixed size (cannot be changed after creation).
- Created using
new
:int[] numbers = new int[5];
- Access elements using index (starting from 0):
numbers[0] = 10;
#5.2. Array Length
- Use
array.length
to get the number of elements in an array (not a method, no parenthesis).
#5.3. Traversing Arrays
- Use
for
loops to iterate through array elements. - Example:
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
#5.4. Enhanced for
Loop
- Simplified way to traverse arrays or collections.
for (type element : array) { /* code */ }
- Example:
for (int num : numbers) { System.out.println(num); }
Array indices start from 0, not 1. Accessing an index out of bounds will cause an ArrayIndexOutOfBoundsException
.
Practice Question
#Multiple Choice Questions
Question 1: What is the index of the first element in an array?
- 0
- 1
- -1
- array.length Answer: 0
Question 2: What is the output of the following code? int[] arr = {1, 2, 3}; System.out.println(arr.length);
- 2
- 3
- 4
- Error Answer: 3
#Free Response Question
Question: Write a method sumArray
that takes an integer array arr
and returns the sum of all elements in the array.
**Answer:**java\npublic int sumArray(int[] arr) {\n int sum = 0;\n for (int num : arr) {\n sum += num;\n }\n return sum;\n}\n```
",
"scoring": {
"initialization": "1 point for initializing the sum variable",
"loop": "1 point for correct for
loop structure",
"summation": "1 point for adding the elements correctly",
"return": "1 point for returning the correct sum"
}
}
}
</div>
## 6. ArrayList <a id='arraylist'></a>
### 6.1. ArrayList Basics
* Dynamic, resizable arrays.
* Part of the `java.util` package: `import java.util.ArrayList;`
* Created using `new`: `ArrayList<Integer> numbers = new ArrayList<>();`
### 6.2. ArrayList Methods
* `add(element)`: Adds an element to the end.
* `add(index, element)`: Inserts an element at a specific index.
* `get(index)`: Returns the element at a specific index.
* `set(index, element)`: Replaces the element at a specific index.
* `remove(index)`: Removes the element at a specific index.
* `size()`: Returns the number of elements.
### 6.3. Traversing ArrayLists
* Use `for` loops or enhanced `for` loops, similar to arrays.
`ArrayList` is a very important topic. Make sure you know how to add, remove, and access elements.
<div data-custom-tag="practice_question">
**MCQ Questions:**
**Question:** Which method is used to add an element to the end of an ArrayList?
**Options:**
- add()
- insert()
- append()
- push()
**Answer:** add()
**Question:** What is the output of the following code? `ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); System.out.println(list.size());`
**Options:**
- 0
- 1
- 2
- Error
**Answer:** 2
**FRQ Question:**
**Question:** Write a method `removeEven` that takes an ArrayList of Integers and removes all even numbers from the list.
**Answer:**java\npublic void removeEven(ArrayList<Integer> list) {\n for (int i = 0; i < list.size(); i++) {\n if (list.get(i) % 2 == 0) {\n list.remove(i);\n i--; // Adjust index after removal\n }\n }\n}\n```
",
"scoring": {
"loop": "1 point for correct `for` loop structure",
"conditional": "1 point for correct conditional statement to check for even numbers",
"removal": "1 point for removing the element correctly",
"index_adjustment": "1 point for adjusting the index after removal",
"void_return": "1 point for not returning anything"
}
}
}
#7. 2D Arrays
#7.1. 2D Array Basics
- Arrays of arrays, representing tables or grids.
- Created using
new
:int[][] matrix = new int[3][4];
- Access elements using two indices:
matrix[row][col] = 10;
#7.2. Traversing 2D Arrays
- Use nested
for
loops to iterate through rows and columns. - Example:
java for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { System.out.print(matrix[row][col] + " "); } System.out.println(); } ```
Remember: matrix.length
gives the number of rows, and matrix[row].length
gives the number of columns in a specific row.
Practice Question
Multiple Choice Questions (MCQ):
-
Question: How do you access the element in the second row and third column of a 2D array named
matrix
? Options:- matrix[1][2]
- matrix[2][1]
- matrix[2, 3]
- matrix[3, 2] Answer: matrix[1][2]
-
Question: What does
matrix.length
represent for a 2D array namedmatrix
? Options:- Number of columns
- Number of rows
- Total number of elements
- Length of the first row Answer: Number of rows
Free Response Question (FRQ):
Question: Write a method sum2DArray
that takes a 2D array of integers and returns the sum of all elements in the array.
**Answer:**java\npublic int sum2DArray(int[][] matrix) {\n int sum = 0;\n for (int row = 0; row < matrix.length; row++) {\n for (int col = 0; col < matrix[row].length; col++) {\n sum += matrix[row][col];\n }\n }\n return sum;\n}\n```
",
"scoring": {
"initialization": "1 point for initializing the sum variable",
"outer_loop": "1 point for correct outer for
loop structure",
"inner_loop": "1 point for correct inner for
loop structure",
"summation": "1 point for adding the elements correctly",
"return": "1 point for returning the correct sum"
}
}
}
</div>
## 8. Inheritance and Polymorphism <a id='inheritance-polymorphism'></a>
### 8.1. Inheritance
* Allows a class (subclass/child) to inherit properties and methods from another class (superclass/parent).
* Use the `extends` keyword: `public class Dog extends Animal { ... }`
* Promotes code reuse and establishes an IS-A relationship.
### 8.2. `super` Keyword
* Used to call the constructor or methods of the superclass.
* Example: `super(name, age);`
### 8.3. Method Overriding
* Subclass provides its own implementation of a method that is already defined in the superclass.
* Use the `@Override` annotation.
### 8.4. Polymorphism
* Ability of an object to take on many forms.
* Achieved through inheritance and method overriding.
* Example: `Animal myAnimal = new Dog(); myAnimal.makeSound();` (calls the `makeSound` method of the `Dog` class).
<div data-custom-tag="memory_aid">
Think of inheritance as a family tree. The child inherits traits from the parent. Polymorphism means "many forms," like a shape that can be a circle, square, or triangle.
</div>
<div data-custom-tag="practice_question">
**MCQ Questions:**
**Question:** Which keyword is used to indicate that a class inherits from another class?
**Options:**
- implements
- inherits
- extends
- includes
**Answer:** extends
**Question:** What is method overriding?
**Options:**
- Creating a new method
- Hiding a method
- Providing a new implementation of an inherited method
- Calling a superclass method
**Answer:** Providing a new implementation of an inherited method
**FRQ Question:**
**Question:** Create a class `Animal` with the following:
* Instance variable: `name` (String)
* Constructor: Takes `name` as a parameter and initializes the instance variable.
* Method: `makeSound()` that prints "Generic animal sound".
Create a subclass `Dog` that extends `Animal` with the following:
* Constructor: Takes `name` as a parameter and calls the superclass constructor.
* Overrides the `makeSound()` method to print "Woof!".
**Answer:**java\nclass Animal {\n private String name;\n public Animal(String name) {\n this.name = name;\n }\n public void makeSound() {\n System.out.println(\"Generic animal sound\");\n }\n}\n\nclass Dog extends Animal {\n public Dog(String name) {\n super(name);\n }\n @Override\n public void makeSound() {\n System.out.println(\"Woof!\");\n }\n}\n```
",
"scoring": {
"animal_class": "1 point for creating the `Animal` class with correct instance variable and constructor",
"animal_makeSound": "1 point for creating the `makeSound` method in `Animal` class",
"dog_class": "1 point for creating the `Dog` class that extends `Animal`",
"dog_constructor": "1 point for creating the `Dog` constructor that calls the superclass constructor",
"dog_override": "1 point for correctly overriding the `makeSound` method in `Dog` class"
}
}
}
#9. Recursion
#9.1. Recursive Methods
- Methods that call themselves.
- Must have a base case (to stop the recursion) and a recursive step.
#9.2. Example: Factorial
java
public int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive step
}
}
#9.3. Example: Fibonacci
java
public int fibonacci(int n) {
if (n <= 1) {
return n; // Base case
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive step
}
}
Forgetting the base case or having an incorrect base case will lead to infinite recursion and a StackOverflowError
.
Practice Question
#Multiple Choice Questions
1. Question: What is a base case in a recursive method?
- The recursive call
- The condition that stops the recursion
- The method's return type
- The method's parameters Answer: The condition that stops the recursion
2. Question: What happens if a recursive method does not have a base case?
- It will run faster
- It will cause a StackOverflowError
- It will return 0
- It will return null Answer: It will cause a StackOverflowError
#Free Response Question
Question: Write a recursive method sumDigits
that takes an integer n
and returns the sum of its digits. For example, if n
is 123
, the method should return 6
.
**Answer:**java\npublic int sumDigits(int n) {\n if (n < 10) {\n return n; // Base case\n } else {\n return n % 10 + sumDigits(n / 10); // Recursive step\n }\n}\n```
",
"scoring": {
"base_case": "1 point for correct base case",
"recursive_call": "1 point for correct recursive call",
"modulus": "1 point for using modulus operator correctly",
"division": "1 point for using division operator correctly",
"return": "1 point for returning the correct sum"
}
}
}
</div>
## Final Exam Focus 🎯
### High-Priority Topics
* **Primitive Types and Operators**: Essential for all code.
* **Control Flow**: `if`, `for`, `while` are fundamental.
* **String Class**: Common in many problems.
* **Classes and Objects**: Core to object-oriented programming.
* **Arrays and ArrayLists**: Data structures you'll use frequently.
* **Inheritance and Polymorphism**: Key for advanced topics.
* **Recursion**: Appears in some FRQs.
### Common Question Types
* **Multiple Choice**: Testing knowledge of concepts and code tracing.
* **Free Response**: Writing methods, classes, and algorithms.
### Last-Minute Tips
* **Time Management**: Don't spend too long on one question. Move on and come back if needed.
* **Code Tracing**: Practice tracing code carefully, especially with loops and conditional statements.
* **Read Carefully**: Pay attention to the details in the question. Understand what the problem is asking before you start coding.
* **Practice, Practice, Practice**: The more you practice, the more confident you'll feel.
### You've Got This! 🎉
Remember, you've come a long way. Take a deep breath, stay calm, and trust your preparation. You're ready to rock this exam! Go get 'em! 🚀
Continue your learning journey

How are we doing?
Give us your feedback and let us know how we can improve