Crash Course — Full Course Cram Sheet
In simple terms: Welcome to your final AP Computer Science A review. This course is all about learning to think like a programmer: breaking down big problems into small, logical steps. The AP exam tests your ability to apply these problem-solving skills using the Java programming language. It focuses on how you design, write, and analyze code, especially with object-oriented principles and common data structures.
Crash Course — Full Course Cram Sheet
1 / 9
Core Framework
- AbstractionThis is the art of hiding complexity. Think of it like driving a car: you use the steering wheel and pedals without needing to know exactly how the engine works. In Java, we do this by using objects and calling their methods.
- Algorithmic ThinkingThis is your core skill. It's about creating a clear, step-by-step recipe (an algorithm) to solve a problem. Every Free Response Question is a test of your ability to design a solid algorithm.
- Object-Oriented Programming (OOP)This is the foundation of Java. We model the world as a collection of
objects, which have data (attributes) and behaviors (methods). You'll be both a user of pre-made objects (likeString) and a creator of your own custom object types (classes). - Data StructuresYou need efficient ways to store and manage information. This course focuses on fundamental structures like
Arrays,ArrayLists, and2D Arrays, which are the building blocks for handling large amounts of data.
Unit Digest
Unit 1: Using Objects and Methods (15-25%)
- Must knowThe three primitive data types:
intfor integers,doublefor decimal numbers, andbooleanfortrue/false. You also need to be an expert user ofStringobjects and their methods (.length(),.substring(),.equals()). - Must knowHow to call methods on objects (
myString.length()) and from static classes (Math.random()). Understand the difference between a method that returns a value and one that isvoid. - Common trapInteger division. Remember,
7 / 2in Java is3, not3.5. The decimal part is simply dropped. If you need a decimal result, at least one of the numbers must be adouble(e.g.,7.0 / 2). - Common trapComparing
Stringobjects. Never use==to check if two strings have the same characters. Always use the.equals()method.==checks if they are the exact same object in memory, which is usually not what you want.
Unit 2: Selection and Iteration (25-35%)
- Must knowHow to control the flow of your program with
if-else if-elsestatements. Master writing complexbooleanexpressions using&&(AND),||(OR), and!(NOT). - Must knowThe two main types of loops:
forloops (when you know how many times you need to repeat) andwhileloops (when you need to repeat until a condition becomes false). - Common trap"Off-by-one" errors in loops. If you're looping through an array of length 10, your loop condition should be
i < 10, which covers indices 0 through 9. A condition ofi <= 10will cause anArrayIndexOutOfBoundsException. - Common trapDe Morgan's Laws.
!(A && B)is the same as!A || !B. And!(A || B)is the same as!A && !B. The AP exam loves to test this, so make sure you can simplify these expressions.
Unit 3: Class Creation (10-18%)
- Must knowThe anatomy of a class:
privateinstance variables (the data),publicconstructors (how to create an object), andpublicmethods (the object's behaviors). - Must knowThe purpose of the
thiskeyword. It's used inside a class to refer to the current object. It's essential for distinguishing between an instance variable and a parameter with the same name (e.g.,this.name = name;). - Common trapForgetting to initialize all instance variables in the constructor. Every piece of data your object holds needs a starting value. If the instructions don't specify one, you should still assign a default (like 0,
null, orfalse). - Common trapStatic vs. instance.
staticvariables and methods belong to the class itself, not to any individual object.Math.random()is static. An object's specificgetScore()method is an instance method.
Unit 4: Data Collections (30-40%)
- Must knowThe difference between an
Arrayand anArrayList. Arrays have a fixed size set at creation (int[] nums = new int[10];).ArrayListscan grow and shrink dynamically. - Must knowHow to traverse (loop through) arrays and
ArrayListsto access each element. You need to be fluent with standard algorithms: finding a min/max, calculating a sum or average, searching for an element, and shifting elements. - Must knowHow to work with 2D arrays. Think of them as a grid or a spreadsheet. Access elements with
grid[row][col]. Traversing them requires a nested loop, with the outer loop for rows and the inner loop for columns. - Common trapSyntax confusion. It's
array.length(a property),myString.length()(a method), andmyList.size()(a method). Write this down and memorize it. Getting this wrong on an FRQ is an easy point to lose.
Cheat Sheet
| Category | Details |
|---|---|
| Exam Format | Section I: Multiple Choice - 40 Questions, 90 Minutes (50% of score) - Approx. 2.25 mins/question Section II: Free Response (FRQ) - 4 Questions, 90 Minutes (50% of score) - Approx. 22.5 mins/question |
| FRQ Question Types | 1. Methods & Control Structures: Writing methods using logic/loops. 2. Class: Writing an entire class from scratch. 3. Array/ArrayList: Writing methods involving 1D array/ ArrayList traversal and manipulation.4. 2D Array: Writing methods involving 2D array traversal. |
| Primitive Types | int (e.g., -5, 0, 120)double (e.g., -2.5, 0.0, 3.14)boolean (true, false) |
| Key Operators | Arithmetic: +, -, *, /, % (modulo/remainder)Relational: ==, !=, <, >, <=, >=Logical: && (AND), || (OR), ! (NOT) |
| Control Flow | if (condition) { ... } else if (condition) { ... } else { ... }for (int i = 0; i < limit; i++) { ... }while (condition) { ... }for (Type element : collection) { ... } (Enhanced for-each loop) |
String Methods |
int length()String substring(int from, int to) (to is exclusive)String substring(int from)int indexOf(String str)boolean equals(Object other)int compareTo(String other) |
Math Methods |
static int abs(int x)static double abs(double x)static double pow(double base, double exp)static double sqrt(double x)static double random() (returns [0.0, 1.0)) |
ArrayList Methods |
int size()boolean add(E obj)void add(int index, E obj)E get(int index)E set(int index, E obj)E remove(int index) |
Array vs. ArrayList |
Array: int[] arr = new int[5];- Fixed size - Access: arr[i]- Length: arr.lengthArrayList: ArrayList<Integer> list = new ArrayList<Integer>();- Dynamic size - Access: list.get(i)- Size: list.size() |
Exam Day Checklist
- Pencils and PensBring several sharpened #2 pencils for the multiple-choice section and a blue or black ink pen for the free-response section.
- Pace YourselfOn the MCQ section, don't get stuck. If a question is taking more than 2-3 minutes, mark it and come back. For the FRQs, you have about 22 minutes per question. If you finish one early, use that extra time on a harder one.
- Use the Scratch PaperFor FRQs, map out your logic before you start writing code. Trace your loops with sample values. For 2D array problems, draw a small grid to visualize what you're doing. This prevents so many simple mistakes.
- Partial Credit is Your FriendOn the FRQs, never leave a question blank. If you can't figure out the whole solution, write the parts you do know. Can you write the method signature? Can you set up the loop correctly? Can you handle a simple case? Write it all down.
- Read the FRQ CarefullyUnderline or circle exactly what the method needs to do, what its parameters are, and what it must
return. Pay close attention to any stated preconditions (e.g., "you can assume the array is not empty"). - Don't Sweat Minor SyntaxThe FRQ graders are looking for your algorithmic understanding, not perfect Java syntax. A missing semicolon is not a big deal. A flawed loop that goes out of bounds is. Focus on the logic.
- Check Your BoundsBefore you finalize any code with a loop, double-check your loop's starting condition, ending condition, and how you access array/
ArrayListelements.ArrayIndexOutOfBoundsExceptionis the most common FRQ error.
Quiz me — 27 cards
Tap a card to reveal the answer. Use this to self-test before the exam.
Abstraction
Abstraction — what's the key idea? (Core Framework)
Abstraction
This is the art of hiding complexity. Think of it like driving a car: you use the steering wheel and pedals without needing to know exactly how the engine works. In Java, we do this by using objects and calling their methods.
1 / 27
71 high-yield questions
Distributed across all units. Tap a choice to lock in your answer.
Question 1 of 71 · Unit 1 · EASY
Which of the following best describes the purpose of an API (Application Program Interface) in Java?
A.
It is a set of pre-written classes and methods that programmers can use to build applications.
B.
It is a tool used to compile Java source code into bytecode.
C.
It is a graphical user interface for interacting with Java applications.
D.
It is a debugging tool for identifying errors in Java programs.
Answer: A — An API provides a standardized way for different software components to communicate, offering ready-to-use functionalities. Choices B, C, and D describe a compiler, a GUI, and a debugger, respectively, which are distinct from an API's role.
Question 2 of 71 · Unit 1 · MEDIUM
Consider the following Java code snippet:
```java
double value = 10.5;
int result = (int) value / 2;
System.out.println(result);
```
What is printed to the console?
A.
5.25
B.
5
C.
5.0
D.
10
Answer: B — The `(int) value` cast truncates 10.5 to 10. Then, integer division `10 / 2` results in 5. The result is stored in an `int` variable, so no decimal part is retained or printed.
Question 3 of 71 · Unit 1 · EASY
Which of the following is a valid way to declare and initialize a `String` variable in Java?
A.
String message = 'Hello';
B.
String message = new String("Hello");
C.
string message = "Hello";
D.
String message = Hello;
Answer: B — Strings in Java are objects and are typically initialized with double quotes. Option B is a valid way using the `new` keyword, though `String message = "Hello";` is more common. Option A uses single quotes for a String, which is incorrect. Option C uses a lowercase 's' for String, which is incorrect. Option D treats 'Hello' as a variable name, not a string literal.
Question 4 of 71 · Unit 1 · EASY
What is the output of the following code segment?
```java
int x = 5;
x += 3;
x *= 2;
System.out.println(x);
```
A.
10
B.
11
C.
16
D.
20
Answer: C — Initially, `x` is 5. `x += 3` makes `x` equal to `5 + 3 = 8`. Then, `x *= 2` makes `x` equal to `8 * 2 = 16`. Therefore, 16 is printed.
Question 5 of 71 · Unit 1 · EASY
Which of the following data types has the largest range of values it can store?
A.
byte
B.
short
C.
int
D.
long
Answer: D — Among the primitive integer types, `long` has the largest range, followed by `int`, `short`, and `byte`. This is a fundamental concept of data type sizes in Java.
Question 6 of 71 · Unit 1 · MEDIUM
Consider the following code:
```java
int a = 7;
double b = 2.0;
double c = a / b;
System.out.println(c);
```
What is the output?
A.
3
B.
3.0
C.
3.5
D.
7.0
Answer: C — When an `int` is divided by a `double`, the `int` is promoted to a `double` before the division occurs. So, `7.0 / 2.0` results in `3.5`. This is an important concept of type promotion in mixed-type expressions.
Question 7 of 71 · Unit 1 · EASY
What is the primary purpose of comments in Java code?
A.
To execute specific parts of the code conditionally.
B.
To provide explanations and documentation for human readers.
C.
To define new variables and data types.
D.
To optimize the code for faster execution.
Answer: B — Comments are ignored by the compiler and serve solely to improve code readability and maintainability by explaining logic, purpose, or complex sections to other developers or the future self. They do not affect code execution or performance.
Question 8 of 71 · Unit 1 · MEDIUM
Given the following code:
```java
String s1 = "hello";
String s2 = "world";
String s3 = s1 + s2;
System.out.println(s3.length());
```
What is printed to the console?
A.
5
B.
10
C.
11
D.
12
Answer: B — `s1 + s2` concatenates the strings to form "helloworld". The `length()` method returns the number of characters in the string. "helloworld" has 10 characters.
Question 9 of 71 · Unit 1 · EASY
Which of the following is NOT a primitive data type in Java?
A.
boolean
B.
char
C.
String
D.
double
Answer: C — `String` is a class in Java, not a primitive data type. `boolean`, `char`, and `double` are all primitive data types.
Question 10 of 71 · Unit 1 · HARD
What is the result of the following expression?
```java
(double) (5 / 2) + 0.5
```
A.
2.0
B.
2.5
C.
3.0
D.
3.5
Answer: B — First, `5 / 2` performs integer division, resulting in `2`. Then, `(double) 2` casts it to `2.0`. Finally, `2.0 + 0.5` results in `2.5`. Students often mistakenly think the cast applies before the division.
Question 11 of 71 · Unit 1 · EASY
Which of the following is the correct way to import a class named `Scanner` from the `java.util` package?
A.
import Scanner from java.util;
B.
import java.util.Scanner;
C.
include java.util.Scanner;
D.
java.util.Scanner;
Answer: B — The correct syntax for importing a specific class in Java is `import packageName.ClassName;`. Option B follows this syntax. The other options use incorrect keywords or syntax.
Question 12 of 71 · Unit 1 · EASY
What is the value of `x` after the following operations?
```java
int x = 10;
x %= 3;
```
A.
0
B.
1
C.
2
D.
3
Answer: B — The `%` operator calculates the remainder of a division. `10 % 3` means 10 divided by 3 is 3 with a remainder of 1. So, `x` becomes 1.
Question 13 of 71 · Unit 1 · MEDIUM
Which of the following statements about `final` variables in Java is true?
A.
A `final` variable must be initialized when it is declared.
B.
The value of a `final` variable can be changed after it is initialized.
C.
A `final` variable can only store primitive data types.
D.
A `final` variable is always a constant.
Answer: D — A `final` variable, once initialized, cannot have its value reassigned, effectively making it a constant. While it often is initialized upon declaration, it can also be initialized in a constructor or initializer block. It can store any data type, not just primitives. Its value cannot be changed after initialization.
Question 14 of 71 · Unit 2 · EASY
What will be the output of the following code segment?
```java
int a = 10;
int b = 5;
if (a > b) {
System.out.print("A");
}
else {
System.out.print("B");
}
System.out.print("C");
```
A.
A
B.
AC
C.
B
D.
BC
Answer: B — Since `a` (10) is greater than `b` (5), the condition `a > b` is true. Therefore, "A" is printed. After the `if-else` block, "C" is always printed. So the output is "AC".
Question 15 of 71 · Unit 2 · MEDIUM
Which of the following boolean expressions is equivalent to `!(A && B)`?
A.
`!A || !B`
B.
`!A && !B`
C.
`A || B`
D.
`A && !B`
Answer: A — This is De Morgan's Law. The negation of a conjunction (`&&`) is the disjunction (`||`) of the negations. `!(A && B)` is equivalent to `!A || !B`. This is a common concept in boolean logic.
Question 16 of 71 · Unit 2 · MEDIUM
Consider the following code segment:
```java
int x = 5;
int y = 10;
if (x > 0 && y < 10) {
System.out.print("One");
}
else if (x < 10 || y == 10) {
System.out.print("Two");
}
else {
System.out.print("Three");
}
```
What is printed to the console?
A.
One
B.
Two
C.
Three
D.
Nothing is printed.
Answer: B — The first condition `(x > 0 && y < 10)` is `(true && false)`, which is `false`. The second condition `(x < 10 || y == 10)` is `(true || true)`, which is `true`. Therefore, "Two" is printed.
Question 17 of 71 · Unit 2 · EASY
How many times will the loop execute?
```java
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
```
A.
0
B.
4
C.
5
D.
6
Answer: C — The loop starts with `i = 0` and continues as long as `i < 5`. The values of `i` will be 0, 1, 2, 3, 4. When `i` becomes 5, the condition `i < 5` is false, and the loop terminates. This results in 5 iterations.
Question 18 of 71 · Unit 2 · EASY
What is the output of the following code?
```java
int count = 0;
while (count < 3) {
System.out.print(count + " ");
count++;
}
```
A.
0 1 2
B.
0 1 2 3
C.
1 2 3
D.
Nothing, it's an infinite loop.
Answer: A — The loop starts with `count = 0`. It prints 0, increments to 1. Prints 1, increments to 2. Prints 2, increments to 3. Then `count < 3` (3 < 3) is false, and the loop terminates. So, "0 1 2 " is printed.
Question 19 of 71 · Unit 2 · MEDIUM
Which of the following `if` statements correctly checks if an integer `num` is between 10 (inclusive) and 20 (exclusive)?
A.
`if (num >= 10 && num < 20)`
B.
`if (num > 10 && num <= 20)`
C.
`if (num >= 10 || num < 20)`
D.
`if (num > 10 || num < 20)`
Answer: A — To be between 10 inclusive and 20 exclusive, `num` must be greater than or equal to 10 AND less than 20. The `&&` operator is crucial here to ensure both conditions are met. `||` would allow numbers outside the range.
Question 20 of 71 · Unit 2 · MEDIUM
What is the output of the following nested loop?
```java
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("*");
}
System.out.println();
}
```
A.
***
***
B.
*
**
***
C.
******
D.
***
Answer: A — The outer loop runs twice (for `i=0` and `i=1`). For each iteration of the outer loop, the inner loop runs three times, printing three asterisks. After the inner loop completes, `System.out.println()` moves to the next line. So, it prints three asterisks on the first line, then three asterisks on the second line.
Question 21 of 71 · Unit 2 · HARD
Given the boolean variables `p = true` and `q = false`, what is the value of `(p && !q) || (!p && q)`?
A.
true
B.
false
C.
Compilation Error
D.
Runtime Error
Answer: A — Substitute the values: `(true && !false) || (!true && false)` becomes `(true && true) || (false && false)`. This simplifies to `true || false`, which evaluates to `true`. This expression is the XOR (exclusive OR) logical operation.
Question 22 of 71 · Unit 2 · MEDIUM
Which of the following is an example of an infinite loop?
A.
`for (int i = 0; i < 10; i--)`
B.
`while (true)`
C.
`for (int i = 0; i < 10; i++)`
D.
`int x = 0; while (x < 5) { x++; }`
Answer: B — A `while (true)` loop's condition is always true, so it will never terminate unless explicitly broken out of. Option A is an infinite loop if `i` starts at 0 and decrements, making `i < 10` always true for positive `i` and then for negative `i`. However, `while(true)` is the most direct and common example of an infinite loop. Option C and D are finite loops.
Question 23 of 71 · Unit 2 · MEDIUM
What is the output of the following code?
```java
int num = 4;
if (num % 2 == 0) {
if (num > 5) {
System.out.println("A");
} else {
System.out.println("B");
}
} else {
System.out.println("C");
}
```
A.
A
B.
B
C.
C
D.
Nothing
Answer: B — First, `num % 2 == 0` (4 % 2 == 0) is true. This enters the outer `if` block. Then, `num > 5` (4 > 5) is false. So, the `else` part of the inner `if` block is executed, printing "B".
Question 24 of 71 · Unit 2 · EASY
Which of the following is NOT a valid relational operator in Java?
A.
==
B.
!=
C.
=>
D.
<=
Answer: C — The relational operators in Java are `==` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than or equal to), and `>=` (greater than or equal to). `=>` is not a valid operator; it should be `>=`.
Question 25 of 71 · Unit 2 · HARD
Consider the following code segment:
```java
int k = 0;
for (int i = 0; i < 5; i++) {
for (int j = i; j < 3; j++) {
k++;
}
}
System.out.println(k);
```
What is the final value of `k`?
A.
3
B.
6
C.
9
D.
15
Answer: B — Let's trace:
- `i = 0`: `j` goes from 0 to 2 (0, 1, 2) -> `k` increments 3 times.
- `i = 1`: `j` goes from 1 to 2 (1, 2) -> `k` increments 2 times.
- `i = 2`: `j` goes from 2 to 2 (2) -> `k` increments 1 time.
- `i = 3`: `j` goes from 3 to 2 (loop does not run) -> `k` increments 0 times.
- `i = 4`: `j` goes from 4 to 2 (loop does not run) -> `k` increments 0 times.
Total increments: 3 + 2 + 1 = 6. So `k` is 6.
Question 26 of 71 · Unit 2 · MEDIUM
Which of the following statements is true about the `switch` statement in Java?
A.
It can be used with `double` or `boolean` types.
B.
The `break` statement is optional and only used for optimization.
C.
The `default` case is mandatory in every `switch` statement.
D.
It provides a way to execute different code blocks based on the value of a single variable.
Answer: D — The `switch` statement allows selection among many alternatives based on the value of an expression. It cannot be used with `double` or `boolean` (only `byte`, `short`, `char`, `int`, `String`, or enums). The `break` statement is crucial to prevent 'fall-through' to subsequent cases, not just for optimization. The `default` case is optional.
Question 27 of 71 · Unit 2 · EASY
What is the output of the following code?
```java
int x = 1;
int y = 2;
if (x == 1) {
if (y == 2) {
System.out.println("A");
} else {
System.out.println("B");
}
} else {
System.out.println("C");
}
```
A.
A
B.
B
C.
C
D.
Nothing
Answer: A — The condition `x == 1` is true. Inside this block, the condition `y == 2` is also true. Therefore, "A" is printed.
Question 28 of 71 · Unit 3 · EASY
Which of the following is the primary purpose of a constructor in a Java class?
A.
To define the behavior of an object through methods.
B.
To create a new instance of a class and initialize its instance variables.
C.
To declare static variables that belong to the class.
D.
To destroy an object when it is no longer needed.
Answer: B — Constructors are special methods used to create new objects (instances) of a class and initialize their state (instance variables). Methods define behavior, static variables belong to the class, and garbage collection handles object destruction.
Question 29 of 71 · Unit 3 · EASY
Consider a class `Car` with an instance variable `speed`. Which of the following is the correct way to declare a private instance variable `speed` of type `int`?
A.
public int speed;
B.
private int speed;
C.
static int speed;
D.
int speed();
Answer: B — Instance variables are typically declared with an access modifier (like `private`) followed by the data type and variable name. `private` restricts access to within the class. `public` allows access from anywhere. `static` makes it a class variable. `int speed()` declares a method.
Question 30 of 71 · Unit 3 · MEDIUM
What is the scope of a local variable declared inside a method?
A.
Throughout the entire class.
B.
Only within the method where it is declared.
C.
Only within the block (e.g., `if` statement, loop) where it is declared.
D.
Globally accessible by any part of the program.
Answer: C — Local variables are accessible only within the block of code (method, loop, `if` statement) where they are declared. This is a fundamental concept of variable scope.
Question 31 of 71 · Unit 3 · MEDIUM
Which of the following statements about `static` methods in Java is true?
A.
They can access instance variables directly.
B.
They must be called on an object instance.
C.
They belong to the class, not to a specific object.
D.
They can be overridden by subclasses.
Answer: C — Static methods belong to the class itself and are called using the class name. They cannot directly access instance variables because they are not associated with a specific object. They cannot be overridden (though they can be hidden).
Question 32 of 71 · Unit 3 · MEDIUM
Given a class `Dog` with a constructor `public Dog(String name)` and an instance variable `String dogName`, which of the following correctly initializes `dogName` in the constructor?
A.
`dogName = name;`
B.
`this.dogName = name;`
C.
`name = dogName;`
D.
Both A and B are correct.
Answer: D — Both `dogName = name;` and `this.dogName = name;` are correct ways to assign the parameter `name` to the instance variable `dogName`. `this.dogName` is preferred for clarity, especially if the parameter name matches the instance variable name, but in this case, `dogName = name;` also works because there's no ambiguity.
Question 33 of 71 · Unit 3 · EASY
What is the purpose of the `return` keyword in a non-void method?
A.
To terminate the program execution.
B.
To indicate that the method does not produce a result.
C.
To send a value back to the caller of the method.
D.
To declare a new variable within the method.
Answer: C — The `return` keyword in a non-void method is used to send a value of the specified return type back to the code that invoked the method. It also terminates the method's execution. Option B describes `void` methods, and A and D are incorrect.
Question 34 of 71 · Unit 3 · MEDIUM
Which of the following best describes encapsulation in object-oriented programming?
A.
The ability of an object to take on many forms.
B.
The mechanism of hiding the internal implementation details of an object and exposing only necessary functionalities.
C.
The process of creating new classes from existing classes.
D.
The concept of defining multiple methods with the same name but different parameters.
Answer: B — Encapsulation is the bundling of data (instance variables) and methods that operate on the data into a single unit (class), and restricting direct access to some of the object's components. This is often achieved using `private` access modifiers and public getter/setter methods.
Question 35 of 71 · Unit 3 · EASY
Consider a class `Point` with a method `public void move(int dx, int dy)`. If `p1` is an object of `Point`, which of the following is a valid call to the `move` method?
A.
Point.move(5, 10);
B.
move(p1, 5, 10);
C.
p1.move(5, 10);
D.
new Point().move(5, 10);
Answer: C — Since `move` is an instance method (not static), it must be called on an object instance. `p1.move(5, 10)` correctly calls the method on the `p1` object. Option A would be for a static method. Option B is incorrect syntax. Option D creates a new temporary object and calls move on it, which is valid but not necessarily on `p1`.
Question 36 of 71 · Unit 3 · MEDIUM
What happens if a class does not explicitly define any constructors?
A.
The program will not compile.
B.
The Java compiler automatically provides a default no-argument constructor.
C.
Objects of that class cannot be created.
D.
The class becomes an abstract class.
Answer: B — If no constructors are explicitly defined, the Java compiler automatically provides a public, no-argument default constructor. This allows objects of the class to be instantiated without arguments. If any constructor is defined, the default constructor is not provided.
Question 37 of 71 · Unit 3 · HARD
Which of the following is true about passing objects as parameters to methods in Java?
A.
Objects are passed by value, meaning a copy of the object is made.
B.
Objects are passed by reference, meaning the original object can be modified.
C.
Only primitive data types can be passed as parameters.
D.
A new object is always created inside the method when an object is passed.
Answer: B — In Java, all parameters are passed by value. However, for objects, the 'value' being passed is a copy of the reference to the object. This means both the original reference and the copied reference point to the same object in memory, allowing the object's state to be modified through the parameter. It's often referred to as 'pass-by-value of the reference'.
Question 38 of 71 · Unit 3 · EASY
What is the purpose of the `this` keyword in Java?
A.
To refer to the superclass of the current object.
B.
To declare a new instance variable.
C.
To refer to the current object itself.
D.
To call a static method from another class.
Answer: C — The `this` keyword is a reference to the current object. It is commonly used to distinguish between instance variables and local parameters with the same name, or to call another constructor from within the same class.
Question 39 of 71 · Unit 3 · HARD
Consider a class `Counter` with a `private static int count = 0;` and a method `public void increment() { count++; }`. If two `Counter` objects are created and `increment()` is called on each, what will be the value of `count`?
A.
0
B.
1
C.
2
D.
Compilation Error
Answer: C — Since `count` is a `static` variable, it belongs to the class, not to individual objects. Both `Counter` objects share the same `count` variable. Each call to `increment()` will modify this single `count`. So, after two increments, `count` will be 2.
Question 40 of 71 · Unit 4 · EASY
Given an array `int[] numbers = {1, 2, 3, 4, 5};`, what is the value of `numbers[2]`?
A.
1
B.
2
C.
3
D.
4
Answer: C — Array indices in Java are 0-based. So, `numbers[0]` is 1, `numbers[1]` is 2, and `numbers[2]` is 3.
Question 41 of 71 · Unit 4 · EASY
Which of the following is the correct way to declare an `ArrayList` that stores `String` objects?
A.
ArrayList<String> list = new ArrayList<String>();
B.
ArrayList list = new ArrayList();
C.
String[] list = new String[10];
D.
ArrayList<String> list = new ArrayList();
Answer: A — Option A uses the correct generic syntax for `ArrayList` declaration and instantiation. Option B is valid but uses raw types, which is generally discouraged. Option C declares a regular array, not an `ArrayList`. Option D is also valid due to type inference (diamond operator) but A is the most explicit correct form.
Question 42 of 71 · Unit 4 · MEDIUM
What will be the output of the following code segment?
```java
int[] arr = {10, 20, 30, 40};
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 30) {
break;
}
System.out.print(arr[i] + " ");
}
```
A.
10 20
B.
10 20 30
C.
10 20 30 40
D.
Nothing, compilation error.
Answer: A — The loop iterates through the array. When `i` is 0, `arr[0]` (10) is printed. When `i` is 1, `arr[1]` (20) is printed. When `i` is 2, `arr[2]` is 30. The `if` condition `arr[i] == 30` becomes true, and the `break` statement terminates the loop immediately. So, only "10 20 " is printed.
Question 43 of 71 · Unit 4 · MEDIUM
Given an `ArrayList<Integer> nums = new ArrayList<Integer>();` and `nums.add(10); nums.add(20); nums.add(30);`, what is the result of `nums.remove(1);`?
A.
The list becomes `[10, 30]` and returns `20`.
B.
The list becomes `[10, 20]` and returns `30`.
C.
The list becomes `[20, 30]` and returns `10`.
D.
An `IndexOutOfBoundsException` is thrown.
Answer: A — The `remove(int index)` method removes the element at the specified index and shifts subsequent elements to the left. The initial list is `[10, 20, 30]`. Removing the element at index 1 (which is 20) results in the list `[10, 30]`, and the method returns the removed element, 20.
Question 44 of 71 · Unit 4 · EASY
Which of the following is a wrapper class for the primitive type `int`?
A.
Int
B.
Integer
C.
Number
D.
int
Answer: B — Wrapper classes provide a way to use primitive data types as objects. `Integer` is the wrapper class for `int`. `Int` (capital I) is not a valid class name in Java for this purpose. `Number` is an abstract superclass for numeric wrapper classes. `int` is the primitive type itself.
Question 45 of 71 · Unit 4 · MEDIUM
What is the output of the following code?
```java
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.print(name.substring(0, 1));
}
```
A.
ABC
B.
AliceBobCharlie
C.
A B C
D.
Error
Answer: A — The enhanced for loop iterates through each `name` in the `names` array. `name.substring(0, 1)` extracts the first character of each string. So, 'A' from "Alice", 'B' from "Bob", and 'C' from "Charlie" are printed consecutively.
Question 46 of 71 · Unit 4 · MEDIUM
When should an `ArrayList` be preferred over a traditional array in Java?
A.
When the size of the collection is fixed and known at compile time.
B.
When performance is the absolute highest priority for primitive data types.
C.
When the size of the collection needs to change dynamically during runtime.
D.
When storing a collection of primitive data types without autoboxing.
Answer: C — `ArrayList` is dynamic in size, meaning it can grow or shrink as elements are added or removed, making it suitable when the collection size is not fixed. Traditional arrays have a fixed size. Options A, B, and D describe scenarios where traditional arrays might be preferred.
Question 47 of 71 · Unit 4 · EASY
What is the result of attempting to access an array element at an index that is out of bounds (e.g., `arr[arr.length]` or `arr[-1]`)?
A.
A compilation error.
B.
A runtime error (`ArrayIndexOutOfBoundsException`).
C.
The program will crash without an error message.
D.
It will return a default value (e.g., 0 for `int` arrays).
Answer: B — Accessing an array with an invalid index (less than 0 or greater than or equal to `length`) results in a runtime error, specifically an `ArrayIndexOutOfBoundsException`. This is a common trap for students.
Question 48 of 71 · Unit 4 · HARD
Consider the following code:
```java
ArrayList<String> words = new ArrayList<String>();
words.add("apple");
words.add("banana");
words.add(1, "cherry");
System.out.println(words.get(2));
```
What is printed to the console?
A.
apple
B.
banana
C.
cherry
D.
IndexOutOfBoundsException
Answer: B — Initially, `words` is `["apple", "banana"]`. `words.add(1, "cherry")` inserts "cherry" at index 1, shifting "banana" to index 2. So, the list becomes `["apple", "cherry", "banana"]`. `words.get(2)` retrieves the element at index 2, which is "banana".
Question 49 of 71 · Unit 4 · MEDIUM
Which of the following is the correct way to initialize an array of 5 integers with all elements set to 0?
A.
`int[] arr = new int[5];`
B.
`int[] arr = {0, 0, 0, 0, 0};`
C.
`int arr[5];`
D.
Both A and B are correct.
Answer: D — Option A correctly declares and initializes an `int` array of size 5. By default, `int` arrays are initialized with 0s. Option B explicitly initializes the array with five 0s. Both achieve the desired outcome. Option C is C++ syntax, not Java.
Question 50 of 71 · Unit 4 · MEDIUM
What is the purpose of autoboxing and unboxing in Java?
A.
To automatically convert between different primitive types (e.g., `int` to `double`).
B.
To automatically convert between primitive types and their corresponding wrapper classes.
C.
To convert `String` objects to primitive types.
D.
To optimize memory usage for large collections.
Answer: B — Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes (e.g., `int` to `Integer`). Unboxing is the reverse conversion. This allows primitive values to be used where objects are expected (like in `ArrayLists`).
Question 51 of 71 · Unit 4 · EASY
Given `int[][] matrix = {{1, 2, 3}, {4, 5, 6}};`, what is the value of `matrix[1][0]`?
A.
1
B.
2
C.
4
D.
5
Answer: C — In a 2D array, `matrix[row][column]`. `matrix[1]` refers to the second row `{4, 5, 6}`. `matrix[1][0]` refers to the element at index 0 within that row, which is 4.
Question 52 of 71 · Unit 4 · EASY
Which of the following methods is used to get the number of elements in an `ArrayList`?
A.
length
B.
size()
C.
count()
D.
length()
Answer: B — For `ArrayList` objects, the `size()` method returns the number of elements. `length` is a field for arrays, and `length()` is a method for `String` objects.
Question 53 of 71 · Unit 4 · HARD
Consider the following code:
```java
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) == 20) {
numbers.remove(i);
}
}
System.out.println(numbers);
```
What is the output of this code?
A.
[10, 30]
B.
[10, 20, 30]
C.
[10]
D.
IndexOutOfBoundsException
Answer: A — Initially, `numbers` is `[10, 20, 30]`. When `i=0`, 10 is not 20. When `i=1`, 20 is found, `numbers.remove(1)` is called. The list becomes `[10, 30]`. The element 30 shifts from index 2 to index 1. The loop then increments `i` to 2. Now `i` (2) is equal to `numbers.size()` (2), so the loop terminates. The element 30 at the new index 1 is never checked. This is a common pitfall when removing elements while iterating forward through an `ArrayList`.
Question 54 of 71 · Unit 4 · EASY
Which loop is generally preferred for iterating through all elements of an `ArrayList` when the index is not needed?
A.
A `while` loop with a counter.
B.
A traditional `for` loop with an index.
C.
An enhanced `for` loop (for-each loop).
D.
A recursive method.
Answer: C — The enhanced `for` loop (or for-each loop) is designed for iterating over collections and arrays when you need to access each element but not its index. It makes the code more concise and readable for such scenarios. If you need the index, a traditional `for` loop is necessary.
Question 55 of 71 · Unit 4 · EASY
Given `int[] data = {1, 2, 3};`, what is the result of `data[data.length - 1]`?
A.
1
B.
2
C.
3
D.
ArrayIndexOutOfBoundsException
Answer: C — `data.length` is 3. So, `data.length - 1` is 2. `data[2]` refers to the element at index 2, which is 3. This is the correct way to access the last element of an array.
Question 56 of 71 · Unit 4 · MEDIUM
What is the primary difference between `==` and the `equals()` method when comparing two `String` objects?
A.
`==` compares the content of the strings, while `equals()` compares their memory addresses.
B.
`==` compares their memory addresses, while `equals()` compares the content of the strings.
C.
Both `==` and `equals()` always compare the content of the strings.
D.
Both `==` and `equals()` always compare their memory addresses.
Answer: B — For `String` objects (and other objects), `==` compares whether two references point to the exact same object in memory. The `equals()` method (overridden in `String`) compares the actual character sequences (content) of the strings. This is a crucial distinction for object comparison.
Question 57 of 71 · Unit 4 · MEDIUM
Which of the following is a valid way to create an `ArrayList` of `Double` objects with an initial capacity of 10?
A.
ArrayList<double> list = new ArrayList<double>(10);
B.
ArrayList<Double> list = new ArrayList<Double>(10);
C.
ArrayList<Double> list = new ArrayList(10);
D.
Double[] list = new Double[10];
Answer: B — `ArrayList` can only store objects, so `Double` (the wrapper class) must be used, not the primitive `double`. The constructor `new ArrayList<Double>(10)` correctly sets the initial capacity. Option C is also valid due to type inference but B is more explicit. Option A uses the primitive type, which is incorrect. Option D creates a regular array.
Question 58 of 71 · Unit 4 · EASY
Consider the following code:
```java
int[] values = {1, 2, 3, 4, 5};
int sum = 0;
for (int val : values) {
sum += val;
}
System.out.println(sum);
```
What is the output?
A.
1
B.
5
C.
15
D.
Error
Answer: C — The enhanced for loop iterates through each element in the `values` array. `sum` accumulates the value of each element: `0+1=1`, `1+2=3`, `3+3=6`, `6+4=10`, `10+5=15`. The final sum is 15.
Question 59 of 71 · Unit 4 · HARD
What is the result of `"hello".compareTo("world")`?
A.
A positive integer.
B.
A negative integer.
C.
Zero.
D.
A boolean value.
Answer: B — The `compareTo()` method compares two strings lexicographically. It returns a negative integer if the calling string comes before the argument string, zero if they are equal, and a positive integer if the calling string comes after. 'h' comes before 'w' in alphabetical order, so "hello" comes before "world", resulting in a negative integer.
Question 60 of 71 · Unit 4 · MEDIUM
Which of the following is true about `null` in Java when referring to an object reference?
A.
It refers to an empty string.
B.
It refers to an object that has been deallocated from memory.
C.
It indicates that an object reference variable does not currently point to any object.
D.
It is equivalent to the integer value 0.
Answer: C — `null` is a special literal that can be assigned to any object reference variable. It signifies that the variable currently holds no reference to any object. It is not an empty string, nor does it mean the object is deallocated (that's garbage collection), and it's not numerically equivalent to 0.
Question 61 of 71 · Unit 4 · MEDIUM
Given `ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C");`, what is the state of `list` after `list.set(1, "D");`?
A.
["A", "B", "C", "D"]
B.
["A", "D", "C"]
C.
["A", "B", "D"]
D.
["D", "B", "C"]
Answer: B — The `set(index, element)` method replaces the element at the specified position in this list with the specified element. Initially `list` is `["A", "B", "C"]`. `list.set(1, "D")` replaces the element at index 1 ("B") with "D". The list becomes `["A", "D", "C"]`.
Question 62 of 71 · Unit 4 · EASY
What is the purpose of the `Integer.parseInt(String s)` method?
A.
To convert an `int` to a `String`.
B.
To convert a `String` to an `int`.
C.
To convert an `Integer` object to an `int` primitive.
D.
To convert an `int` to an `Integer` object.
Answer: B — `Integer.parseInt(String s)` is a static method that parses the string argument as a signed decimal integer. It throws a `NumberFormatException` if the string does not contain a parsable integer. Option A is `String.valueOf()` or `Integer.toString()`. Options C and D are handled by autoboxing/unboxing.
Question 63 of 71 · Unit 4 · EASY
Consider a 2D array `int[][] grid = new int[3][4];`. How many elements does this array contain?
A.
3
B.
4
C.
7
D.
12
Answer: D — A 2D array `new int[rows][columns]` has `rows * columns` elements. In this case, `3 * 4 = 12` elements.
Question 64 of 71 · Unit 4 · MEDIUM
Which of the following is the most efficient way to add an element to the end of an `ArrayList`?
A.
Using `list.add(list.size(), element);`
B.
Using `list.add(element);`
C.
Using `list.set(list.size(), element);`
D.
Using a loop to find the next available index and then `list.add(index, element);`
Answer: B — The `list.add(element)` method is specifically designed to add an element to the end of the `ArrayList` and is the most efficient way to do so (amortized O(1)). `list.add(list.size(), element)` also works but is less direct. `list.set()` replaces an existing element, and a loop is unnecessary.
Question 65 of 71 · Unit 4 · MEDIUM
What is the output of the following code?
```java
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
int total = 0;
for (int[] row : matrix) {
total += row[0];
}
System.out.println(total);
```
A.
1
B.
9
C.
15
D.
Error
Answer: B — The outer enhanced for loop iterates through each row of the `matrix`. `row` will be `[1, 2]`, then `[3, 4]`, then `[5, 6]`. `row[0]` accesses the first element of each row. So, `total` becomes `1 + 3 + 5 = 9`.
Question 66 of 71 · Unit 4 · HARD
Which of the following statements about `ArrayList` and arrays is true regarding their memory usage?
A.
`ArrayList` always uses less memory than an array of the same number of elements.
B.
Arrays always use less memory than an `ArrayList` for the same number of elements.
C.
`ArrayList` stores primitive types directly, while arrays store wrapper objects.
D.
Memory usage depends entirely on the data types stored, not the collection type.
Answer: B — Arrays are more memory-efficient because they store primitive types directly and have a fixed overhead. `ArrayList` stores objects (wrapper classes for primitives) and has additional overhead for its internal array, capacity management, and object references. Option C is incorrect; `ArrayList` stores objects, and arrays store primitives or objects.
Question 67 of 71 · Unit 4 · EASY
Which of the following is a common ethical concern related to data collection and usage?
A.
Ensuring data is stored in a `String` array rather than an `ArrayList`.
B.
The potential for misuse of personal data and privacy violations.
C.
Optimizing search algorithms for faster data retrieval.
D.
Making sure all data is stored in a single, centralized database.
Answer: B — Ethical and social issues around data collection primarily revolve around privacy, security, consent, and the potential for discrimination or misuse of personal information. The other options relate to technical implementation or database design, not core ethical concerns.
Question 68 of 71 · Unit 4 · MEDIUM
Consider the following code:
```java
ArrayList<String> list = new ArrayList<String>();
list.add("cat");
list.add("dog");
list.add("mouse");
list.remove("dog");
System.out.println(list.size());
```
What is printed to the console?
A.
1
B.
2
C.
3
D.
Compilation Error
Answer: B — Initially, the list is `["cat", "dog", "mouse"]`. `list.remove("dog")` removes the first occurrence of the object "dog" from the list. The list becomes `["cat", "mouse"]`. The `size()` method then returns 2.
Question 69 of 71 · Unit 4 · EASY
What is the value of `arr.length` for the array `int[] arr = {10, 20, 30};`?
A.
0
B.
1
C.
3
D.
4
Answer: C — The `length` property of an array returns the number of elements in the array. This array has three elements: 10, 20, and 30. So, `arr.length` is 3.
Question 70 of 71 · Unit 4 · HARD
Which of the following is true about the `Integer` wrapper class?
A.
It is mutable, meaning its value can be changed after creation.
B.
It can store `null` as a value.
C.
It is less memory-efficient than the primitive `int`.
D.
Both B and C are true.
Answer: D — `Integer` objects are immutable; their value cannot change once created. However, an `Integer` *reference* can be `null`, unlike a primitive `int`. Wrapper objects (like `Integer`) inherently have more memory overhead than their primitive counterparts because they are objects. Therefore, both B and C are true.
Question 71 of 71 · Unit 4 · HARD
What is the output of the following code?
```java
int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length - 1; i++) {
nums[i] = nums[i+1];
}
for (int num : nums) {
System.out.print(num + " ");
}
```
A.
1 2 3 4 5
B.
2 3 4 5 5
C.
2 3 4 5 1
D.
1 1 2 3 4
Answer: B — The first loop shifts elements to the left: `nums[0]` becomes `nums[1]` (2), `nums[1]` becomes `nums[2]` (3), and so on. The last element `nums[4]` (which was 5) is never overwritten. So, the array becomes `[2, 3, 4, 5, 5]`. The second loop then prints these values.
11 AP-style free-response
Try the prompt yourself first. Then reveal the rubric + model solution.
FRQ #1 · Unit 1
Robot Movement Simulation
Prompt
A `Robot` object has two instance variables: `xPos` (an `int` representing its horizontal position) and `yPos` (an `int` representing its vertical position). Both are initialized to 0 when a `Robot` object is created. The `Robot` class also has a method `move(String direction)` which takes a string ("NORTH", "SOUTH", "EAST", or "WEST") and updates the robot's position accordingly. Moving NORTH increases `yPos` by 1, SOUTH decreases `yPos` by 1, EAST increases `xPos` by 1, and WEST decreases `xPos` by 1.
(a) Write the `Robot` class constructor and the `move` method. Ensure the `move` method handles invalid direction strings by doing nothing.
(b) In the `main` method of a separate class, create a `Robot` object, move it three steps EAST, two steps NORTH, and then one step SOUTH. Print its final `xPos` and `yPos`.
(a) Write the `Robot` class constructor and the `move` method. Ensure the `move` method handles invalid direction strings by doing nothing.
(b) In the `main` method of a separate class, create a `Robot` object, move it three steps EAST, two steps NORTH, and then one step SOUTH. Print its final `xPos` and `yPos`.
Show rubric & model solution
Rubric (10 points)
- 1 point: `Robot` class declaration and instance variables `xPos`, `yPos` declared as `int`.
- 1 point: Constructor correctly initializes `xPos` and `yPos` to 0.
- 1 point: `move` method signature is correct (`public void move(String direction)`).
- 1 point: Correctly uses `if/else if` or `switch` to check `direction` string.
- 1 point: Correctly updates `xPos` for EAST/WEST movements.
- 1 point: Correctly updates `yPos` for NORTH/SOUTH movements.
- 1 point: Handles invalid direction strings (does nothing).
- 1 point: Correctly creates a `Robot` object in `main`.
- 1 point: Correctly calls `move` methods with specified directions.
- 1 point: Correctly prints final `xPos` and `yPos`.
Model solution
public class Robot {
private int xPos;
private int yPos;
public Robot() {
xPos = 0;
yPos = 0;
}
public void move(String direction) {
if (direction.equals("NORTH")) {
yPos++;
} else if (direction.equals("SOUTH")) {
yPos--;
} else if (direction.equals("EAST")) {
xPos++;
} else if (direction.equals("WEST")) {
xPos--;
}
// Invalid directions are ignored as per problem statement
}
public int getXPos() {
return xPos;
}
public int getYPos() {
return yPos;
}
public static void main(String[] args) {
Robot myRobot = new Robot();
myRobot.move("EAST");
myRobot.move("EAST");
myRobot.move("EAST");
myRobot.move("NORTH");
myRobot.move("NORTH");
myRobot.move("SOUTH");
System.out.println("Final X Position: " + myRobot.getXPos()); // Expected: 3
System.out.println("Final Y Position: " + myRobot.getYPos()); // Expected: 1
}
}
FRQ #2 · Unit 2
Number Sequence Analysis
Prompt
Write a static method `analyzeSequence(int start, int end)` that takes two integers, `start` and `end`, and prints information about numbers in the range `[start, end]` (inclusive). Assume `start` is always less than or equal to `end`.
The method should:
(a) Print all numbers in the range that are divisible by 3 but not by 5.
(b) Count how many numbers in the range are prime.
(c) Return the sum of all even numbers in the range.
For part (b), you may assume the existence of a helper method `isPrime(int num)` that returns `true` if `num` is prime and `false` otherwise. You do not need to implement `isPrime`.
The method should:
(a) Print all numbers in the range that are divisible by 3 but not by 5.
(b) Count how many numbers in the range are prime.
(c) Return the sum of all even numbers in the range.
For part (b), you may assume the existence of a helper method `isPrime(int num)` that returns `true` if `num` is prime and `false` otherwise. You do not need to implement `isPrime`.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static int analyzeSequence(int start, int end)`.
- 1 point: Correct loop structure to iterate from `start` to `end` (inclusive).
- 1 point: Correct condition for divisibility by 3 and not by 5 (`num % 3 == 0 && num % 5 != 0`).
- 1 point: Correctly prints numbers satisfying the condition in (a).
- 1 point: Correctly initializes and updates a counter for prime numbers.
- 1 point: Correctly calls `isPrime(num)` for each number in the loop.
- 1 point: Correctly initializes and updates a sum for even numbers.
- 1 point: Correct condition for even numbers (`num % 2 == 0`).
- 1 point: Correctly returns the sum of even numbers.
- 1 point: Prints the count of prime numbers after the loop.
Model solution
public class SequenceAnalyzer {
// Assume this helper method exists and works correctly
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
public static int analyzeSequence(int start, int end) {
System.out.println("Numbers divisible by 3 but not by 5:");
int primeCount = 0;
int evenSum = 0;
for (int i = start; i <= end; i++) {
// Part (a): Divisible by 3 but not by 5
if (i % 3 == 0 && i % 5 != 0) {
System.out.print(i + " ");
}
// Part (b): Count prime numbers
if (isPrime(i)) {
primeCount++;
}
// Part (c): Sum of even numbers
if (i % 2 == 0) {
evenSum += i;
}
}
System.out.println(); // New line after printing numbers
System.out.println("Number of primes in the range: " + primeCount);
return evenSum;
}
public static void main(String[] args) {
// Example usage:
int sumOfEvens = analyzeSequence(1, 20);
System.out.println("Sum of even numbers: " + sumOfEvens); // Expected: 110
System.out.println("\nAnother example:");
sumOfEvens = analyzeSequence(10, 30);
System.out.println("Sum of even numbers: " + sumOfEvens); // Expected: 220
}
}
FRQ #3 · Unit 3
Book Class Design
Prompt
Design a `Book` class that represents a book in a library system. Each `Book` object should store the following information:
- `title` (String)
- `author` (String)
- `isbn` (String)
- `isAvailable` (boolean, true if available, false if checked out)
(a) Write the complete `Book` class, including:
- A constructor that takes `title`, `author`, and `isbn` as parameters and initializes `isAvailable` to `true`.
- Accessor (getter) methods for `title`, `author`, and `isbn`.
- A mutator (setter) method for `isAvailable` called `setCheckedOut(boolean checkedOut)`.
- A `toString()` method that returns a string representation of the book in the format: "Title: [title], Author: [author], ISBN: [isbn], Available: [true/false]".
(b) In a separate `Library` class, write a `main` method that creates two `Book` objects, checks out one of them, and then prints the details of both books using their `toString()` methods.
- `title` (String)
- `author` (String)
- `isbn` (String)
- `isAvailable` (boolean, true if available, false if checked out)
(a) Write the complete `Book` class, including:
- A constructor that takes `title`, `author`, and `isbn` as parameters and initializes `isAvailable` to `true`.
- Accessor (getter) methods for `title`, `author`, and `isbn`.
- A mutator (setter) method for `isAvailable` called `setCheckedOut(boolean checkedOut)`.
- A `toString()` method that returns a string representation of the book in the format: "Title: [title], Author: [author], ISBN: [isbn], Available: [true/false]".
(b) In a separate `Library` class, write a `main` method that creates two `Book` objects, checks out one of them, and then prints the details of both books using their `toString()` methods.
Show rubric & model solution
Rubric (10 points)
- 1 point: `Book` class declaration with private instance variables `title`, `author`, `isbn` (String) and `isAvailable` (boolean).
- 1 point: Constructor signature is correct (`public Book(String title, String author, String isbn)`).
- 1 point: Constructor correctly initializes all instance variables, setting `isAvailable` to `true`.
- 1 point: Correct implementation of getter methods for `title`, `author`, `isbn`.
- 1 point: Correct implementation of `setCheckedOut(boolean checkedOut)` method.
- 1 point: Correct `toString()` method signature and returns a `String`.
- 1 point: `toString()` method includes all instance variable values in the specified format.
- 1 point: `main` method in `Library` class correctly creates two `Book` objects.
- 1 point: `main` method correctly calls `setCheckedOut` on one book.
- 1 point: `main` method correctly prints both book objects using `toString()`.
Model solution
// Book.java
public class Book {
private String title;
private String author;
private String isbn;
private boolean isAvailable;
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.isAvailable = true; // Initially available
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getIsbn() {
return isbn;
}
public boolean isAvailable() { // Custom getter for boolean, common practice
return isAvailable;
}
public void setCheckedOut(boolean checkedOut) {
this.isAvailable = !checkedOut;
}
@Override
public String toString() {
return "Title: " + title + ", Author: " + author + ", ISBN: " + isbn + ", Available: " + isAvailable;
}
}
// Library.java
public class Library {
public static void main(String[] args) {
Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565");
Book book2 = new Book("1984", "George Orwell", "978-0451524935");
System.out.println("Before checkout:");
System.out.println(book1);
System.out.println(book2);
book1.setCheckedOut(true); // Check out book1
System.out.println("\nAfter checkout:");
System.out.println(book1);
System.out.println(book2);
}
}
FRQ #4 · Unit 4
Array Manipulation
Prompt
Write a static method `processArray(int[] arr)` that takes an array of integers as a parameter. The method should perform the following operations:
(a) Find and print the maximum value in the array.
(b) Count and print how many times the number 7 appears in the array.
(c) Replace all negative numbers in the array with 0.
(d) Return the modified array.
Example: If `arr` is `{1, -5, 7, 10, -2, 7, 0}`, after calling `processArray(arr)`, it should print `Max value: 10`, `Count of 7s: 2`, and return `{1, 0, 7, 10, 0, 7, 0}`.
(a) Find and print the maximum value in the array.
(b) Count and print how many times the number 7 appears in the array.
(c) Replace all negative numbers in the array with 0.
(d) Return the modified array.
Example: If `arr` is `{1, -5, 7, 10, -2, 7, 0}`, after calling `processArray(arr)`, it should print `Max value: 10`, `Count of 7s: 2`, and return `{1, 0, 7, 10, 0, 7, 0}`.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static int[] processArray(int[] arr)`.
- 1 point: Correctly initializes `maxVal` and iterates through the array to find the maximum.
- 1 point: Correctly prints the maximum value.
- 1 point: Correctly initializes `sevenCount` and iterates through the array to count 7s.
- 1 point: Correctly prints the count of 7s.
- 1 point: Correctly iterates through the array to modify negative numbers.
- 1 point: Correctly replaces negative numbers with 0.
- 1 point: Returns the modified array.
- 1 point: `main` method (or test code) correctly calls `processArray`.
- 1 point: `main` method (or test code) correctly prints the modified array.
Model solution
import java.util.Arrays;
public class ArrayProcessor {
public static int[] processArray(int[] arr) {
if (arr == null || arr.length == 0) {
System.out.println("Array is empty or null.");
return arr;
}
// Part (a): Find maximum value
int maxVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
System.out.println("Max value: " + maxVal);
// Part (b): Count occurrences of 7
int sevenCount = 0;
for (int num : arr) {
if (num == 7) {
sevenCount++;
}
}
System.out.println("Count of 7s: " + sevenCount);
// Part (c): Replace negative numbers with 0
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
arr[i] = 0;
}
}
// Part (d): Return the modified array
return arr;
}
public static void main(String[] args) {
int[] myArray = {1, -5, 7, 10, -2, 7, 0, 15, -3};
System.out.println("Original array: " + Arrays.toString(myArray));
int[] modifiedArray = processArray(myArray);
System.out.println("Modified array: " + Arrays.toString(modifiedArray));
// Expected output for modifiedArray: [1, 0, 7, 10, 0, 7, 0, 15, 0]
int[] emptyArray = {};
processArray(emptyArray);
int[] anotherArray = { -1, -2, -3 };
System.out.println("\nOriginal array: " + Arrays.toString(anotherArray));
modifiedArray = processArray(anotherArray);
System.out.println("Modified array: " + Arrays.toString(modifiedArray));
}
}
FRQ #5 · Unit 1
Temperature Converter
Prompt
Write a program that converts a temperature from Fahrenheit to Celsius. The program should:
(a) Declare a `double` variable for Fahrenheit temperature and initialize it to `68.0`.
(b) Declare a `double` variable for Celsius temperature.
(c) Calculate the Celsius temperature using the formula: `C = (F - 32) * 5 / 9`.
(d) Print both the Fahrenheit and Celsius temperatures, formatted to two decimal places. Use `System.out.printf()` for formatting.
Example Output:
`Fahrenheit: 68.00`
`Celsius: 20.00`
(a) Declare a `double` variable for Fahrenheit temperature and initialize it to `68.0`.
(b) Declare a `double` variable for Celsius temperature.
(c) Calculate the Celsius temperature using the formula: `C = (F - 32) * 5 / 9`.
(d) Print both the Fahrenheit and Celsius temperatures, formatted to two decimal places. Use `System.out.printf()` for formatting.
Example Output:
`Fahrenheit: 68.00`
`Celsius: 20.00`
Show rubric & model solution
Rubric (7 points)
- 1 point: Correctly declares `fahrenheit` as `double` and initializes it to `68.0`.
- 1 point: Correctly declares `celsius` as `double`.
- 1 point: Correctly applies the conversion formula `(fahrenheit - 32) * 5 / 9`.
- 1 point: Uses `System.out.printf()` for output.
- 1 point: Correctly formats Fahrenheit temperature to two decimal places (`%.2f`).
- 1 point: Correctly formats Celsius temperature to two decimal places (`%.2f`).
- 1 point: Prints both Fahrenheit and Celsius values with appropriate labels.
Model solution
public class TemperatureConverter {
public static void main(String[] args) {
// (a) Declare and initialize Fahrenheit temperature
double fahrenheit = 68.0;
// (b) Declare Celsius temperature variable
double celsius;
// (c) Calculate Celsius temperature
celsius = (fahrenheit - 32) * 5 / 9;
// (d) Print both temperatures, formatted to two decimal places
System.out.printf("Fahrenheit: %.2f\n", fahrenheit);
System.out.printf("Celsius: %.2f\n", celsius);
}
}
FRQ #6 · Unit 2
Password Validator
Prompt
Write a static method `isValidPassword(String password)` that takes a `String` representing a password and returns `true` if the password meets the following criteria, and `false` otherwise:
1. It must be at least 8 characters long.
2. It must contain at least one uppercase letter.
3. It must contain at least one digit (0-9).
(a) Implement the `isValidPassword` method.
(b) In a `main` method, test `isValidPassword` with at least three different passwords: one valid, one invalid due to length, and one invalid due to missing a digit.
1. It must be at least 8 characters long.
2. It must contain at least one uppercase letter.
3. It must contain at least one digit (0-9).
(a) Implement the `isValidPassword` method.
(b) In a `main` method, test `isValidPassword` with at least three different passwords: one valid, one invalid due to length, and one invalid due to missing a digit.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static boolean isValidPassword(String password)`.
- 1 point: Correctly checks if password length is at least 8.
- 1 point: Initializes boolean flags for uppercase and digit found.
- 1 point: Uses a loop to iterate through password characters.
- 1 point: Correctly checks for an uppercase letter using `Character.isUpperCase()`.
- 1 point: Correctly checks for a digit using `Character.isDigit()`.
- 1 point: Correctly updates boolean flags within the loop.
- 1 point: Returns `true` only if all three conditions (length, uppercase, digit) are met.
- 1 point: `main` method correctly calls `isValidPassword` with a valid password.
- 1 point: `main` method correctly calls `isValidPassword` with at least two invalid passwords (one for length, one for missing digit).
Model solution
public class PasswordValidator {
public static boolean isValidPassword(String password) {
// 1. Check length
if (password.length() < 8) {
return false;
}
boolean hasUppercase = false;
boolean hasDigit = false;
// Iterate through characters to check for uppercase and digit
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch)) {
hasUppercase = true;
}
if (Character.isDigit(ch)) {
hasDigit = true;
}
}
// 2. Check for at least one uppercase letter
// 3. Check for at least one digit
return hasUppercase && hasDigit;
}
public static void main(String[] args) {
// Test cases
String validPass = "MyPass123";
String shortPass = "Pass1";
String noDigitPass = "MyPassword";
String noUpperPass = "mypass123";
String allGoodPass = "StrongP@ssword1";
System.out.println("\"" + validPass + "\" is valid: " + isValidPassword(validPass)); // Expected: true
System.out.println("\"" + shortPass + "\" is valid: " + isValidPassword(shortPass)); // Expected: false (length)
System.out.println("\"" + noDigitPass + "\" is valid: " + isValidPassword(noDigitPass)); // Expected: false (no digit)
System.out.println("\"" + noUpperPass + "\" is valid: " + isValidPassword(noUpperPass)); // Expected: false (no uppercase)
System.out.println("\"" + allGoodPass + "\" is valid: " + isValidPassword(allGoodPass)); // Expected: true
}
}
FRQ #7 · Unit 3
BankAccount Class
Prompt
Create a `BankAccount` class. Each `BankAccount` object should have an `accountNumber` (String) and a `balance` (double).
(a) Write the `BankAccount` class, including:
- A constructor that takes an `accountNumber` and an initial `balance`. Assume the initial balance is always non-negative.
- An accessor method `getAccountNumber()`.
- An accessor method `getBalance()`.
- A `deposit(double amount)` method that adds `amount` to the balance. Assume `amount` is always positive.
- A `withdraw(double amount)` method that subtracts `amount` from the balance. If the `amount` is greater than the current `balance`, the withdrawal should not occur, and the method should print an error message (e.g., "Insufficient funds."). Assume `amount` is always positive.
(b) In a `main` method, create a `BankAccount` object, deposit $100, attempt to withdraw $50, then attempt to withdraw $200. Print the balance after each operation.
(a) Write the `BankAccount` class, including:
- A constructor that takes an `accountNumber` and an initial `balance`. Assume the initial balance is always non-negative.
- An accessor method `getAccountNumber()`.
- An accessor method `getBalance()`.
- A `deposit(double amount)` method that adds `amount` to the balance. Assume `amount` is always positive.
- A `withdraw(double amount)` method that subtracts `amount` from the balance. If the `amount` is greater than the current `balance`, the withdrawal should not occur, and the method should print an error message (e.g., "Insufficient funds."). Assume `amount` is always positive.
(b) In a `main` method, create a `BankAccount` object, deposit $100, attempt to withdraw $50, then attempt to withdraw $200. Print the balance after each operation.
Show rubric & model solution
Rubric (10 points)
- 1 point: `BankAccount` class declaration with private instance variables `accountNumber` (String) and `balance` (double).
- 1 point: Constructor signature is correct (`public BankAccount(String accountNumber, double initialBalance)`).
- 1 point: Constructor correctly initializes `accountNumber` and `balance`.
- 1 point: Correct implementation of `getAccountNumber()` and `getBalance()` methods.
- 1 point: Correct implementation of `deposit(double amount)` (adds to balance).
- 1 point: Correct implementation of `withdraw(double amount)` method signature.
- 1 point: `withdraw` method correctly checks for `amount > balance`.
- 1 point: `withdraw` method prints error message if insufficient funds.
- 1 point: `withdraw` method correctly updates balance if sufficient funds.
- 1 point: `main` method correctly demonstrates deposit, successful withdraw, and unsuccessful withdraw, printing balance after each.
Model solution
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + String.format("%.2f", amount) + ". New balance: $" + String.format("%.2f", balance));
}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient funds. Cannot withdraw $" + String.format("%.2f", amount) + ". Current balance: $" + String.format("%.2f", balance));
} else {
balance -= amount;
System.out.println("Withdrew: $" + String.format("%.2f", amount) + ". New balance: $" + String.format("%.2f", balance));
}
}
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("12345-6789", 500.00);
System.out.println("Initial balance for account " + myAccount.getAccountNumber() + ": $" + String.format("%.2f", myAccount.getBalance()));
myAccount.deposit(100.00);
// Expected: Deposited: $100.00. New balance: $600.00
myAccount.withdraw(50.00);
// Expected: Withdrew: $50.00. New balance: $550.00
myAccount.withdraw(200.00);
// Expected: Withdrew: $200.00. New balance: $350.00
myAccount.withdraw(400.00);
// Expected: Insufficient funds. Cannot withdraw $400.00. Current balance: $350.00
System.out.println("Final balance: $" + String.format("%.2f", myAccount.getBalance()));
// Expected: Final balance: $350.00
}
}
FRQ #8 · Unit 4
ArrayList Operations
Prompt
Write a static method `manageInventory(ArrayList<String> inventory, String item, String operation)` that simulates managing a simple inventory list. The method takes an `ArrayList` of `String` objects representing inventory items, an `item` `String`, and an `operation` `String` ("ADD", "REMOVE", or "CHECK").
(a) If `operation` is "ADD", add the `item` to the `inventory` list. Print a confirmation message.
(b) If `operation` is "REMOVE", remove the first occurrence of `item` from the `inventory` list if it exists. Print a confirmation or an error message if the item is not found.
(c) If `operation` is "CHECK", print whether the `item` is currently in the `inventory` list.
(d) For any other `operation` string, print an "Invalid operation." message.
(e) In a `main` method, create an `ArrayList` of strings, then call `manageInventory` to:
- Add "Laptop"
- Add "Mouse"
- Check for "Laptop"
- Remove "Keyboard" (should show not found)
- Remove "Mouse"
- Check for "Mouse"
Print the `inventory` list after all operations.
(a) If `operation` is "ADD", add the `item` to the `inventory` list. Print a confirmation message.
(b) If `operation` is "REMOVE", remove the first occurrence of `item` from the `inventory` list if it exists. Print a confirmation or an error message if the item is not found.
(c) If `operation` is "CHECK", print whether the `item` is currently in the `inventory` list.
(d) For any other `operation` string, print an "Invalid operation." message.
(e) In a `main` method, create an `ArrayList` of strings, then call `manageInventory` to:
- Add "Laptop"
- Add "Mouse"
- Check for "Laptop"
- Remove "Keyboard" (should show not found)
- Remove "Mouse"
- Check for "Mouse"
Print the `inventory` list after all operations.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static void manageInventory(ArrayList<String> inventory, String item, String operation)`.
- 1 point: Correctly handles "ADD" operation using `inventory.add(item)`.
- 1 point: Prints confirmation for "ADD" operation.
- 1 point: Correctly handles "REMOVE" operation using `inventory.remove(item)`.
- 1 point: Prints confirmation for successful "REMOVE" operation.
- 1 point: Prints error message for unsuccessful "REMOVE" operation (item not found).
- 1 point: Correctly handles "CHECK" operation using `inventory.contains(item)`.
- 1 point: Prints appropriate message for "CHECK" operation (found/not found).
- 1 point: Correctly handles invalid `operation` string.
- 1 point: `main` method correctly demonstrates all specified operations and prints final list.
Model solution
import java.util.ArrayList;
import java.util.Arrays;
public class InventoryManager {
public static void manageInventory(ArrayList<String> inventory, String item, String operation) {
if (operation.equals("ADD")) {
inventory.add(item);
System.out.println("Added '" + item + "' to inventory.");
} else if (operation.equals("REMOVE")) {
if (inventory.remove(item)) { // remove returns true if item was found and removed
System.out.println("Removed '" + item + "' from inventory.");
} else {
System.out.println("Error: '" + item + "' not found in inventory for removal.");
}
} else if (operation.equals("CHECK")) {
if (inventory.contains(item)) {
System.out.println("Yes, '" + item + "' is in inventory.");
} else {
System.out.println("No, '" + item + "' is not in inventory.");
}
} else {
System.out.println("Invalid operation: " + operation);
}
}
public static void main(String[] args) {
ArrayList<String> myInventory = new ArrayList<>();
System.out.println("Initial inventory: " + myInventory);
manageInventory(myInventory, "Laptop", "ADD");
manageInventory(myInventory, "Mouse", "ADD");
System.out.println("Current inventory: " + myInventory);
manageInventory(myInventory, "Laptop", "CHECK");
manageInventory(myInventory, "Keyboard", "REMOVE"); // Not found
manageInventory(myInventory, "Mouse", "REMOVE");
manageInventory(myInventory, "Mouse", "CHECK"); // Not found now
System.out.println("\nFinal inventory: " + myInventory);
// Expected final inventory: [Laptop]
}
}
FRQ #9 · Unit 2
Nested Loop Pattern
Prompt
Write a static method `printPattern(int size)` that takes an integer `size` as a parameter and prints a right-aligned triangle pattern of asterisks. For example, if `size` is 4, the method should print:
```
*
**
***
****
```
Your solution must use nested `for` loops.
```
*
**
***
****
```
Your solution must use nested `for` loops.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static void printPattern(int size)`.
- 1 point: Outer loop iterates `size` times (for rows).
- 1 point: Inner loop for spaces iterates correctly (`size - i - 1` or similar logic).
- 1 point: Prints a single space for each iteration of the space loop.
- 1 point: Inner loop for asterisks iterates correctly (`i + 1` or similar logic).
- 1 point: Prints a single asterisk for each iteration of the asterisk loop.
- 1 point: Uses `System.out.println()` after inner loops to move to the next line.
- 1 point: Correct output for `size = 1`.
- 1 point: Correct output for `size = 4` (or similar example).
- 1 point: Uses nested `for` loops as required.
Model solution
public class PatternPrinter {
public static void printPattern(int size) {
for (int i = 0; i < size; i++) { // Outer loop for rows
// Inner loop for printing leading spaces
for (int j = 0; j < size - 1 - i; j++) {
System.out.print(" ");
}
// Inner loop for printing asterisks
for (int k = 0; k <= i; k++) {
System.out.print("*");
}
System.out.println(); // Move to the next line after each row
}
}
public static void main(String[] args) {
System.out.println("Pattern for size = 3:");
printPattern(3);
/* Expected:
*
**
***
*/
System.out.println("\nPattern for size = 5:");
printPattern(5);
/* Expected:
*
**
***
****
*****
*/
System.out.println("\nPattern for size = 1:");
printPattern(1);
/* Expected:
*
*/
}
}
FRQ #10 · Unit 3
Student Class with GPA
Prompt
Create a `Student` class to store information about a student. Each `Student` object should have a `name` (String), an `id` (String), and a `gpa` (double).
(a) Write the `Student` class, including:
- A constructor that takes `name` and `id` as parameters. The `gpa` should be initialized to `0.0`.
- Accessor (getter) methods for `name`, `id`, and `gpa`.
- A mutator (setter) method `updateGPA(double newGPA)` that updates the student's GPA. The method should ensure `newGPA` is between `0.0` and `4.0` (inclusive). If `newGPA` is outside this range, the GPA should not be updated, and an error message should be printed (e.g., "Invalid GPA value.").
- A `toString()` method that returns a string representation of the student in the format: "Name: [name], ID: [id], GPA: [gpa formatted to 2 decimal places]".
(b) In a `main` method, create a `Student` object, update its GPA twice (once with a valid value, once with an invalid value), and then print the student's details using `toString()`.
(a) Write the `Student` class, including:
- A constructor that takes `name` and `id` as parameters. The `gpa` should be initialized to `0.0`.
- Accessor (getter) methods for `name`, `id`, and `gpa`.
- A mutator (setter) method `updateGPA(double newGPA)` that updates the student's GPA. The method should ensure `newGPA` is between `0.0` and `4.0` (inclusive). If `newGPA` is outside this range, the GPA should not be updated, and an error message should be printed (e.g., "Invalid GPA value.").
- A `toString()` method that returns a string representation of the student in the format: "Name: [name], ID: [id], GPA: [gpa formatted to 2 decimal places]".
(b) In a `main` method, create a `Student` object, update its GPA twice (once with a valid value, once with an invalid value), and then print the student's details using `toString()`.
Show rubric & model solution
Rubric (10 points)
- 1 point: `Student` class declaration with private instance variables `name`, `id` (String) and `gpa` (double).
- 1 point: Constructor signature is correct (`public Student(String name, String id)`).
- 1 point: Constructor correctly initializes `name`, `id`, and `gpa` to `0.0`.
- 1 point: Correct implementation of getter methods for `name`, `id`, `gpa`.
- 1 point: Correct implementation of `updateGPA(double newGPA)` method signature.
- 1 point: `updateGPA` method correctly checks if `newGPA` is within `0.0` and `4.0` range.
- 1 point: `updateGPA` method updates `gpa` only if valid.
- 1 point: `updateGPA` method prints error message for invalid GPA.
- 1 point: Correct `toString()` method signature and returns a `String` with GPA formatted to 2 decimal places.
- 1 point: `main` method correctly creates a `Student` object, calls `updateGPA` with valid and invalid values, and prints using `toString()`.
Model solution
public class Student {
private String name;
private String id;
private double gpa;
public Student(String name, String id) {
this.name = name;
this.id = id;
this.gpa = 0.0; // Initial GPA
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public double getGpa() {
return gpa;
}
public void updateGPA(double newGPA) {
if (newGPA >= 0.0 && newGPA <= 4.0) {
this.gpa = newGPA;
System.out.println("GPA updated to: " + String.format("%.2f", newGPA));
} else {
System.out.println("Invalid GPA value: " + String.format("%.2f", newGPA) + ". GPA not updated.");
}
}
@Override
public String toString() {
return "Name: " + name + ", ID: " + id + ", GPA: " + String.format("%.2f", gpa);
}
public static void main(String[] args) {
Student student1 = new Student("Alice Smith", "A001");
System.out.println("Initial: " + student1);
student1.updateGPA(3.75);
System.out.println("After valid update: " + student1);
student1.updateGPA(4.5);
System.out.println("After invalid update attempt: " + student1);
student1.updateGPA(-0.5);
System.out.println("After another invalid update attempt: " + student1);
student1.updateGPA(2.90);
System.out.println("After another valid update: " + student1);
}
}
FRQ #11 · Unit 4
2D Array Processing
Prompt
Write a static method `processMatrix(int[][] matrix)` that takes a 2D array (matrix) of integers as a parameter. The method should perform the following operations:
(a) Print the sum of all elements in the matrix.
(b) Print the sum of elements in each row.
(c) Return a new 1D array where each element is the sum of the corresponding column in the original matrix.
Assume the matrix is not `null` and has at least one row and one column, and all rows have the same number of columns.
(a) Print the sum of all elements in the matrix.
(b) Print the sum of elements in each row.
(c) Return a new 1D array where each element is the sum of the corresponding column in the original matrix.
Assume the matrix is not `null` and has at least one row and one column, and all rows have the same number of columns.
Show rubric & model solution
Rubric (10 points)
- 1 point: Correct method signature `public static int[] processMatrix(int[][] matrix)`.
- 1 point: Correctly initializes `totalSum` for part (a).
- 1 point: Uses nested loops to iterate through all elements of the matrix.
- 1 point: Correctly calculates and prints `totalSum` (part a).
- 1 point: Correctly calculates and prints row sums (part b).
- 1 point: Correctly determines the number of columns for the column sums array.
- 1 point: Initializes the column sums array with correct size.
- 1 point: Correctly accumulates column sums within the nested loops.
- 1 point: Returns the correctly populated column sums array.
- 1 point: `main` method (or test code) correctly calls `processMatrix` and prints the returned column sums array.
Model solution
import java.util.Arrays;
public class MatrixProcessor {
public static int[] processMatrix(int[][] matrix) {
int totalSum = 0;
int numRows = matrix.length;
int numCols = matrix[0].length;
int[] colSums = new int[numCols]; // For part (c)
System.out.println("\nProcessing Matrix:");
for (int r = 0; r < numRows; r++) {
int rowSum = 0;
for (int c = 0; c < numCols; c++) {
int element = matrix[r][c];
totalSum += element;
rowSum += element;
colSums[c] += element; // Accumulate column sum
}
System.out.println("Sum of Row " + r + ": " + rowSum); // Part (b)
}
System.out.println("Total Sum of all elements: " + totalSum); // Part (a)
return colSums; // Part (c)
}
public static void main(String[] args) {
int[][] myMatrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[] columnSums = processMatrix(myMatrix);
System.out.println("Column Sums: " + Arrays.toString(columnSums));
// Expected output:
// Sum of Row 0: 6
// Sum of Row 1: 15
// Sum of Row 2: 24
// Total Sum of all elements: 45
// Column Sums: [12, 15, 18]
int[][] anotherMatrix = {
{10, 20},
{30, 40},
{50, 60}
};
columnSums = processMatrix(anotherMatrix);
System.out.println("Column Sums: " + Arrays.toString(columnSums));
// Expected output:
// Sum of Row 0: 30
// Sum of Row 1: 70
// Sum of Row 2: 110
// Total Sum of all elements: 210
// Column Sums: [90, 120]
}
}