Java from your first compile to recursion, taught in the four units of the 2025 College Board framework. Fifty-eight lessons follow the CED topic by topic, quote the required content, run every program through a real compiler, and end with six practice items each; every unit ends with ten exam-style multiple-choice questions on a code stimulus, and the free-response section holds eight full FRQ prompts with scoring notes and a canonical nine-point solution.
What this course covers, and how the exam weights it.
AP Computer Science A follows the four units of the 2025 College Board framework. Unit 4 (data collections, 30–40%) and Unit 2 (selection and iteration, 25–35%) carry most of the exam's weight, and the four free-response questions come from them in a fixed order: methods and control structures, class design, data analysis with an ArrayList, and a 2D array. Section I is 42 multiple-choice questions in 90 minutes for 55% of the score; Section II is those four free-response questions in 90 minutes for the other 45%, worth 7, 7, 5 and 6 points. The course has 58 lessons: 14 in Unit 1, 14 in Unit 2, 10 in Unit 3 and 20 in Unit 4. Each lesson quotes the CED's required content, shows Java that was compiled and run, traces it step by step, flags what the exam asks in an Exam focus box, and ends with six practice items with answers. Inheritance and overriding are outside the 2025 course, so this course does not teach them, and recursion is taught for tracing only because writing recursive code is also outside the exam. Every unit ends with a ten-question review in the exam's own multiple-choice style, and the FRQ section at the bottom of the outline holds eight prompts, two of each exam type, each with a coding space, the scoring notes, and the canonical solution explained point by point.
U1Using Objects and Methods15–25%
U2Selection and Iteration25–35%
U3Class Creation10–18%
U4Data Collections30–40%
All four units are open, 58 topics in all. Every topic opens with the method, worked examples, and a set of practice problems. Every problem has a full worked solution, so you can find the step where yours went wrong. Each unit closes with a ten-problem mixed review.
Free preview: all of Unit 1, its lessons and its review set,
is open to everyone with no account. Past that, a few more lessons open
for free, and a free account can start a free month of this course: no
card, every lesson and practice set open for 30 days. Grading of
written work and teacher review come with a paid plan.
An algorithm is a step-by-step process for finishing a task or solving a problem. You already follow algorithms all day: a recipe, the directions to a friend's house, the steps for long division. A program is an algorithm written in a language a computer will accept, and this course teaches that language: Java.
Two ideas make an algorithm precise. First, the steps are sequenced: they happen one at a time, in a defined order, and swapping two steps can change the result. Second, each step is exact enough that nobody has to guess what it means. "Add a little tip" is not a step a computer can follow; "multiply the bill by 0.15" is.
Required content · LO 1.1.A, LO 1.1.B, LO 1.1.C
Learning objectives.
1.1.A. Represent patterns and algorithms found in everyday life using written language or diagrams.
1.1.B. Explain the code compilation and execution process.
1.1.C. Identify types of programming errors.
Essential knowledge.
1.1.A.1. Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
1.1.A.2. Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.
1.1.B.1. Code can be written in any text editor; however, an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
1.1.B.2. A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.
1.1.C.1. A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
1.1.C.2. A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
1.1.C.3. A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
1.1.C.4. An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program’s execution.
Describing an algorithm before you code it
You can describe an algorithm in written language or in a diagram, and the exam expects both. A diagram often shows the order at a glance; the same steps in plain sentences are easier to turn into code line by line.
Figure 1.1. An algorithm drawn as a flowchart. Each box is one step, and the arrows fix the order: the tip must be computed before the total can use it.
Here is the same algorithm in written form.
Read the amount of the bill.
Compute the tip as the bill times 0.15.
Compute the total as the bill plus the tip.
Display the total.
Try swapping steps 2 and 3. The total would be computed before the tip exists, so the algorithm no longer does what you meant. That is what sequencing means: an order is part of the definition of the algorithm.
From source code to a running program
Java code can be written in any text editor, but programmers use an integrated development environment (IDE) because it bundles the tools you need to write, compile, and run code in one place. The path a Java program takes is always the same.
Figure 1.2. The compiler can stop a program before it starts; only the JVM can stop it while it runs. A logic error passes through both stages unnoticed.
You write source code in a file ending in .java.
The compiler (javac) checks that code against the rules of the language. If it finds a mistake it reports it and stops; nothing can run until every error it can detect is fixed.
If the code is acceptable, the compiler produces bytecode in a .class file.
The Java Virtual Machine (the JVM, started with java) runs the bytecode.
Every program on the exam sits inside a class, and execution begins at the first statement of main:
public class Main {
public static void main(String[] args) {
// statements run in order, top to bottom
}
}
The file is named after its class (Main.java). Statements end in semicolons and blocks are wrapped in braces. On the exam, snippets usually show only the statements; you can assume the class and main around them.
Four ways code goes wrong
The compiler can catch some mistakes and cannot catch others. The difference is the most tested idea in this lesson.
Kind of error
What is wrong
Who finds it
What you see
Syntax error
The code breaks a rule of the language (missing semicolon, misspelled keyword, wrong type)
The compiler
An error message with a line number; no .class file; the program never runs
Logic error
The algorithm is wrong, so the program runs and gives the wrong answer
You, by testing with data whose answer you already know
Output that is wrong but looks normal
Run-time error
The program breaks while it is running
The JVM, during the run
The program stops abnormally, often after printing some output
Exception
A kind of run-time error that the compiler could not foresee; it interrupts the normal flow of the program
The JVM
A named exception such as ArithmeticException and a message
The rows are not equal in how loudly they announce themselves. A syntax error shouts at compile time. An exception shouts at run time. A logic error says nothing at all, which is why testing matters: the only way to find it is to compare what the program did with what it should have done.
Worked example · a program that runs
Convert 21.5 degrees Celsius to Fahrenheit and print the result.
public class Main {
public static void main(String[] args) {
double celsius = 21.5;
double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
System.out.println(celsius + " C is " + fahrenheit + " F");
}
}
Compiled and run, it prints:
21.5 C is 70.7 F
Every statement executed once, top to bottom. The sequence matters: fahrenheit could not be computed before celsius had a value.
Worked example · the same program, one semicolon short
Delete the semicolon after 21.5 and compile again. The compiler stops and reports where it got lost.
public class Main {
public static void main(String[] args) {
double celsius = 21.5
System.out.println(celsius);
}
}
No .class file is produced, so nothing runs and nothing prints. The caret sits just after the last good token, so the problem is at the end of the line named, not the start of the next one. This is a syntax error.
Worked example · one program, two different errors
The compiler accepts the code below, so the problem cannot be a syntax error. It fails later.
int total = 120;
int count = 0;
System.out.println("Average: " + total / count);
Exception in thread "main" java.lang.ArithmeticException: / by zero
Integer division by zero cannot be checked in advance when the divisor is a variable, so the compiler lets it through and the JVM stops the run. This is a run-time error, specifically an exception.
Now a program that compiles, runs to the end, and is still wrong. The goal is the average of 4 and 10, which is 7.
int a = 4;
int b = 10;
System.out.println("Average: " + (a + b / 2));
Average: 9
The multiplication-and-division-first rule made b / 2 happen before the addition, so the algorithm computed 4 + 5. Nothing crashed and nothing was reported. Only a test whose answer you already knew (7) revealed it. This is a logic error.
Exam focus
Exam questions in this topic ask you to identify the kind of error from a description or a code segment, and to put algorithm steps in a correct order. Use who and when to decide: complaints before the program starts come from the compiler (syntax); complaints in the middle of a run come from the JVM (run-time or exception); wrong answers with no complaint are logic errors. On the free-response section, your code is read for whether it would compile, so unbalanced braces and missing semicolons matter even though a human grades it.
Practice
Which of the following is a syntax error?
A. int total = 10 / zero; // zero holds 0
B. int sum = a + b / 2; // meant (a + b) / 2
C. System.out.println("Done")
D. int count = 5;
Show answer
C. The statement is missing its closing semicolon, which breaks a rule of the language, so the compiler reports it before the program can run. A is a run-time error (an ArithmeticException when the division happens), B is a logic error (it compiles and runs but computes the wrong value), and D is correct code.
A program compiles without any message and prints Total: 40 for three items that cost 10, 20, and 30. What kind of error is this, and how would you find it?
Show answer
A logic error. The program ran to the end, so the compiler and the JVM had no complaint. You find it by testing with data whose answer you know: the three prices sum to 60, so 40 shows the algorithm is wrong.
Put these steps in an order that computes the area of a circle with radius 3.
1. Display area
2. Set area to 3.14 * radius * radius
3. Set radius to 3
Show answer
3, 2, 1. The radius must have a value before the area uses it, and the area must exist before it is displayed. The order is part of the algorithm.
The following is run. Name the kind of error and say whether any output appears.
int items = 0;
int people = 5;
System.out.println("Sharing...");
System.out.println(people / items);
Show answer
A run-time error, an ArithmeticException. The compiler accepts the code, so the first line prints Sharing..., and then the JVM stops the program at the division. Output appears before the failure.
Why do most programmers write Java in an IDE rather than a plain text editor?
Show answer
An IDE combines the tools for writing, compiling, and running code in one place, so a programmer can fix compiler errors and test the program without leaving the editor. A text editor can produce the same code, but it provides none of those tools.
True or false: the compiler detects every error in a program before it runs.
Show answer
False. The compiler detects errors in the rules of the language (syntax errors, and mismatches it can see). It cannot detect logic errors, and it cannot detect run-time errors such as dividing by a variable that holds zero, so those appear only when the program is tested or run.
A variable is a named storage location that holds a value. In Java every variable has a name and a data type, and the type is permanent: a variable declared to hold whole numbers holds whole numbers for its whole life. The compiler enforces that promise, which is why so many Java mistakes are caught before the program ever runs.
A data type is a set of values together with the operations you can perform on those values. Java sorts data types into two categories. Primitive types hold a single plain value. Reference types define objects, and a variable of a reference type holds a reference to an object stored elsewhere.
Required content · LO 1.2.A, LO 1.2.B
Learning objectives.
1.2.A. Identify the most appropriate data type category for a particular specification.
1.2.B. Develop code to declare variables to store numbers and Boolean values.
Essential knowledge.
1.2.A.1. A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
1.2.A.2. The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
1.2.A.3. A reference type is used to define objects that are not primitive types.
1.2.B.1. The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false. Outside the course: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam.
1.2.B.2. A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.
The three primitive types in this course
Type
Values
Examples of literals
Typical use
int
whole numbers, positive, negative, or zero
0, 42, -7
counting, indexes, ages, scores
double
real numbers, with a fractional part
3.14, -0.5, 2.0
measurements, averages, prices
boolean
exactly true or false
true, false
yes or no questions, conditions
7 and 7.0 are different values of different types. They print differently, they divide differently (Lesson 1.3 shows how), and they are stored differently. String is the reference type you meet first: a variable of type String holds a reference to a sequence of characters, and you write one in double quotes.
Declaring and initializing
A declaration gives a variable a type and a name. An initialization gives it its first value; you can do both in one statement.
int quantity = 3; // whole number
double unitPrice = 12.50; // number with a fractional part
boolean taxExempt = false; // exactly true or false
String itemName = "Notebook"; // reference type: a String object
Names follow rules and habits.
A name starts with a letter and contains letters, digits, and underscores. quantity and item2 are valid; 2ndItem is not.
A reserved word such as int, class, new, public, or return cannot be a name.
Names are case sensitive: total and Total are two different variables.
By convention names for variables use camelCase: unitPrice, not UnitPrice or unit_price.
The same name cannot be declared twice in the same block of code.
A variable of a primitive type holds the value itself. A variable of a reference type holds a reference, so it can also hold the special value null, meaning no object (Lesson 1.4 explains it).
Key idea · a variable holds one value at a time
A variable can change while the program runs, but it holds a single value at any moment. When a new value is stored, the old one is gone. The data type fixes what kind of value fits: an int variable cannot hold 3.5, and a boolean variable cannot hold 1.
Worked example · a receipt
Declare one variable of each type and print a receipt line for each.
Notice that 12.50 printed as 12.5. The trailing zero in the literal is formatting, not part of the value: a double stores a number, never a number of decimal places.
Worked example · choosing the type from a specification
For each quantity, choose the most appropriate type and write the declaration.
Quantity
Type
Declaration
Why
number of students in a class
int
int students = 24;
counted in whole units
the average of three test scores
double
double average = 87.5;
an average can have a fractional part
whether a door is locked
boolean
boolean locked = true;
exactly two possibilities
a person's name
String
String name = "Maya";
text, so a reference type
the number of miles driven, to the tenth
double
double miles = 12.4;
a measurement with a fractional part
The rule is: counted values are int; measured values are double; yes or no values are boolean; text is String.
Worked example · what the compiler refuses
Each line below breaks a rule, and the compiler rejects the program at that line.
public class Main {
public static void main(String[] args) {
int wholeNumber = 3.5;
}
}
Main.java:3: error: incompatible types: possible lossy conversion from double to int
int wholeNumber = 3.5;
^
1 error
A double value would lose its fractional part if it were forced into an int, so Java refuses to do it silently. A similar refusal happens for boolean flag = "yes"; (a String is not a boolean) and for int 2ndPlace = 2; (a name cannot start with a digit).
Exam focus
The exam asks you to pick the most appropriate data type for a given specification, so practice the counted, measured, yes or no, and text rule until it is automatic. It will also show code with a mismatch (a double assigned to an int, a String assigned to a boolean) and ask why it will not compile. Only int, double, and boolean are tested among primitive types; long, short, byte, float, and char are outside the course and the exam.
Practice
Which type is most appropriate for the number of tickets sold in a day?
Show answer
int. A count of tickets is a whole number, and no fractional ticket exists.
Which type is most appropriate for a student's grade point average such as 3.67?
Show answer
double. It is a real number with a fractional part.
Which declaration compiles?
A. int score = 9.5;
B. double score = 9;
C. boolean score = 1;
D. String score = 9;
Show answer
B. A whole number is accepted where a double is expected (the int 9 becomes 9.0), so B compiles. A would lose the fractional part, C stores an int in a boolean, and D stores a number where a String object is required.
What is printed?
int a = 7;
double b = 7.0;
System.out.println(a);
System.out.println(b);
Show answer
7 on one line and 7.0 on the next. The two variables hold values of different types, and a double always prints with a decimal point.
What is wrong with this program, and when does the problem show up?
int count = 1;
int count = 2;
Show answer
The name count is declared twice in the same block, so the compiler rejects the code. It is a syntax-level error found at compile time, before anything runs.
Which of these is a reference type: int, boolean, String, double?
Show answer
String. The other three are primitive types. A variable of type String holds a reference to a String object rather than the characters themselves.
A program is only useful if it can show you something and calculate something. This lesson covers both: the statements that display output, and the expressions that compute values from numbers and variables. Expressions are the core of every program in the course, and the exam tests them constantly, so the details matter: what division really does with whole numbers, what the remainder operator is for, and the order in which operators run.
Required content · LO 1.3.A, LO 1.3.B, LO 1.3.C
Learning objectives.
1.3.A. Develop code to generate output and determine the result that would be displayed.
1.3.B. Develop code to utilize string literals and determine the result of using string literals.
1.3.C. Develop code for arithmetic expressions and determine the result of these expressions.
Essential knowledge.
1.3.A.1. System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
1.3.B.1. A literal is the code representation of a fixed value.
1.3.B.2. A string literal is a sequence of characters enclosed in double quotes.
1.3.B.3. Escape sequences are special sequences of characters that can be included in a string. They start with a \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline \n.
1.3.C.1. Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
1.3.C.2. The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. X EXCLUSION STATEMENT—Expressions that result in special double values (e.g., infinities and NaN) are outside the scope of the AP Computer Science A course and exam.
1.3.C.3. When dividing numeric values that are both int values, the result is only the integer portion of the quotient. When dividing numeric values that use at least one double value, the result is the quotient.
1.3.C.4. The remainder operator % is used to compute the remainder when one number a is divided by another number b. X EXCLUSION STATEMENT—The use of values less than 0 for a and the use of values less than or equal to 0 for b is outside the scope of the AP Computer Science A course and exam.
1.3.C.5. Operators can be used to construct compound expressions. At compile time, numeric values are associated with operators according to operator precedence to determine how they are grouped. Parentheses can be used to modify operator precedence. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right.
1.3.C.6. An attempt to divide an integer by the integer zero will result in an ArithmeticException. X EXCLUSION STATEMENT—The use of dividing by zero when one numeric value is a double is outside the scope of the AP Computer Science A course and exam.
Displaying output
System.out.print and System.out.println both display what you give them. The only difference is the cursor: println moves it to a new line afterward, and print does not.
A literal is the code representation of a fixed value. A string literal is a sequence of characters enclosed in double quotes. To put certain characters inside a string literal you use an escape sequence, which starts with a backslash and has a special meaning in Java. Three are required in this course.
Escape sequence
Meaning
Example
Displays
\"
a double quote
"She said \"hi\""
She said "hi"
\\
one backslash
"C:\\temp"
C:\temp
\n
a new line
"one\ntwo"
one then two on the next line
System.out.println("She said \"hi\" and left.\nGoodbye");
She said "hi" and left.
Goodbye
Arithmetic expressions
An arithmetic expression is made of numeric values, variables, and operators. The five arithmetic operators are addition +, subtraction -, multiplication *, division /, and remainder %. The type of the result depends on the types of the operands.
An operation on two int values evaluates to an int.
An operation with at least one double value evaluates to a double.
### Division
When both operands are int, / produces only the integer part of the quotient: the digits after the decimal point are discarded, not rounded. When at least one operand is a double, the result is the full quotient.
Expression
Value
Why
7 / 2
3
both int: integer part of 3.5
7.0 / 2
3.5
one double, so a double quotient
7 / 2.0
3.5
same
1 / 4
0
the integer part of 0.25
1.0 / 4
0.25
Dividing an int by the integer 0 throws an ArithmeticException while the program runs.
### The remainder operator
a % b is the remainder when a is divided by b. On the exam, a is zero or positive and b is positive. 17 % 5 is 2 because 5 goes into 17 three times (15) with 2 left over. Four uses show up again and again.
Task
Expression
Example
Is a number even?
n % 2 == 0
10 % 2 is 0
Last digit of a number
n % 10
4073 % 10 is 3
Remove the last digit
n / 10
4073 / 10 is 407
Wrap around a range
(start + steps) % size
(5 + 4) % 7 is 2
### Precedence
Operators are grouped before the expression is evaluated. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence evaluate from left to right. Parentheses change the order, and they are the cheapest insurance against mistakes.
The last two are the classic trap: 20 / 4 * 2 goes left to right, so it is 5 * 2. The fifth expression's parentheses force 4 * 2 first, so it is 20 / 8, which is 2 in integer division.
Worked example · tracing integer arithmetic
Trace the values and say what is printed.
int minutes = 135;
int hours = minutes / 60;
int leftover = minutes % 60;
double avg = minutes / 60;
double exact = minutes / 60.0;
System.out.println(hours + " h " + leftover + " min");
System.out.println(avg);
System.out.println(exact);
Statement
Value stored
Reasoning
hours = minutes / 60
2
135 / 60 is integer division
leftover = minutes % 60
15
135 minus 120
avg = minutes / 60
2.0
the division happens first, on two int values, giving 2; then the int is stored in a double
exact = minutes / 60.0
2.25
one double operand, so a real quotient
2 h 15 min
2.0
2.25
The line avg = minutes / 60 is the most common wrong answer on the exam. The type of the variable on the left does not change the type of the operation on the right.
Worked example · splitting a number into digits
Print the tens digit and the ones digit of 74, and the number with its digits reversed.
int n = 74;
int ones = n % 10;
int tens = n / 10;
int reversed = ones * 10 + tens;
System.out.println(tens + " " + ones);
System.out.println(reversed);
7 4
47
74 % 10 is the remainder, 4, so it is the ones digit. 74 / 10 throws away the 4 and keeps 7. The reversed number is rebuilt with place values: 4 tens and 7 ones.
Worked example · a compound expression
Evaluate 3 + 6 / 4 * 2 - 5 % 3, showing the order of evaluation.
System.out.println(3 + 6 / 4 * 2 - 5 % 3);
3
Step by step, the operators /, *, and % run first, left to right: 6 / 4 is 1, then 1 * 2 is 2, and 5 % 3 is 2. What remains is 3 + 2 - 2, evaluated left to right: 5 - 2, which is 3.
Exam focus
Expect questions that ask for the value of an expression with mixed int and double operands, and questions where the answer depends on integer division or the remainder. The usual wrong answers come from applying the type of the variable instead of the type of the operands, rounding where Java truncates, or ignoring precedence. Write out the order of evaluation when a line has more than two operators. The exam stays with non-negative values for % and never divides by zero in a double expression.
4, then 1, then 4.5. The first quotient is integer division (4.5 truncated to 4), the remainder of 9 divided by 2 is 1, and the third has a double operand, so the quotient is exact.
What is the value of 10 - 4 * 2 + 6 / 3?
System.out.println(10 - 4 * 2 + 6 / 3);
Show answer
4. Multiplication and division first: 4 * 2 is 8 and 6 / 3 is 2. Then 10 - 8 + 2 left to right is 4.
A class has 25 students and tables seat 4. Write expressions for the number of full tables and the number of students left over.
int students = 25;
int fullTables = students / 4;
int leftOver = students % 4;
System.out.println(fullTables + " " + leftOver);
Show answer
Full tables is students / 4, which is 6; students left over is students % 4, which is 1. Integer division and remainder are a matched pair: (students / 4) * 4 + students % 4 always equals students.
What is printed?
double result = 5 / 2;
System.out.println(result);
Show answer
2.0. The right side is evaluated first as integer division, giving 2, and that int is then widened to a double for storage.
Write the statement that displays exactly this output on two lines: Name: "Ada" and then Done.
System.out.println("Name: \"Ada\"\nDone");
Show answer
The escape sequence \" puts a double quote inside the string and \n starts a new line, so the single println above produces both lines.
Declaring a variable creates a box. An assignment statement puts something in it. This is where programs start to move: values are computed, stored, and changed as the statements run, and the skill the exam tests most here is tracing, meaning following those changes line by line and keeping track of what each variable holds.
Required content · LO 1.4.A, LO 1.4.B
Learning objectives.
1.4.A. Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.
1.4.B. Develop code to read input.
Essential knowledge.
1.4.A.1. Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
1.4.A.2. The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left. Outside the course: The use of assignment operators inside expressions (e.g., a = b = 4; or a[i += 5]) is outside the scope of the AP Computer Science A course and exam.
1.4.A.3. During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression.
1.4.B.1. Input can come in a variety of forms, such as tactile, audio, visual, or text. The Scanner class is one way to obtain text input from the keyboard. Outside the course: Any specific form of input from the user is outside the scope of the AP Computer Science A course and exam.
The assignment operator
The assignment operator = stores a value in a variable. It does not mean "equals" the way it does in algebra. It means: evaluate the expression on the right, then store the result in the variable on the left.
int score = 10; // initialization: the first time score gets a value
score = score + 5; // evaluate score + 5 (that is 15), then store it in score
Because the right side is evaluated first, a statement like score = score + 5 is perfectly sensible: it reads the old value, adds, and stores the new one. Rules that follow from this:
A variable must be assigned a value before it is used in an expression. A variable is initialized the first time it is assigned a value.
The value must come from a compatible data type. An int can go in a double; a double cannot go in an int without a cast (Lesson 1.5).
A variable of a reference type can be assigned a new object, or the special literal null, which means the variable is not associated with any object.
During execution an expression is evaluated to produce a single value, and that value has a type determined by the expression.
Assignment is a statement, not something to use inside another expression: forms such as a = b = 4; are outside the course.
Tracing
A trace table is a table with one column per variable and one row per statement. Fill in each row with the values after that statement runs. Tracing on paper is the best habit you can build for this course, because it is how you find out what code really does.
Worked example · a trace
Trace this code and give the final values.
int a = 5;
int b = a;
a = a + 2;
b = b * 3;
System.out.println(a + " " + b);
After the statement
a
b
int a = 5;
5
not yet declared
int b = a;
5
5
a = a + 2;
7
5
b = b * 3;
7
15
7 15
The line int b = a; copies the value of a at that moment. Later changing a does not change b, because the two variables are separate boxes.
Worked example · swapping two values
Swap the values of x and y. Without a helper variable the first assignment would destroy a value, so a third variable holds it temporarily.
int x = 3;
int y = 8;
int temp = x;
x = y;
y = temp;
System.out.println("x = " + x + ", y = " + y);
After the statement
x
y
temp
start
3
8
int temp = x;
3
8
3
x = y;
8
8
3
y = temp;
8
3
3
x = 8, y = 3
Try it without temp: x = y; would make both variables 8, and the original 3 would be gone with no way to recover it.
Worked example · what the compiler refuses
A variable must be assigned a value before it is used.
public class Main {
public static void main(String[] args) {
int total;
int doubled = total * 2;
}
}
Main.java:4: error: variable total might not have been initialized
int doubled = total * 2;
^
1 error
The declaration made the box but never put anything in it, so reading it makes no sense and the compiler refuses. Assigning an incompatible value is also refused: int n = "five"; fails with incompatible types: String cannot be converted to int.
Getting data in: input
Programs also take input, which can be tactile, audio, visual, or text. The Scanner class is one way to obtain text typed at a keyboard, and the only form of input this course uses in code is reading from a file (Lesson 4.6). Keyboard input appears in many classroom programs, so the idiom is worth recognizing, but no specific form of keyboard input is tested on the exam.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Your age: ");
int age = in.nextInt();
System.out.println("Next year you will be " + (age + 1));
}
}
The call in.nextInt() waits for the user, reads an int, and the = stores it in age. Everything after that is ordinary assignment and expressions.
Exam focus
Tracing questions dominate this topic: a short segment of assignments, then "what is the value of b after the code runs?" Build a trace table every time; do not do it in your head. Expect x = x + 1 style statements, copies such as b = a followed by a change to a, and swaps. Remember that the right side is evaluated first, and that the type of the whole expression, not of the variable on the left, controls integer or real division.
Practice
What are the values of a and b after the code runs?
int a = 4;
int b = 9;
a = b;
b = a + 1;
System.out.println(a + " " + b);
Show answer
a is 9 and b is 10. After a = b; both variables hold 9. Then b = a + 1; stores 10 in b, and a is untouched.
What is printed?
int n = 6;
n = n * 2;
n = n - 5;
System.out.println(n);
Show answer
7. The value goes 6, then 12, then 7.
Which statement correctly increases count by 3?
A. count + 3 = count;
B. count = count + 3;
C. 3 + count;
D. count == count + 3;
Show answer
B. The assignment operator needs a variable on the left and an expression on the right. A reverses the sides, C computes a value and throws it away, and D is a comparison, not a change.
Does this compile? Why or why not?
int price;
System.out.println(price);
Show answer
No. price is declared but never assigned a value before it is used, so the compiler reports that it might not have been initialized.
Trace the code and give the final output.
int p = 2;
int q = 3;
p = p + q;
q = p - q;
p = p - q;
System.out.println(p + " " + q);
Show answer
3 2. After the first assignment p is 5. Then q = 5 - 3 is 2, and p = 5 - 2 is 3. This sequence swaps the two values with no helper variable, but only because the values are numbers.
A variable String title has been declared and not assigned. Which statement is valid, and what does it do?
A. title = null;
B. title = 5;
C. title = "";
Show answer
A and C are both valid. null means the variable refers to no object, and "" is a real String object with no characters. B is invalid because an int is not a String.
Java keeps int and double apart on purpose, but real programs mix them all the time: an average of whole numbers, a price rounded to cents, a percentage of a count. This lesson covers the tool that converts between them, the cast, and the two ways numbers can quietly go wrong: values that fall out of an int's range and values a double cannot hold exactly.
Required content · LO 1.5.A, LO 1.5.B, LO 1.5.C
Learning objectives.
1.5.A. Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.
1.5.B. Describe conditions when an integer expression evaluates to a value out of range.
1.5.C. Describe conditions that limit accuracy of expressions.
Essential knowledge.
1.5.A.1. The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
1.5.A.2. Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
1.5.A.3. Some code causes int values to be automatically cast (widened) to double values.
1.5.A.4. Values of type double can be rounded to the nearest integer by (int) (x + 0.5) for non-negative numbers or (int)(x - 0.5) for negative numbers.
1.5.B.1. The constant Integer.MAX_VALUE holds the value of the largest possible int value. The constant Integer.MIN_VALUE holds the value of the smallest possible int value.
1.5.B.2. Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.
1.5.B.3. If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.
1.5.C.1. Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, use int values. Outside the course: Other special decimal data types that can be used to avoid rounding errors are outside the scope of the AP Computer Science A course and exam.
Casting with (int) and (double)
A casting operator converts a value to another type. The two you need are (int) and (double), written in parentheses directly before the value.
(int) on a doubletruncates: the digits to the right of the decimal point are dropped, with no rounding. (int) 3.99 is 3, and (int) -3.99 is -3, because truncation always moves toward zero.
(double) on an int produces the same number with a decimal part: (double) 4 is 4.0.
Some code casts automatically. An int used where a double is needed is widened to a double without a cast, which is why double x = 7; is legal and stores 7.0.
A cast applies to the value immediately after it, before any arithmetic operator runs. That makes the position of the parentheses matter.
Expression
Value
Why
(int) 3.7 * 2
6
the cast happens first: 3 * 2
(int) (3.7 * 2)
7
multiply first (7.4), then truncate
(double) 7 / 2
3.5
the cast turns 7 into 7.0 first, so real division
(double) (7 / 2)
3.0
integer division first (3), then widen
The second pair is the most useful pattern in the course. To compute an average of int values without losing the fraction, cast one operand before the division:
int sum = 17;
int count = 4;
System.out.println(sum / count);
System.out.println((double) sum / count);
System.out.println((double) (sum / count));
4
4.25
4.0
### Rounding to the nearest integer
A cast truncates, so to round you first nudge the value. For a non-negative x, (int) (x + 0.5) gives the nearest integer. For a negative x, (int) (x - 0.5) does. To round to a number of decimal places, scale up, round, and scale back down:
Integers in Java are stored in a fixed amount of memory (4 bytes), so an int can only hold values between two limits. Two constants name them.
Constant
Value
Integer.MAX_VALUE
2147483647
Integer.MIN_VALUE
-2147483648
If an expression would produce an int outside that range, integer overflow occurs. Java does not stop and does not warn. The result is an int that is in the allowed range but not the value you expected, because the value wraps around.
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1);
2147483647
-2147483648
When a double is not exact
A double also lives in a fixed amount of memory. Many decimal numbers, such as 0.1, have no exact binary representation, so the stored value is the nearest one that fits. Arithmetic on these values can produce a round-off error.
The rule that follows: do not rely on exact equality of computed double values, and when exactness matters, use int values. A program that tracks money in whole cents with an int never accumulates this error.
Worked example · predicting the value of a cast expression
Give the value and the type of each expression.
int a = 9;
int b = 4;
double d = 2.5;
System.out.println(a / b);
System.out.println((double) a / b);
System.out.println((int) d * 3);
System.out.println((int) (d * 3));
System.out.println((int) (d + 0.5));
2
2.25
6
7
3
Expression
Reasoning
Value
a / b
both int, so integer division
2 (an int)
(double) a / b
cast first, then 9.0 / 4
2.25 (a double)
(int) d * 3
(int) 2.5 is 2, times 3
6 (an int)
(int) (d * 3)
7.5 truncated
7 (an int)
(int) (d + 0.5)
3.0 truncated
3 (an int)
Worked example · an average that comes out wrong
A program computes the average of three test scores and displays 88.0, though the real average is 88.33.
int s1 = 90;
int s2 = 85;
int s3 = 90;
double wrong = (s1 + s2 + s3) / 3;
double right = (s1 + s2 + s3) / 3.0;
System.out.println(wrong);
System.out.println(right);
88.0
88.33333333333333
The sum is 265, an int, and 265 / 3 is integer division: it throws away .33 before the result is ever stored in the double. The fix is to make one operand a double. Writing 3.0 does it, and so does (double) (s1 + s2 + s3) / 3.
Worked example · counting dollars in cents
A program totals items that cost 1.10 and 2.20 dollars, then repeats the calculation in whole cents.
The double total is slightly off, a round-off error, because neither 1.10 nor 2.20 is stored exactly. The int version is exact for every input, because whole numbers within the int range are stored exactly. Use / and % to split cents into dollars and cents.
Exam focus
Expect a question that asks for the value of an expression with casts in different positions, and one that asks what happens when a value exceeds Integer.MAX_VALUE (an in-range but wrong value, never an error message). Also expect the average pattern: the exam wants you to notice that the cast must come before the division. Know the rounding formula (int) (x + 0.5) for non-negative values. Other special decimal types that avoid round-off error are outside the course.
Practice
What is printed?
double x = 8.9;
int y = (int) x;
System.out.println(y);
System.out.println((int) -x);
Show answer
8 and -8. The cast truncates toward zero, so 8.9 becomes 8 and -8.9 becomes -8. It does not round.
What is printed?
int total = 7;
int n = 2;
System.out.println(total / n);
System.out.println((double) total / n);
System.out.println((double) (total / n));
Show answer
3, 3.5, 3.0. The first is integer division. In the second the cast makes total a double before dividing. In the third the division is already finished (giving 3) before the cast widens it.
Complete the statement so that pct holds the percent of questions answered correctly as a double (for 17 of 20 it should hold 85.0).
int correct = 17;
int total = 20;
double pct = 100.0 * correct / total;
System.out.println(pct);
Show answer
100.0 * correct / total multiplies first (left to right) with a double, giving 1700.0, then divides by 20. Writing 100 * correct / total would have used integer arithmetic throughout, which gives 85 here but would give 62 for 5 correct out of 8 instead of 62.5.
A student claims the code below throws an exception. Explain what really happens.
int n = Integer.MAX_VALUE;
n = n + 1;
System.out.println(n);
Show answer
No exception occurs. The sum is outside the int range, so integer overflow produces a different int in the allowed range. Here it wraps to Integer.MIN_VALUE, which is -2147483648.
Write an expression that rounds the non-negative double variable grade to the nearest integer.
(int) (grade + 0.5). Adding 0.5 pushes any fractional part of 0.5 or more up to the next whole number, and the cast then truncates, so 86.5 becomes 87.
Why is 0.1 + 0.2 == 0.3 false, and how can a program avoid this kind of surprise when counting money?
Show answer
A double stores the nearest representable value, and 0.1 and 0.2 are not stored exactly, so their sum differs slightly from the stored 0.3 (a round-off error). Storing money in whole cents in an int avoids it, because integers in range are exact.
Programs update variables constantly: add to a running total, count up one, halve a size. The statement total = total + price; does this, and it is so common that Java gives it a shorter form. This lesson is short on new ideas and long on payoff, because every loop you write from Unit 2 onward uses these operators.
Required content · LO 1.6.A
Learning objective.
1.6.A. Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.
Essential knowledge.
1.6.A.1. Compound assignment operators +=, -=, *=, /=, and %= can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right and then assigns the result to the variable on the left.
1.6.A.2. The post-increment operator ++ and post-decrement operator -- are used to add 1 or subtract 1 from the stored value of a numeric variable. The new value is assigned to the variable. Outside the course: The use of increment and decrement operators in prefix form (e.g., ++x) is outside the scope of the AP Computer Science A course and exam. The use of increment and decrement operators inside other expressions (e.g., arr[x++]) is outside the scope of the AP Computer Science A course and exam.
The compound assignment operators
A compound assignment operator combines an arithmetic operation with an assignment. It performs the operation between the value on the left and the value on the right, then assigns the result to the variable on the left.
Compound form
Same as
Example
If x starts at 10, x becomes
x += 3
x = x + 3
add
13
x -= 3
x = x - 3
subtract
7
x *= 3
x = x * 3
multiply
30
x /= 3
x = x / 3
divide (integer division for int)
3
x %= 3
x = x % 3
remainder
1
The right side is fully evaluated first, as a single value, and then the operation is applied. So x *= 2 + 3 means x = x * (2 + 3), not x = x * 2 + 3.
int x = 10;
x *= 2 + 3;
System.out.println(x);
50
Increment and decrement
Adding 1 or subtracting 1 is so common that it has its own operators. The post-increment operator ++ adds 1 to the stored value of a numeric variable, and the post-decrement operator -- subtracts 1. The new value is assigned to the variable.
int count = 5;
count++;
count++;
count--;
System.out.println(count);
6
On the exam, ++ and -- appear only as statements by themselves, in the postfix form. The prefix form (++count) and increments used inside other expressions (for example arr[i++]) are outside the course, so you will never have to decide what such a combination does.
Two patterns every program uses
An accumulator is a variable that builds up a result by repeating the same update: a running total, a product, a count. A counter is the special case that adds 1.
int total = 0;
total += 12;
total += 8;
total += 15;
int visits = 0;
visits++;
visits++;
System.out.println("total = " + total + ", visits = " + visits);
total = 35, visits = 2
Initialize an accumulator to the value that leaves the result unchanged: 0 for a sum, 1 for a product. Starting a sum at 1 makes every total one too big, a logic error that no tool will report.
Worked example · translating between forms
Rewrite each statement without a compound operator, and give the value of n if it starts at 20.
Statement
Equivalent
n afterward
n += 5;
n = n + 5;
25
n -= 8;
n = n - 8;
12
n *= 2;
n = n * 2;
40
n /= 3;
n = n / 3;
6
n %= 6;
n = n % 6;
2
n++;
n = n + 1;
21
int n = 20;
n /= 3;
System.out.println(n);
n %= 4;
System.out.println(n);
6
2
The division keeps only the integer part (20 / 3 is 6), and the remainder of 6 divided by 4 is 2.
Worked example · tracing a series of updates
Trace the code and give the final output.
int a = 3;
int b = 4;
a += b;
b *= a;
a -= b / 2;
b %= 5;
System.out.println(a + " " + b);
After the statement
a
b
int a = 3; int b = 4;
3
4
a += b;
7
4
b *= a;
7
28
a -= b / 2;
-7
28
b %= 5;
-7
3
-7 3
a -= b / 2 first computes 28 / 2 (14), then subtracts that from a: 7 - 14 is -7.
Worked example · a typing slip that still compiles
A student means to add 2 to x, but writes the operator the wrong way round.
int x = 10;
x =+ 2;
System.out.println(x);
2
The statement x =+ 2; is x = +2;: an ordinary assignment of the value positive 2. It compiles, it runs, and it quietly replaces the 10. The correct operator is +=, with the plus before the equals sign. Errors like this are logic errors, which is why you test with known answers and trace code instead of trusting it.
Exam focus
Questions here are tracing questions: a sequence of compound assignments, then "what is the value of x?" Be careful with /= on int values (truncation), with %=, and with a right side that is itself an expression (x *= 2 + 3). The postfix forms x++ and x-- are the only increment forms tested, and only as stand-alone statements.
Practice
What is printed?
int k = 8;
k += 4;
k /= 3;
k -= 1;
System.out.println(k);
Show answer
3. The value goes 8, 12, 4, then 3.
What is printed?
int p = 5;
p *= 1 + 2;
System.out.println(p);
Show answer
15. The right side 1 + 2 is evaluated to 3 first, so the statement is p = p * 3.
Which statement is equivalent to score -= 3;?
A. score = 3 - score;
B. score = score - 3;
C. score =- 3;
D. score == score - 3;
Show answer
B. A reverses the subtraction, C assigns negative 3, and D is a comparison that changes nothing.
What is printed?
int n = 17;
n %= 5;
n++;
n *= n;
System.out.println(n);
Show answer
9. 17 % 5 is 2, n++ makes it 3, and n *= n is 3 * 3.
Write statements that use a counter and an accumulator to count the values and add them up: 4, 9, and 2.
int sum = 0;
int count = 0;
sum += 4;
count++;
sum += 9;
count++;
sum += 2;
count++;
System.out.println(sum + " " + count);
Show answer
The sum starts at 0, so the accumulator ends at 15, and the counter ends at 3. Initializing the sum to 0 leaves the first addition unchanged.
A program is meant to compute 5 factorial (5 x 4 x 3 x 2 x 1) but prints 0. Find the bug.
int result = 0;
result *= 5;
result *= 4;
result *= 3;
result *= 2;
System.out.println(result);
Show answer
The accumulator for a product must start at 1, not 0. Anything times 0 is 0, so every update leaves it at 0.
Nobody writes every piece of a program from scratch. The System.out.println you have used since Lesson 1.1 was written by someone else, and so were String, Math, and ArrayList. This lesson covers how to find out what such pre-written code does, and how to leave the same kind of information for the next reader of your own code.
Required content · LO 1.7.A, LO 1.8.A
Learning objectives.
1.7.A. Identify the attributes and behaviors of a class found in the libraries contained in an API.
1.8.A. Describe the functionality and use of code through comments.
Essential knowledge.
1.7.A.1. Libraries are collections of classes. An application programming interface (API) specification informs the programmer how to use those classes. Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API. A class defines a specific reference type. Classes in the APIs and libraries are grouped into packages. Existing classes and class libraries can be utilized to create objects.
1.7.A.2. Attributes refer to the data related to the class and are stored in variables. Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.
1.8.A.1. Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.
1.8.A.2. A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
1.8.A.3. A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.
Libraries and APIs
A library is a collection of classes. An application programming interface (API) specification is the documentation that tells a programmer how to use those classes: what each class is for, what it can store, and what it can do. A class defines a specific reference type, and classes in a library are grouped into packages.
java.lang holds String, Math, Integer, and Double. It is available by default; you never import it.
java.util holds ArrayList and Scanner. You make its classes available with an import statement at the top of the file.
java.io holds File and IOException. It needs an import too.
Existing classes can be used to create objects, so a library is a toolbox you can reach into without knowing how each tool is built.
### Attributes and behaviors
Documentation describes a class in two parts. Attributes are the data related to the class, stored in variables. Behaviors are what instances of the class can do (or what can be done with them), and they are defined by methods. A String has the attribute "a sequence of characters" and behaviors such as finding its length.
### Reading an API entry
A typical API page lists the class's constructors and methods in a summary table. Here is the shape of such an entry for a made-up class, Thermometer, written the way real documentation reads.
Method summary
What it does
double getCelsius()
Returns the current reading in degrees Celsius.
double getFahrenheit()
Returns the current reading in degrees Fahrenheit.
void setCelsius(double c)
Sets the reading to c degrees Celsius.
boolean isFreezing()
Returns true if the reading is at or below 0 degrees Celsius.
Read each row from left to right: the return type (what you get back, or void for nothing), the name, and the parameter list (what you must provide). That is everything you need to call a method correctly, without seeing one line of its code. Using a method knowing what it does but not how it works is the idea of procedural abstraction, which Lesson 1.9 builds on.
Documenting code with comments
A comment is text for human readers. The compiler ignores it and it never runs. Java has three kinds.
// A single-line comment runs to the end of the line.
/* A block comment can
span several lines. */
/** A Javadoc comment is used to create API documentation.
* It sits just above a class or method. */
Comments exist for both the original programmer and other programmers to understand the code and its functionality. Good comments say why or state what must be true; poor comments restate the code.
### Preconditions and postconditions
Two kinds of comment have exact meanings in this course.
A precondition is a condition that must be true just before a method runs for it to behave as expected. There is no expectation that the method checks it. If a caller breaks the precondition, the result is whatever happens.
A postcondition is a condition that must always be true after the method runs. Postconditions describe the outcome: what is returned, or what the values of an object's attributes are.
/** Returns the average of the two values.
* Precondition: count > 0
* Postcondition: the value returned is sum divided by count, as a double
*/
public static double average(int sum, int count)
The precondition is a promise the caller makes ("I will not pass a count of zero"). The postcondition is the promise the method makes in return ("if you kept your promise, here is exactly what you get").
Worked example · choosing a method from the documentation
Using the Thermometer table above, which statements do the job?
Thermometer t = new Thermometer();
t.setCelsius(100);
double f = t.getFahrenheit();
boolean frozen = t.isFreezing();
Task
Method
Why
store a reading of 100 degrees Celsius
setCelsius(100)
void, takes a double; an int argument is widened
find the reading in Fahrenheit
getFahrenheit()
no parameters, returns a double
decide whether it is at or below freezing
isFreezing()
returns a boolean
You can write correct calls without knowing how any of these methods work. If you called t.isFreezing(0), the compiler would object, because the documentation says the method has no parameters.
Worked example · what comments do to a program
Predict the output. Comments never execute, so commenting out a statement removes it.
int a = 1;
// a = a + 10;
/* a = a + 100;
a = a + 1000; */
a = a + 5;
System.out.println(a);
6
Only a = a + 5; is live code. A frequent exam trick is a statement that looks active but sits inside a block comment, or a closing */ that ends the comment earlier than it seems.
Worked example · writing a precondition and a postcondition
A method returns what percent part is of whole. State what the caller must guarantee and what the method guarantees.
/** Returns part as a whole-number percent of whole (the fraction is dropped).
* Precondition: whole > 0
* Postcondition: the value returned is part * 100 / whole in integer division
*/
public static int percent(int part, int whole) {
return part * 100 / whole;
}
The first call keeps the precondition and receives the promised value.
System.out.println(percent(3, 8));
37
The second call breaks the precondition, and the method does not check it for you.
System.out.println(percent(3, 0));
Exception in thread "main" java.lang.ArithmeticException: / by zero
That is exactly what the definitions predict: the caller broke the precondition, so the method owes no postcondition. Nothing in the method stops the call; a precondition is a promise the caller makes, not a check the method performs.
Exam focus
Expect to be shown an API-style table or a method header and asked which method call completes a task. Know the three comment forms, and know that preconditions are not checked by the method. The postcondition describes the result (what is returned or the new state of the object's attributes). The packages to remember: java.lang is automatic, and java.util and java.io need import.
Practice
Which package must be imported with an import statement before you can use ArrayList?
Show answer
java.util. Classes in java.lang, such as String and Math, are available by default, but ArrayList is in java.util.
What does the compiler do with the text // reset the counter?
Show answer
It ignores it. Comments are for human readers and are not executed or compiled into the program.
What is printed?
int n = 2;
/* n = n * 100;
// n = n * 10; */
n = n + 1;
System.out.println(n);
Show answer
3. The block comment starts at /* and ends at the first */, so both multiplications (even the one that begins with //) are inside it. Only n = n + 1; runs.
A method's comment says "Precondition: items is not empty." A caller passes an empty list and the program fails. Whose responsibility was that?
Show answer
The caller's. A precondition states what must be true before the call, and the method is not required to check it. Breaking it means the method's postcondition no longer has to hold.
Using the Thermometer table, write a call that stores 21.5 degrees Celsius in the object room.
Show answer
room.setCelsius(21.5);. The method is void, takes one double, and returns nothing, so the call is a statement by itself.
In a class description, what is the difference between an attribute and a behavior?
Show answer
An attribute is data related to the class, stored in variables. A behavior is something instances of the class can do (or have done to them), defined by a method.
A method is a named block of code that only runs when it is called. You have been calling methods since the first lesson (System.out.println is one), and in this lesson you learn to read the line that describes a method, its signature, closely enough to know exactly how to call it and exactly what you get back.
Required content · LO 1.9.A, LO 1.9.B
Learning objectives.
1.9.A. Identify the correct method to call based on documentation and method signatures.
1.9.B. Describe how to call methods.
Essential knowledge.
1.9.A.1. A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
1.9.A.2. A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
1.9.B.1. A void method does not have a return value and is therefore not called as part of an expression.
1.9.B.2. A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
1.9.B.3. An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
1.9.B.4. Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
1.9.B.5. A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
Why methods exist
Naming a block of code lets you use it by name, as many times as you want, without rewriting it. That is procedural abstraction: you can use a method knowing what it does even if you do not know how it was written. A block of code is any section of code enclosed in braces.
Parts of a method header
public static double average(int sum, int count)
public static are modifiers; Lesson 1.10 explains static.
double is the return type: the type of value the method gives back. A method that gives back nothing says void.
average is the name.
(int sum, int count) is the parameter list. A parameter is a variable declared in the header and usable inside the body. It receives a value when the method is called.
The method signature is the name together with the ordered list of parameter types. For the method above it is average(int, int). A method without parameters has an empty parameter list, such as reset(). The return type is not part of the signature.
Calling a method
An argument is the value passed into a method when it is called. The arguments must be compatible in number and order with the parameter types in the signature. Arguments are passed using call by value: each parameter is initialized with a copy of the argument, so changing the parameter inside the method never changes the caller's variable.
Methods live inside a class. The examples in this lesson leave out the public class Main { ... } wrapper to keep them short.
public static double average(int sum, int count) {
return (double) sum / count;
}
public static void main(String[] args) {
int total = 17;
int n = 4;
double result = average(total, n);
System.out.println(result);
}
4.25
### void and non-void
A void method has no return value, so it is called as a statement by itself and is never part of an expression.
A non-void method returns a value of the type named in its header. To use that value, store it in a variable or use it as part of an expression. Calling it as a statement and ignoring the result is legal but wastes the result.
### Overloading
Methods are overloaded when there are several methods with the same name but different signatures. Java picks the version whose parameter types match the arguments. Two methods that differ only in return type are not allowed, because the signature does not include the return type.
### The flow of control
A method call interrupts the sequential execution of statements: the program first runs the statements in the method, then continues at the point immediately after the call. The method ends when its last statement runs or when a return statement runs.
Figure 1.3. Flow of control for a method call. The highlighted statement pauses while the method runs; the returned value takes the place of the call, and execution continues with the next statement.
Worked example · reading signatures
Match each call to a method, or say why none matches.
public static int square(int n)
public static double square(double x)
public static void greet(String name)
public static int max(int a, int b)
Call
Result
Why
square(5)
25 (an int)
the int argument matches square(int)
square(2.5)
6.25 (a double)
a double argument matches square(double)
greet("Ada")
no value
void: use it as a statement only
max(3, 9)
9
two int arguments, in order
max(3)
does not compile
wrong number of arguments
max(3, "9")
does not compile
a String where an int is required
int r = greet("Ada");
does not compile
void method used as a value
Worked example · call by value
Does the method change the caller's variable?
public static void addTen(int n) {
n = n + 10;
System.out.println("inside: " + n);
}
public static void main(String[] args) {
int score = 5;
addTen(score);
System.out.println("outside: " + score);
}
inside: 15
outside: 5
The parameter n was initialized with a copy of score's value, 5. The method changed its own copy to 15. The caller's score is a different variable and still holds 5.
Worked example · tracing the flow of control
Trace which line prints and in what order.
public static int twice(int x) {
System.out.println("in twice");
return x * 2;
// nothing after return runs
}
public static void main(String[] args) {
System.out.println("start");
int r = twice(4) + twice(1);
System.out.println("r = " + r);
}
start
in twice
in twice
r = 10
main prints start, then evaluates twice(4) + twice(1) left to right. Each call interrupts main, prints in twice, returns a value, and control resumes where the call was. The sum is 8 + 2, so r is 10.
All three share the name describe; their signatures describe(int), describe(double), and describe(String) differ in parameter type, so the arguments decide which runs.
Exam focus
Expect a method header and a list of calls, and you decide which call is legal, what it returns, and how it is used. Count arguments, check their order and types, and check whether the method is void. Questions about call by value present a method that modifies its parameter and ask what the caller's variable holds afterward (it is unchanged for a primitive argument). Overloading questions ask you to match arguments to signatures.
Practice
What is the signature of public static int clamp(int value, int low, int high)?
Show answer
clamp(int, int, int): the name and the ordered list of parameter types. The return type int and the parameter names are not part of the signature.
Which call is legal for public static double half(int n)?
A. half();
B. half(3, 4);
C. double h = half(9);
D. int h = half(9);
Show answer
C. A passes no argument and B passes two to a one-parameter method. D tries to store a double result in an int without a cast, which does not compile.
What is printed?
public static int triple(int n) {
return n * 3;
}
public static void main(String[] args) {
int a = 4;
triple(a);
System.out.println(a);
a = triple(a);
System.out.println(a);
}
Show answer
4 and then 12. The first call returns 12, but the value is discarded and a is unchanged. The second call stores the returned value in a.
What is printed?
public static void change(int x) {
x = 99;
}
public static void main(String[] args) {
int y = 1;
change(y);
System.out.println(y);
}
Show answer
1. The parameter x received a copy of y, so setting it to 99 has no effect on y.
Can a class contain public static int size(String s) and public static double size(String s) together? Why or why not?
Show answer
No. The signatures are both size(String); the return type is not part of the signature, so these are not different overloads and the compiler rejects the second declaration.
Order the output of this code.
public static void show(String label) {
System.out.println(label);
}
public static void main(String[] args) {
show("A");
show("B");
show("A");
}
Show answer
A, B, A. Each call runs the method body once, in the order the calls appear, and control returns to the line after each call.
Some methods belong to a class as a whole rather than to any one object. You have used several already without creating anything: Math.sqrt(49) does not need a Math object, because Math is a toolbox of methods that stand on their own. This lesson explains what makes those methods different, and how to call and write them.
Required content · LO 1.10.A
Learning objective.
1.10.A. Develop code to call class methods and determine the result of those calls.
Essential knowledge.
1.10.A.1. Class methods are associated with the class, not instances of the class. Class methods include the keyword static in the header before the method name.
1.10.A.2. Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
What a class method is
Class methods are associated with the class, not with instances of the class. A class method has the keyword static in its header, before the return type.
public static int square(int n)
Because a class method belongs to the class, you do not create an object to call it. The usual call uses the class name with the dot operator.
public class Converter {
public static double toFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32.0;
}
public static int square(int n) {
return n * n;
}
}
double boiling = Converter.toFahrenheit(100);
int area = Converter.square(7);
System.out.println(boiling);
System.out.println(area);
212.0
49
When the call appears in the class that defines the method, the class name is optional: inside Converter you may write square(7) instead of Converter.square(7). From any other class you must name the class.
Calling a method and using its value
Everything from Lesson 1.9 still applies. The arguments must match the parameter types in number and order. A void class method is a statement by itself; a non-void class method returns a value that you store or use in an expression, and a method call can be an argument to another method call.
The inner call runs first and returns 9; that value is the argument for the outer call, which returns 81.
Why call a class method without an object
A class method is the right tool when the work depends only on its arguments. Converting a temperature needs no stored state: give it a number, get a number. Methods that depend on the data stored in a particular object are instance methods (Lesson 1.14), and they are called on an object instead.
Class method
Instance method
Header has
static
no static
Belongs to
the class
one object of the class
Called with
ClassName.method(args)
objectName.method(args)
Needs an object first
no
yes
Worked example · calling class methods from another class
Which statements work, and what do they print?
int a = Converter.square(5);
double f = Converter.toFahrenheit(0);
System.out.println(a + " " + f);
25 32.0
The class name is in front of each call, no object was created, and the int argument 0 was widened to the double the parameter needs. Both results are stored in variables whose types match the return types.
Worked example · the class name is optional inside the class
A main method in the same class as the helper methods.
public class Main {
public static int cube(int n) {
return n * n * n;
}
public static int sumOfCubes(int a, int b) {
return cube(a) + cube(b);
}
public static void main(String[] args) {
System.out.println(sumOfCubes(2, 3));
System.out.println(Main.cube(4));
}
}
35
64
sumOfCubes calls cube with no class name, which is legal because both methods are in Main. main may use either form. The first line is 8 + 27.
Worked example · why this will not compile
Three common mistakes with class methods.
public class Main {
public int getFive() {
return 5;
}
public static void main(String[] args) {
int x = getFive();
}
}
Main.java:7: error: non-static method getFive() cannot be referenced from a static context
int x = getFive();
^
1 error
getFive has no static in its header, so it is an instance method and needs an object. main is a class method and has no object. The other two mistakes are equally common: a call from another class with no class name (square(7) instead of Converter.square(7)) fails with cannot find symbol, and a wrong argument type (Converter.square("7")) fails with incompatible types: String cannot be converted to int.
Exam focus
Expect code with a mix of class method calls (possibly nested) and a question that asks for the printed value, or one that asks why a call will not compile. For a compile question, check three things in order: is the method static (or is there an object), does the class name appear where it must, and do the arguments match the signature. Inside the defining class the class name is optional.
16. The inner call returns 4, which becomes the argument of the outer call.
A class Tools declares public static int twice(int n). Write a statement outside Tools that stores twice(8) in int r.
public class Tools {
public static int twice(int n) {
return n * 2;
}
}
int r = Tools.twice(8);
System.out.println(r);
Show answer
int r = Tools.twice(8);. From another class the call needs the class name and the dot operator, and no Tools object is created.
What keyword in a method header marks it as a class method?
Show answer
static.
Will this call compile from another class? Why or why not?
double d = Converter.toFahrenheit("32");
Show answer
No. The parameter is a double and the argument is a String, so the compiler reports incompatible types: String cannot be converted to double.
From inside Converter, which of these calls to square are legal?
A. square(4);
B. Converter.square(4);
C. new Converter().square(4);
Show answer
A and B. Inside the defining class the class name is optional, so both name the same method. C also compiles in Java, but it is unnecessary for a class method, and the exam writes class-method calls as in A or B.
The Math class is the first library class you will use constantly. It holds the common mathematical operations, and it contains only class methods, so every call is written Math.name(...) with no object. The Math class is part of the java.lang package, which is available by default: no import is needed.
Required content · LO 1.11.A
Learning objective.
1.11.A. Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.
Essential knowledge.
1.11.A.1. The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
1.11.A.2. The Math class contains only class methods. The following Math class methods—including what they do and when they are used—are part of the Java Quick Reference:
static int abs(int x) returns the absolute value of an int value.
static double abs(double x) returns the absolute value of a double value.
static double pow(double base, double exponent) returns the value of the first parameter raised to the power of the second parameter.
static double sqrt(double x) returns the nonnegative square root of a double value.
static double random() returns a double value greater than or equal to 0.0 and less than 1.0.
1.11.A.3. The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range based on specified criteria. Each endpoint of the range can be inclusive, meaning the value is included, or exclusive, meaning the value is not included.
The five methods you need
These are the Math methods on the Java Quick Reference sheet you receive during the exam.
Method
Returns
What it does
static int abs(int x)
int
the absolute value of an int
static double abs(double x)
double
the absolute value of a double
static double pow(double base, double exponent)
double
base raised to the power exponent
static double sqrt(double x)
double
the nonnegative square root of x
static double random()
double
a value greater than or equal to 0.0 and less than 1.0
abs is overloaded: the version that runs depends on the argument type. Note carefully that pow, sqrt, and random always return a double, even when the answer is a whole number.
Because pow returns a double, storing its result in an int needs a cast:
int big = (int) Math.pow(2, 10);
System.out.println(big);
1024
Random numbers
Math.random() returns a double in the interval from 0.0 up to but not including 1.0. Each endpoint of a range is either inclusive (the value can occur) or exclusive (it cannot). Here the lower end is inclusive and the upper end exclusive, written [0.0, 1.0).
You turn that one primitive into any range you want with arithmetic and a cast:
Multiply by the number of values you want: Math.random() * 6 is in [0.0, 6.0).
Cast with (int) to truncate: (int) (Math.random() * 6) is one of 0, 1, 2, 3, 4, 5.
Add the smallest value you want: (int) (Math.random() * 6) + 1 is one of 1 through 6.
For integers from min to max inclusive, the formula is:
int value = (int) (Math.random() * (max - min + 1)) + min;
For a double in [a, b), scale by the width and shift: Math.random() * (b - a) + a.
You can test a formula without waiting for random numbers by feeding it values at the edges of the range. Pretend Math.random() returned r:
r
r * 6
(int) (r * 6)
+ 1
0.0
0.0
0
1
0.16
0.96
0
1
0.17
1.02
1
2
0.5
3.0
3
4
0.999
5.994
5
6
The smallest possible r gives the smallest value and the largest possible r gives the largest, and nothing can produce 7. That is the check to use on any random-range expression.
Worked example · the distance between two points
Find the distance between (1, 2) and (4, 6) with the distance formula.
int x1 = 1;
int y1 = 2;
int x2 = 4;
int y2 = 6;
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
System.out.println(distance);
5.0
Math.pow(3, 2) is 9.0 and Math.pow(4, 2) is 16.0. Their sum, 25.0, has a square root of 5.0. The int arguments were widened to double because the parameters are double.
Worked example · choosing a range
Write an expression for each description, then check the endpoints.
double r = 0.999;
int roll = (int) (r * 6) + 1;
int age = (int) (r * (65 - 18 + 1)) + 18;
int pick = (int) (r * 10);
System.out.println(roll + " " + age + " " + pick);
6 65 9
Description
Expression
Smallest
Largest
a die roll, 1 to 6
(int) (Math.random() * 6) + 1
1
6
an age from 18 to 65 inclusive
(int) (Math.random() * 48) + 18
18
65
a digit, 0 to 9
(int) (Math.random() * 10)
0
9
The 48 comes from 65 - 18 + 1, the number of values in an inclusive range. Forgetting the + 1 is the classic off-by-one mistake: it silently makes the top value impossible.
Worked example · mixed calls and types
Evaluate each statement, noting the type of each result.
int a = Math.abs(-12) + 3;
double b = Math.abs(-12.0) + 3;
double c = Math.pow(3, 2) / 2;
int d = (int) Math.sqrt(30);
System.out.println(a + " " + b + " " + c + " " + d);
15 15.0 4.5 5
Math.abs(-12) uses the int version and returns 12, so a is the int 15. With a double argument the result is a double. Math.pow(3, 2) is 9.0, and 9.0 / 2 is 4.5. Math.sqrt(30) is about 5.477, and the cast truncates it to 5.
Exam focus
Expect the exam to ask for the range of an expression that uses Math.random() (what are the smallest and largest values it can produce, and which are possible) and to ask you to complete a random expression for a stated range. Check the endpoints with the table method. Remember the return types: pow, sqrt, and random return double, and abs returns whatever type it was given. The Math methods on the Java Quick Reference are all you can assume.
7 and 25.0. The absolute value of -7 is 7 (an int), and Math.pow returns a double, so 25 prints as 25.0.
Which expression produces an int from 1 to 10 inclusive?
A. (int) (Math.random() * 10)
B. (int) (Math.random() * 10) + 1
C. (int) (Math.random() * 11)
D. (int) (Math.random() * 10 + 1.0) + 1
Show answer
B. Math.random() * 10 is in [0.0, 10.0), the cast gives 0 through 9, and adding 1 gives 1 through 10. A gives 0 to 9, C gives 0 to 10, and D gives 1 to 11.
What is the smallest and largest value that (int) (Math.random() * 5) + 3 can produce?
Show answer
Smallest 3, largest 7. The cast part is 0 through 4, and the shift of 3 gives 3 through 7. There are five possible values.
Write a statement that stores the cube root idea x squared in an int named sq when x is the int 9, using Math.pow.
int x = 9;
int sq = (int) Math.pow(x, 2);
System.out.println(sq);
Show answer
int sq = (int) Math.pow(x, 2);. The cast is required because Math.pow returns a double, which cannot be stored in an int without one.
12 and 12.0. In the first line, (int) (r * 4) is (int) 2.0, or 2, and adding 10 gives the int 12. The second line never casts, so the sum stays a double.
Why does this code not compile, and how do you fix it?
int root = Math.sqrt(16);
Show answer
Math.sqrt returns a double, and a double cannot be stored in an int without a cast (a possible lossy conversion). Fix it with int root = (int) Math.sqrt(16); or store the result in a double.
Primitive types such as int hold a single value. Most of the data programmers work with is richer than that: a book has a title and a number of pages, a student has a name and a grade. Java models such things with classes and objects. This lesson covers what they are, how a variable refers to an object, and how to create one by calling a constructor. Writing your own classes comes in Unit 3. Here you learn to use classes that someone else wrote, which is how the exam presents them.
Required content · LO 1.12.A, LO 1.12.B, LO 1.13.A, LO 1.13.B, LO 1.13.C
Learning objectives.
1.12.A. Explain the relationship between a class and an object.
1.12.B. Develop code to declare variables to store reference types.
1.13.A. Identify, using its signature, the correct constructor being called.
1.13.B. Develop code to declare variables of the correct types to hold object references.
1.13.C. Develop code to create an object by calling a constructor.
Essential knowledge.
1.12.A.1. An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
1.12.A.2. A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass. Outside the course: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam.
1.12.A.3. All classes in Java are subclasses of the Object class.
1.12.B.1. A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
1.13.A.1. A class contains constructors that are called to create objects. They have the same name as the class.
1.13.A.2. A constructor signature consists of the constructor’s name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
1.13.A.3. Constructors are said to be overloaded when there are multiple constructors with different signatures.
1.13.B.1. A variable of a reference type holds an object reference or, if there is no object, null.
1.13.C.1. An object is typically created using the keyword new followed by a call to one of the class’s constructors.
1.13.C.2. Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
1.13.C.3. A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
1.13.C.4. A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.
Classes and objects
A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. An object is a specific instance of a class with defined attributes. One Book class can produce many Book objects, each with its own title and number of pages.
To use a class, read its documentation. Here is the one we will use for the rest of the unit.
Book constructor
What it does
Book(String t)
creates a book titled t with 100 pages
Book(String t, int p)
creates a book titled t with p pages
Book method
What it does
String getTitle()
returns the title
int getPages()
returns the number of pages
void setPages(int p)
changes the number of pages to p
boolean isLong()
returns true if the book has more than 300 pages
Every class in Java is a subclass of the Object class. Classes can also be related to each other as a superclass and its subclasses, which share attributes and behaviors; designing and implementing those inheritance relationships is outside the scope of this course and the exam.
Variables that refer to objects
A variable of a primitive type holds the value itself. A variable of a reference type holds an object reference, which can be thought of as the memory address of the object. The object lives elsewhere; the variable only says where.
Figure 1.4. A primitive variable stores its value. A reference variable stores a reference, drawn as an arrow, to an object. Assigning one reference to another copies the arrow, not the object.
When no object has been assigned, a reference variable holds the special value null. The declaration alone does not create an object:
Book novel; // a variable that can refer to a Book, holding nothing yet
Book empty = null; // explicitly refers to no object
Creating an object with a constructor
A class contains constructors, which are called to create objects. A constructor has the same name as the class. An object is typically created using the keyword new followed by a call to one of the class's constructors.
Book novel = new Book("Dune", 612);
Book pamphlet = new Book("Tips");
System.out.println(novel.getTitle() + " " + novel.getPages());
System.out.println(pamphlet.getTitle() + " " + pamphlet.getPages());
Dune 612
Tips 100
Parts of the creation statement, left to right: the type of the variable (Book), the variable name (novel), the assignment operator, the keyword new, the constructor call, and the list of arguments. Parameters allow constructors to accept values that establish the initial values of the object's attributes.
### Constructor signatures and overloading
A constructor signature consists of the constructor's name (the class name) and the ordered list of parameter types. When a class has several constructors with different signatures they are overloaded, and the arguments you supply decide which one runs: new Book("Tips") matches Book(String), and new Book("Dune", 612) matches Book(String, int). The arguments must be compatible in number, order, and type with the signature. As with methods, arguments are passed by call by value: the parameters are initialized with copies of the arguments.
A constructor call interrupts the sequential execution of statements. The program runs the constructor's statements first, and when the last one finishes, control returns to the point just after the call.
Worked example · choosing the constructor
Which of these calls compile, and which constructor does each use?
Call
Compiles?
Constructor
new Book("Emma")
yes
Book(String)
new Book("Emma", 474)
yes
Book(String, int)
new Book(474, "Emma")
no
arguments in the wrong order
new Book()
no
no constructor with no parameters
new Book("Emma", 474.5)
no
a double cannot be passed for an int
new Book("Emma", "474")
no
a String cannot be passed for an int
Book b = new Book("Emma", 474);
System.out.println(b.isLong());
true
When a call does not compile, the reason is always one of three: wrong number of arguments, wrong order, or wrong type.
Worked example · references and aliases
Two reference variables can refer to the same object. Assigning one reference variable to another copies the reference, not the object.
Book a = new Book("Atlas", 200);
Book b = a;
b.setPages(350);
System.out.println(a.getPages());
System.out.println(a == b);
350
true
There is only one Book object. b = a made both variables refer to it. The change made through b is visible through a, and a == b is true because the two references hold the same address (comparing references is the subject of Lesson 2.6). Creating a second book with new would give a different object and a different reference.
Worked example · references that refer to nothing
A reference variable that holds null has no object to work with.
Book shelf = null;
System.out.println(shelf == null);
System.out.println(shelf.getPages());
Exception in thread "main" java.lang.NullPointerException
Comparing a reference with null is safe, and it prints true here. Using a null reference to call a method is not: the program stops with a NullPointerException. A variable declared as Book shelf; and never assigned would not even compile if read, as in Lesson 1.4.
Exam focus
Expect questions that give a constructor list and ask which new call is valid or which constructor runs, questions that trace code in which two references share one object, and questions that end in a NullPointerException. State the relationship between a class and an object precisely: the class is the blueprint, an object is one instance. A reference-type variable holds an object reference or null, never the object itself. Inheritance is mentioned only as a fact; you are not asked to design it.
Practice
Which statement correctly creates a Book titled "Poems" with 80 pages?
A. Book b = Book("Poems", 80);
B. Book b = new Book(80, "Poems");
C. Book b = new Book("Poems", 80);
D. Book b = new Book("Poems");
Show answer
C. Creation needs new, and the arguments must match Book(String, int) in order. A omits new, B swaps the arguments, and D uses the one-parameter constructor, which would give 100 pages.
What is printed?
Book x = new Book("Maps", 40);
Book y = new Book("Maps", 40);
System.out.println(x == y);
Book z = x;
System.out.println(x == z);
Show answer
false and true. new was called twice, so x and y refer to two different objects even though they look identical. z = x copies the reference, so x and z refer to the same object.
What is printed?
Book p = new Book("Notes");
Book q = p;
q.setPages(p.getPages() + 50);
System.out.println(p.getPages());
Show answer
150. p and q share one object. The object started with 100 pages, and the setPages call through q raised it to 150.
What is the value of a reference variable that has been declared but has no object?
Show answer
null, the special literal that means the reference is not associated with any object. (A local variable that was never assigned cannot be read at all; a field or an explicit assignment gives null.)
Why does new Book() not compile for the Book class above?
Show answer
The class has only constructors with the signatures Book(String) and Book(String, int). No constructor with an empty parameter list exists, so a call with no arguments matches nothing.
In one sentence each, what is a class and what is an object?
Show answer
A class is the blueprint that defines the attributes and behaviors; an object is one specific instance of the class, with its own values for the attributes.
In Lesson 1.10 you called methods on a class. Most methods in object-oriented code are different: they are called on an object, and they read or change the data stored in that particular object. Two Book objects with different page counts give different answers to the same getPages() call. This lesson is the lesson about the dot operator.
Required content · LO 1.14.A
Learning objective.
1.14.A. Develop code to call instance methods and determine the result of these calls.
Essential knowledge.
1.14.A.1. Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods.
1.14.A.2. A method call on a null reference will result in a NullPointerException.
The dot operator
Instance methods are called on objects of the class. You write the object's name, a dot, the method name, and the arguments.
objectName.methodName(arguments)
The object supplies the data; the arguments supply anything else the method needs. Use the Book class from Lesson 1.12.
Book novel = new Book("Dune", 612);
Book zine = new Book("Tips", 24);
System.out.println(novel.getPages());
System.out.println(zine.getPages());
System.out.println(novel.isLong());
System.out.println(zine.isLong());
612
24
true
false
The same method name gives different answers because each call runs on a different object with different stored data.
What calls return and what they change
A method call has two possible effects, and you should always ask about both.
A returned value.getPages() returns an int. Use it in an expression or store it. The call novel.getPages(); on a line by itself computes the value and discards it.
A change to the object.setPages(int) is void: it changes the stored data and returns nothing, so it appears as a statement by itself.
A method that only returns information about an object is called an accessor. One that changes the object's stored data is a mutator, and is often void. You will write both in Unit 3.
The null trap
A method call on a null reference results in a NullPointerException. The reference must refer to an object before you can use the dot operator on it.
Worked example · reading and changing an object
Trace the object's state.
Book b = new Book("Poems", 80);
b.setPages(b.getPages() * 2);
System.out.println(b.getTitle() + ": " + b.getPages() + " pages");
System.out.println(b.isLong());
b.setPages(b.getPages() + 150);
System.out.println(b.isLong());
After the statement
pages in the object
new Book("Poems", 80)
80
b.setPages(b.getPages() * 2)
160 (the argument is evaluated first: 80 * 2)
b.setPages(b.getPages() + 150)
310
Poems: 160 pages
false
true
The argument b.getPages() * 2 is itself a method call, and it runs before setPages starts. 160 is not above 300, so isLong() is false at first; after the second change the count is 310, and it is true.
Worked example · aliases and method calls
Which output do you get?
Book first = new Book("Alpha", 100);
Book second = new Book("Beta", 200);
Book alias = first;
alias.setPages(999);
second = first;
second.setPages(second.getPages() - 1);
System.out.println(first.getPages());
System.out.println(alias.getPages());
System.out.println(second.getTitle());
998
998
Alpha
alias = first makes both refer to the Alpha book, so setting 999 through alias changes Alpha. second = first then abandons the Beta book (its reference is overwritten) and also refers to Alpha. Subtracting 1 through second makes Alpha's count 998, and all three variables show it.
Worked example · why this will not compile or run
Three mistakes, three different reports.
public class Main {
public static void main(String[] args) {
int count = 5;
System.out.println(count.getPages());
}
}
Main.java:4: error: int cannot be dereferenced
System.out.println(count.getPages());
^
1 error
A primitive has no methods, so the dot operator cannot be applied to an int. Calling a method the class does not define (novel.getAuthor()) fails with cannot find symbol. And calling a method on an object that was never created, for example Book lost = null; lost.getTitle();, compiles but stops with a NullPointerException when it runs.
Exam focus
Expect traces that mix instance method calls with assignment of references, usually with aliasing: the question is how many objects exist and who sees a change. Ask of every call: does it return something I must use, does it change the object, and is the reference non-null? Questions about NullPointerException give you a reference that is null at the moment of the call.
Practice
What is printed?
Book b = new Book("Maps", 50);
b.setPages(70);
System.out.println(b.getPages());
Show answer
70. The setPages call replaced the stored value 50 with 70.
What is printed?
Book b = new Book("Maps", 50);
b.getPages();
b.setPages(b.getPages() + 5);
System.out.println(b.getPages());
Show answer
55. The first call returns 50 but the value is discarded and changes nothing. The second reads 50, adds 5, and stores 55.
How many Book objects exist after this code, and what is printed?
Book u = new Book("One", 10);
Book v = new Book("Two", 20);
Book w = u;
w.setPages(30);
System.out.println(u.getPages() + v.getPages() + w.getPages());
Show answer
Two objects exist (new was called twice). u and w share one, so after setPages(30) the sum is 30 + 20 + 30, which is 80. The sum is an int addition, so no digits are joined.
What happens when this code runs?
Book b = null;
System.out.println(b.getTitle());
Show answer
A NullPointerException. b refers to no object, so there is nothing to run getTitle on. The code compiles; the failure happens at run time.
Which call stores the book's page count in an int named n, given Book b?
Book b = new Book("Nine", 9);
int n = b.getPages();
System.out.println(n);
Show answer
int n = b.getPages();. getPages is an instance method that returns an int, so you call it on the object and store the returned value.
True or false: Book.getPages() is a correct way to ask the book b for its page count.
Show answer
False. getPages is an instance method, so it must be called on an object (b.getPages()). Using the class name would be the form for a static method.
Text is everywhere in programs: names, messages, file contents, user input. Java represents text with the String class. A String object represents a sequence of characters, and because String is part of java.lang it is available by default, with no import. This lesson covers how Strings are created and how they are combined. Lesson 1.15b covers how to take them apart.
Required content · LO 1.15.A
Learning objective.
1.15.A. Develop code to create string objects and determine the result of creating and combining strings.
Essential knowledge.
1.15.A.1. A String object represents a sequence of characters and can be created by using a string literal or by calling the String class constructor.
1.15.A.2. The String class is part of the java.lang package. Classes in the java.lang package are available by default.
1.15.A.3. A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
1.15.A.4. Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object. A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
1.15.A.5. A String object can be concatenated with any object, which implicitly calls the object’s toString method (a behavior that is guaranteed to exist by the inheritance relationship every class has with the Object class). An object’s toString method returns a string value representing the object. Subclasses of Object often override the toString method with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass. Outside the course: Overriding the toString method of a class is outside the scope of the AP Computer Science A course and exam.
Creating Strings
A String object can be created by using a string literal (characters in double quotes) or by calling the String class constructor. Both produce a String object.
String a = "hello";
String b = new String("hello");
String empty = "";
System.out.println(a);
System.out.println(b);
System.out.println("[" + empty + "]");
hello
hello
[]
The empty string "" is a real String object with no characters. It is not the same as null, which means the variable refers to no object at all. Escape sequences work inside any literal, as in Lesson 1.3: \", \\, and \n.
Strings are immutable
A String object is immutable: once it is created, its attributes cannot be changed. Methods called on a String never change the String itself; they return a new one. This single fact explains most String surprises on the exam, because it means that "changing" a String always means assigning a new String to the variable.
String word = "cat";
String longer = word + "s";
System.out.println(word);
System.out.println(longer);
word = word + "s";
System.out.println(word);
cat
cats
cats
Building longer left word untouched. Only the assignment word = word + "s" made the variable word refer to a different String.
Concatenation
Two String objects can be concatenated, or joined, with the + operator or the += operator. The result is a new String object. A primitive value can also be concatenated with a String, which causes an implicit conversion of the primitive to a String.
String name = "Ada";
int age = 36;
double height = 1.7;
boolean student = true;
String line = name + " is " + age + " years old and " + height + " m tall. Student: " + student;
System.out.println(line);
String s = "ab";
s += "cd";
s += 5;
System.out.println(s);
Ada is 36 years old and 1.7 m tall. Student: true
abcd5
### The order of evaluation matters
+ is evaluated left to right. If both operands are numbers it adds; as soon as one operand is a String it concatenates. So the same digits give different results depending on where the first String appears.
Expression
Value
Why
1 + 2 + "x"
"3x"
1 + 2 is addition (3), then "3" + "x"
"x" + 1 + 2
"x12"
"x" + 1 is a String, then "x1" + 2
"x" + (1 + 2)
"x3"
the parentheses force the addition first
"" + 7 + 8
"78"
an empty String starts the concatenation
### Concatenating objects
A String can be concatenated with any object. When that happens, Java implicitly calls the object's toString method, which returns a String value representing the object. That behavior is guaranteed for every class because every class in Java is a subclass of Object. Many classes supply a toString that describes the object; some do not, and the default text is not meaningful, so you do not predict it. Writing your own toString is outside the course. If the object is null, the text null is used.
int a = 4;
int b = 5;
System.out.println(a + b);
System.out.println("Sum: " + a + b);
System.out.println("Sum: " + (a + b));
System.out.println(a + b + " is the sum");
System.out.println(a + " and " + b);
9
Sum: 45
Sum: 9
9 is the sum
4 and 5
The first and fourth lines add before any String is involved, so a + b is 9. In the second, the String comes first, so each later + is concatenation and the digits are joined as 45. Parentheses fix it in the third.
Worked example · building a String over several statements
Trace the value of result.
String result = "";
result += "A";
result = result + 1;
result += 2 + 3;
result = "[" + result + "]";
System.out.println(result);
After the statement
result
String result = "";
""
result += "A";
"A"
result = result + 1;
"A1"
result += 2 + 3;
"A15" (the right side 2 + 3 is evaluated to 5 first)
result = "[" + result + "]";
"[A15]"
[A15]
Worked example · a String with an object
The class Point comes with a toString method that returns its coordinates in parentheses.
Point p = new Point(3, 4);
System.out.println("p = " + p);
String text = "Corner " + p + "!";
System.out.println(text);
p = (3, 4)
Corner (3, 4)!
Concatenating p called its toString method automatically. You never wrote p.toString(). The exam shows classes like this and expects you to reason from the documentation, not to write toString yourself.
Exam focus
Expect questions about the value of a concatenation expression where int values and Strings are mixed, so find the first String and read left to right. Expect questions that depend on immutability: a method call whose result is not assigned leaves the String unchanged. Know that += on a String creates a new object and reassigns. Overriding toString is outside the exam; reading code that calls it implicitly is not.
A12 and 3A. In the first line the String appears first, so both + operators concatenate. In the second line the first + adds two ints to 3, and then 3 is concatenated with "A".
What is printed?
String s = "hi";
s += s;
s += 1 + 1;
System.out.println(s);
Show answer
hihi2. s += s gives hihi. For the next line the right side 1 + 1 is evaluated to 2 first, and hihi2 results.
What is printed?
String first = "Java";
String second = first + "Script";
System.out.println(first);
System.out.println(second);
Show answer
Java, then JavaScript. Concatenation builds a new String and never changes first, because Strings are immutable.
Write one statement that stores the text Total: 15 in a String named msg, using int total = 15;.
int total = 15;
String msg = "Total: " + total;
System.out.println(msg);
Show answer
String msg = "Total: " + total;. The primitive int is converted to a String automatically when it is concatenated.
What is the difference between "" and null for a String variable?
Show answer
"" is a String object that contains no characters, so you can concatenate with it and use String methods on it. null means the variable refers to no object, so calling a method on it throws a NullPointerException.
What is printed?
String t = "ab";
String u = t + "c";
t = u + t;
System.out.println(t + " " + u);
Show answer
abcab abc. u is abc. Then t = u + t joins u and the old value of t (ab), giving abcab. The variable u is unchanged.
Joining Strings is the easy half. The skill the exam rewards is taking a String apart: pulling out a piece, finding a character, checking whether two Strings are the same, putting them in order. This lesson covers the five String methods on the Java Quick Reference, and the one idea underneath all of them: indexes start at zero.
Required content · LO 1.15.B
Learning objective.
1.15.B. Develop code to call methods on string objects and determine the result of calling these methods.
Essential knowledge.
1.15.B.1. A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in a StringIndexOutOfBoundsException.
1.15.B.2. The following String methods—including what they do and when they are used—are part of the Java Quick Reference:
int length() returns the number of characters in a String object.
String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1.
int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found.
boolean equals(Object other) returns true if this corresponds to the same sequence of characters as other; returns false otherwise.
int compareTo(String other) returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. Strings are ordered based upon the alphabet.
Outside the course: Using the equals method to compare one String object with an object of a type other than String is outside the scope of the AP Computer Science A course and exam.
1.15.B.3. A string identical to the single element substring at position index can be created by calling substring(index, index + 1).
Indexes
A String has index values from 0 to one less than its length. The first character is at index 0, and the last is at index length() - 1.
Figure 1.5. Indexes start at 0. substring(2, 5) takes the characters at indexes 2, 3, and 4, which is 5 - 2 = 3 characters.
Trying to use an index outside that range throws a StringIndexOutOfBoundsException while the program runs.
The methods on the Java Quick Reference
Method
Returns
What it does
int length()
int
the number of characters in the String
String substring(int from, int to)
String
the characters from index from through index to - 1
String substring(int from)
String
the same as substring(from, length()): from from to the end
int indexOf(String str)
int
the index of the first occurrence of str, or -1 if it is not found
boolean equals(Object other)
boolean
true if this String has the same sequence of characters as other
int compareTo(String other)
int
negative if this String comes before other, zero if equal, positive if after
String word = "Computer";
System.out.println(word.length());
System.out.println(word.substring(2, 5));
System.out.println(word.substring(5));
System.out.println(word.indexOf("put"));
System.out.println(word.indexOf("z"));
8
mpu
ter
3
-1
Read substring(2, 5) as "start at index 2, stop before index 5": the first index is included and the second is excluded, so you get 5 - 2 = 3 characters.
### One character at a time
The subset has no single-character type. To get the character at a position, take a one-character substring: substring(index, index + 1).
String word = "Computer";
String first = word.substring(0, 1);
String last = word.substring(word.length() - 1);
System.out.println(first + " " + last);
C r
### Comparing Strings
Use equals to test whether two Strings contain the same characters. compareTo orders Strings by the alphabet: the result is negative, zero, or positive. Only the sign is meaningful; do not depend on the exact number. Capital letters sort before lowercase letters.
The last result is negative because a capital Z is ordered before a lowercase a, so "Zebra" comes before "apple". Only the sign of a compareTo result is meaningful: the exact numbers above come from the way Java compares characters, and the exam asks only whether the result is below, equal to, or above zero. The == operator does not compare characters when applied to objects, and Lesson 2.6 explains why equals is the right choice.
### Strings never change
None of these methods changes the String it is called on. The result must be used or stored, or it is lost.
String s = "hello";
s.substring(1);
System.out.println(s);
s = s.substring(1);
System.out.println(s);
hello
ello
Worked example · extracting a name
Split "Grace Hopper" into a first name and a last name by finding the space.
String full = "Grace Hopper";
int space = full.indexOf(" ");
String first = full.substring(0, space);
String last = full.substring(space + 1);
System.out.println(last + ", " + first);
System.out.println(space);
Hopper, Grace
5
Piece
Expression
Value
index of the space
full.indexOf(" ")
5
first name
full.substring(0, 5)
Grace
last name
full.substring(6)
Hopper
The first name ends before the space, so the end index is space, which is excluded. The last name begins after it, so the start index is space + 1.
Worked example · an index that is out of range
What goes wrong, and when?
String s = "Java";
System.out.println(s.substring(1, 3));
System.out.println(s.substring(2, 6));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
The first line prints av; its indexes are inside 0 through 4. The second asks for an end index of 6, but the String has only 4 characters, so its largest legal end index is s.length(). The program compiles; the exception stops it at run time. Similar failures come from substring(-1) and from substring(s.indexOf("z")) when "z" is not found, because indexOf returns -1.
b.substring(0, 3) is "cat", which has the same characters as a. A shorter String that is a prefix of a longer one comes first, so a.compareTo(b) is negative and b.compareTo(a) is positive. The text log begins at index 4 of catalog.
Exam focus
These methods are tested heavily in multiple-choice tracing questions and in the String question of the free-response section. Practice a fixed routine: write the String with its indexes above it, then apply substring(from, to) by counting to - from characters. Look for the -1 that indexOf returns when the text is absent, the excluded end index, and the unassigned result of a String method. Using equals with an argument that is not a String is outside the course.
Practice
What is printed?
String s = "programming";
System.out.println(s.length());
System.out.println(s.substring(3, 7));
System.out.println(s.indexOf("gram"));
Show answer
11, gram, and 3. The word has 11 characters. Indexes 3, 4, 5, and 6 are g, r, a, m, and gram starts at index 3.
2 and -1. indexOf reports the first occurrence only, at index 2, and returns -1 when the text is not found.
Complete the statement so that last holds the last character of word as a String.
String word = "science";
String last = word.substring(word.length() - 1);
System.out.println(last);
Show answer
word.substring(word.length() - 1). The last index is length() - 1, and substring(from) runs to the end of the String. The form word.substring(word.length() - 1, word.length()) is equivalent.
What is printed?
String s = "java";
s.substring(1, 3);
System.out.println(s);
Show answer
java. The call returns "av", but the result is never stored, and Strings are immutable, so s is unchanged.
What happens when this code runs, and why?
String s = "tree";
System.out.println(s.substring(0, 5));
Show answer
A StringIndexOutOfBoundsException. The String has length 4, so the end index cannot be larger than 4. The code compiles, and the failure happens at run time.
Unit 1 review · 10 multiple-choice
Unit 1 review: using objects and methods
Ten exam-style multiple-choice questions running in lesson order from how Java
compiles and runs through expressions, casting, method signatures, the Math class, objects and
Strings: every output below came from actually compiling and running the code, so click an
option and read why it is right or wrong.
Multiple choice
public class Main {
public static void main(String[] args) {
int count = 5;
double rate = 0.5;
int total = count * rate;
System.out.println(total);
}
}
Which of the following best describes the result of attempting to compile and run the program?
Java truncates only when you ask it to with a cast. Nothing here says
(int), so the compiler refuses the assignment rather than quietly throwing away
the 0.5, and no line of the program ever runs.
2.5 is the correct arithmetic value of count * rate, but the
variable it is being stored in is declared int. A value's type and a variable's
type must be compatible before the program can be built at all.
Correct. One int times one double promotes to
double, and a double will not fit in an int slot.
javac reports it at line 5: incompatible types: possible lossy conversion
from double to int. Writing int total = (int) (count * rate); compiles and
prints 2.
A run-time exception happens while the program is executing, which requires the
program to have compiled first. This error is caught by the compiler, so there is no class
file to run and no exception to throw.
int cents = 287;
System.out.println(cents / 100 + " dollars and " + cents % 100 + " cents");
What is printed as a result of executing the code segment?
Correct. Both operands of / are int, so
287 / 100 is 2 with the remainder discarded, and 287 % 100 is that
discarded remainder, 87. The two operators are a matched pair: one gives the whole part, the
other gives what is left over.
This is what you would get if / behaved like a calculator. Integer
division never produces a fractional part; to see 2.87 you would have to write
cents / 100.0 so that one operand is a double.
8 is the first digit of the remainder, not the remainder. % returns
everything left after the last whole 100 is removed, 287 minus 200, which is 87, not 8.
Neither operator leaves cents alone. This answer treats
+ as pure concatenation everywhere, but cents / 100 and
cents % 100 are arithmetic expressions that are evaluated before anything is
joined to a string.
int x = 4;
int y = 9;
x = y;
y = x;
What are the values of x and y after the code segment executes?
This is the swap the code was probably meant to perform, but it is not what
happens. The decisive line is y = x;: by the time it runs, x already
holds 9, so 9 is what gets copied back into y.
Correct. Assignment copies a value at the moment it executes; it does not
record a relationship. Line 3 overwrites the 4 in x, and that 4 is gone forever,
so line 4 copies 9 into y. A real swap needs a third variable:
int temp = x; x = y; y = temp;.
These are the starting values, which would be right only if both assignments
did nothing. Each = is a command to store, so both variables are written to.
4 is the value x loses on line 3, and nothing ever puts it back.
For y to end at 4, the original x would have to have been saved
somewhere before line 3 overwrote it.
What is printed as a result of executing the code segment?
Only the first cast rounds, and it rounds because of the + 0.5
written inside the parentheses, not because casting rounds. Line 3 has no + 0.5,
so it cannot produce 83.
This assumes both lines truncate identically, but the parentheses on line 2
change what gets truncated: 82.6 + 0.5 is 83.1, and the cast chops that to 83.
Parentheses decide the order, so read them before you read the cast.
Correct. Line 2 evaluates 83.1 first and then truncates it to 83; line 3
truncates 82.6 straight down to 82. This is the whole round-half-up idiom in two lines:
(int) always drops the fraction, so you add 0.5 first when you want rounding.
rounded is declared int, so it cannot hold 82.6,
and the value stored in it is the result of the cast, which has no fractional part at all.
The original score is never printed.
int points = 7;
points += 2.8;
System.out.println(points);
What is the value of points after the code segment executes?
10 would require rounding 9.8 up, and nothing here rounds. The implicit cast
that compound assignment performs behaves exactly like (int): it discards the
fractional part instead of rounding it.
Correct. points += 2.8; means points = (int) (points +
2.8);. The sum 9.8 is computed as a double and then narrowed, so the 0.8
is thrown away and 9 is stored: the silent truncation that makes compound assignment worth
watching.
points is declared int and an int
variable can never hold 9.8. 9.8 is the intermediate value of the addition, not the value
that survives the assignment.
This is the difference between points += 2.8; and
points = points + 2.8;. The second form really is a compile-time error; the
compound form compiles because it carries a built-in narrowing cast.
public class Converter {
public static double milesToKm(double miles) {
return miles * 1.609;
}
public static String formatLabel(String name, int count) {
return name + ": " + count;
}
}
Each of the following statements appears in the main method of another class. Which one causes a compile-time error?
This compiles and returns 8.045. An int argument is widened to
double automatically, because no information is lost going from 5 to 5.0:
widening is the one conversion Java performs for you.
This compiles and returns laps: 3. The first argument is a
String and the second an int, matching the parameter list
(String name, int count) position by position.
Correct. Arguments are matched to parameters by position, never by name or by
guesswork, so 3 lands on the String parameter. javac reports
incompatible types: int cannot be converted to String. Swapping the two arguments
fixes it.
This compiles and returns 4.0225. A double literal passed to a
double parameter needs no conversion at all, so it is the least problematic call
of the four.
// roll should end up holding a whole number
// from 5 through 20, with every value possible
int roll = /* missing code */;
System.out.println(roll);
Which replacement for /* missing code */ makes the segment work as intended for every possible value returned by Math.random?
This comes from multiplying by the larger endpoint instead of the count of
values. Running it 400,000 times produces values from 5 up to 24, so it overshoots the range
by four.
Correct. The range 5 through 20 contains 20 - 5 + 1, or 16,
different values. Math.random() returns at least 0.0 and always less than 1.0,
so Math.random() * 16 truncates to 0 through 15, and adding 5 shifts that to 5
through 20. Testing both ends confirms it: 0.0 gives 5, and 0.999999 gives 20.
Using high - low instead of high - low + 1 loses one
value. The truncated product runs 0 through 14, so the largest result is 19 and the value 20
can never occur.
21 is the count of values from 0 through 20, but the range does not start at 0.
Because 5 is added afterwards, this reaches 25, which is five past the intended top.
public class Rectangle {
private double width;
private double height;
public Rectangle(double w, double h) { width = w; height = h; }
public void setWidth(double w) { width = w; }
public double getWidth() { return width; }
public double getArea() { return width * height; }
}
Rectangle a = new Rectangle(3.0, 4.0);
Rectangle b = new Rectangle(5.0, 2.0);
b = a;
b.setWidth(10.0);
System.out.println(a.getArea() + " " + b.getArea());
What is printed as a result of executing the code segment?
This treats b = a; as copying the rectangle rather than copying a
reference. If there were still two objects, a would keep its area of 12.0, but
after line 3 there is only one object with two names.
Correct. Line 3 stores the address in a into b, so
both variables now point at the 3.0-by-4.0 object and the 5.0-by-2.0 object becomes
unreachable. Line 4 is the decisive step: setting the width through b changes
the one shared object to 10.0 by 4.0, and both calls report 40.0.
10.0 is the new width, not the area. getArea returns
width * height, and the height of the surviving object is still 4.0.
20.0 would be the area of the second rectangle after its width changed to 10.0,
but that object was abandoned on line 3 and setWidth never touches it. Draw the
two arrows before answering an aliasing question.
public class BankAccount {
private double balance;
public BankAccount(double startingBalance) { balance = startingBalance; }
public void deposit(double amount) { balance = balance + amount; }
public void withdraw(double amount) { balance = balance - amount; }
public double getBalance() { return balance; }
}
// in a different class, intended to return twice the account's balance
public static double doubledBalance(BankAccount acct) {
/* missing code */
}
Which replacement for /* missing code */ makes the method work as intended?
balance is declared private, so it is visible only
inside BankAccount. javac reports balance has private access in
BankAccount; the accessor method is the only door into that field.
getBalance is an instance method, so it needs an object, not a
class name. The compiler says non-static method getBalance() cannot be referenced from a
static context: a class name works only for static methods such as
Math.sqrt.
Correct. An instance method is called on a reference with the dot operator,
and because getBalance returns a double, the call can sit inside a
larger expression. Passing an account holding 325.50 returns 651.0.
This writes the object as an argument instead of as the receiver. There is no
method named getBalance in the class doing the calling, so the compiler reports
cannot find symbol.
String word = "Programming";
System.out.println(word.substring(3, 7) + word.indexOf("gram"));
What is printed as a result of executing the code segment?
This starts counting at index 1 instead of 0. Index 0 is P, 1 is r, 2 is o and
3 is g, so substring(3, 7) begins at the g, not at the r after it.
Five characters would come from substring(3, 8). The second
argument of substring is the index where the piece stops, and that
character is not included, so indexes 3, 4, 5 and 6 give exactly four characters.
Correct. substring(3, 7) takes indexes 3 through 6 of
Programming, which is gram, and indexOf("gram") returns the index
where that match begins, which is 3. The + then joins a String to an int, so the
int is converted to text and the line prints gram3 with no space.
4 would be the position of gram if the first character were
numbered 1. Java indexes Strings from 0, which is also why indexOf can use
-1 as its "not found" signal.
Unit 1 gave you sequencing: statements run one after another, in order. That is enough to compute a total or print a receipt, but not enough to make a decision or to do something a thousand times. This unit adds the other two building blocks of algorithms: selection and repetition. Before you meet the Java for them, this lesson looks at the ideas in plain language and in diagrams, because designing the algorithm is always the first step.
Required content · LO 2.1.A
Learning objective.
2.1.A. Represent patterns and algorithms that involve selection and repetition found in everyday life using written language or diagrams.
Essential knowledge.
2.1.A.1. The building blocks of algorithms include sequencing, selection, and repetition.
2.1.A.2. Algorithms can contain selection, through decision making, and repetition, via looping.
2.1.A.3. Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
2.1.A.4. Repetition is when a process repeats itself until a desired outcome is reached.
2.1.A.5. The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm.
The three building blocks
Sequencing runs steps one at a time in a defined order.
Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision. "If it is raining, take an umbrella" is selection.
Repetition is when a process repeats itself until a desired outcome is reached. "Keep stirring until the sugar dissolves" is repetition. In code it is called iteration, or looping.
Algorithms can contain selection through decision making and repetition through looping, and any algorithm you will write this year is built from just these three pieces. The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm: the same steps in a different arrangement can produce a different result.
Describing selection and repetition
Written language works well for short algorithms. Diagrams, such as flowcharts, show the structure at a glance. A diamond is a true or false decision, a box is a step, and an arrow that points back up is a loop.
Figure 2.1. A countdown. The diamond is a true or false decision (selection); the arrow that returns to it repeats the steps below (repetition). When count is no longer greater than 0, the no branch ends the loop.
The same algorithm in words:
Set count to 3.
If count is greater than 0, display count, subtract 1 from count, and go back to step 2.
Otherwise display Liftoff and stop.
Step 2 contains both blocks at once: the test is selection, and going back to the test is repetition. In Java the same algorithm reads as follows. You will learn each piece of this syntax in the lessons ahead; for now, match it to the diagram.
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Liftoff");
3
2
1
Liftoff
Worked example · selection in plain language and code
Write an algorithm that tells a customer whether a total qualifies for free shipping (an order of $50 or more).
Read the order total.
If the total is at least 50, display "Free shipping".
Otherwise display "Shipping applies".
The decision splits the path into two branches and exactly one of them runs. In Java:
int total = 62;
if (total >= 50) {
System.out.println("Free shipping");
} else {
System.out.println("Shipping applies");
}
Free shipping
With total set to 40 the other branch runs. A test of an algorithm with selection needs at least one input for each branch.
Worked example · repetition until a goal is reached
You put $1 in a jar and double the amount in the jar every day. How many days until the jar holds more than $100?
Set days to 0 and amount to 1.
As long as amount is 100 or less, double amount and add 1 to days.
Display days.
int amount = 1;
int days = 0;
while (amount <= 100) {
amount = amount * 2;
days++;
}
System.out.println(days + " days, amount " + amount);
7 days, amount 128
days
0
1
2
3
4
5
6
7
amount
1
2
4
8
16
32
64
128
The algorithm repeats until a desired outcome is reached: the number of days was never known in advance.
Worked example · the order of the blocks changes the result
A bank account holds $30 and a customer asks for $50. Two designs of the same withdrawal differ only in order.
int balance = 30;
int request = 50;
if (balance >= request) {
balance = balance - request;
}
System.out.println("check first: " + balance);
check first: 30
int balance = 30;
int request = 50;
balance = balance - request;
if (balance < 0) {
System.out.println("overdrawn");
}
System.out.println("subtract first: " + balance);
overdrawn
subtract first: -20
Both designs use one sequence step and one selection, but only the first protects the account, because it makes the decision before the subtraction. The order of the building blocks is part of the algorithm.
Exam focus
This topic is tested as design and tracing without much Java: given a description, identify which building blocks it uses, put the steps in an order that works, and say what a flowchart or a short code segment produces. Name each block when you see it: a true or false test is selection, a path that returns to an earlier step is repetition. When you test, run one input down every branch of every decision.
Practice
Which building block does each phrase describe? (a) Do steps 1, 2, and 3 in that order. (b) If the password is wrong, show an error. (c) Keep asking until the answer is valid.
Show answer
(a) sequencing, (b) selection, (c) repetition. A true or false decision is selection, and a process that repeats until an outcome is reached is repetition.
What does this code print?
int n = 3;
while (n > 0) {
System.out.print(n + " ");
n--;
}
System.out.println("go");
Show answer
3 2 1 go. The loop shows n and reduces it until n is 0, then the last statement runs once.
A flowchart has a decision diamond whose "no" arrow leads back to a step above it. Which building block is that arrow?
Show answer
Repetition. An arrow that returns to an earlier step repeats part of the algorithm until the decision comes out the other way.
An algorithm should add 5 to x only if x is below 10, then double x. Does swapping the two steps change the result for x = 8?
int x = 8;
if (x < 10) {
x = x + 5;
}
x = x * 2;
System.out.println(x);
int y = 8;
y = y * 2;
if (y < 10) {
y = y + 5;
}
System.out.println(y);
Show answer
Yes. In the first order x becomes 13 and then 26. In the second order y becomes 16 first, so the test y < 10 is false and 5 is never added, leaving 16.
How many branches does an algorithm with one true or false decision have, and how many of them run in a single execution?
Show answer
Two branches (the true branch and the false branch). Exactly one of them runs each time the decision is evaluated.
Write the steps in words of an algorithm that finds how many times 4 can be subtracted from 30 before the result is below 4.
Show answer
1. Set count to 0 and rest to 30. 2. As long as rest is at least 4, subtract 4 from rest and add 1 to count. 3. Display count. For 30 the loop runs 7 times, leaving 2.
Selection and repetition both depend on one kind of value: true or false. A Boolean expression produces one of them, and it is the question a program asks before deciding what to do next. In this lesson you build those questions with the relational operators, and you learn to read them without making the mistakes that cause most Boolean bugs.
Required content · LO 2.2.A
Learning objective.
2.2.A. Develop code to create Boolean expressions with relational operators and determine the result of these expressions.
Essential knowledge.
2.2.A.1. Values can be compared using the relational operators == and != to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references.
2.2.A.2. Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values.
2.2.A.3. An expression involving relational operators evaluates to a Boolean value.
The relational operators
Values can be compared using relational operators. The result is always a boolean.
Operator
Meaning
Example
Value
==
is equal to
5 == 5
true
!=
is not equal to
5 != 5
false
<
is less than
3 < 8
true
>
is greater than
3 > 8
false
<=
is less than or equal to
4 <= 4
true
>=
is greater than or equal to
3 >= 4
false
== and != test whether two values are the same, and they work on any type. With primitive types they compare the actual primitive values. With reference types they compare the object references (Lesson 2.6 explains what that means). The four ordering operators, <, >, <=, and >=, apply to numeric values. An expression that uses relational operators evaluates to a Boolean value, so you can print it, store it in a boolean variable, or use it as the condition of a statement.
int age = 16;
boolean canDrive = age >= 16;
boolean isAdult = age >= 18;
System.out.println(canDrive);
System.out.println(isAdult);
System.out.println(age != 16);
true
false
false
The statement boolean canDrive = age >= 16; stores the answer to the question. You do not need an if to produce a Boolean value.
Pitfalls
### = is not ==
A single = is assignment; a double == is comparison. Using = where a condition is needed is a very common mistake, and with int values the compiler catches it.
public class Main {
public static void main(String[] args) {
int x = 3;
if (x = 5) {
System.out.println("five");
}
}
}
Main.java:4: error: incompatible types: int cannot be converted to boolean
if (x = 5) {
^
1 error
### Comparing real numbers
Because of round-off error (Lesson 1.5), do not test two computed double values for equality with ==.
double a = 0.1 + 0.2;
System.out.println(a == 0.3);
System.out.println(a > 0.29 && a < 0.31);
false
true
When a double result must be compared, check whether it is close enough instead of exactly equal. (The && in the second test is explained in Lesson 2.5: it means "and".)
### Remainder tests
The remainder operator makes useful Boolean expressions: n % 2 == 0 is true when n is even, and n % 5 == 0 is true when n is a multiple of 5.
Worked example · evaluating expressions
Give the value of each expression when x is 7 and y is 12.
int x = 7;
int y = 12;
System.out.println(x < y);
System.out.println(x == y - 5);
System.out.println(y % x == 5);
System.out.println(y / x >= 2);
System.out.println(x * 2 != y + 2);
true
true
true
false
false
Expression
Work
Value
x < y
7 < 12
true
x == y - 5
arithmetic first: 7 == 7
true
y % x == 5
12 % 7 is 5, so 5 == 5
true
y / x >= 2
integer division: 1 >= 2
false
x * 2 != y + 2
14 != 14
false
Arithmetic operators are evaluated before relational operators, so x == y - 5 needs no parentheses.
Worked example · writing the expression for a description
Write a Boolean expression for each description.
Description
Expression
score is at least 60
score >= 60
n is even
n % 2 == 0
n is odd
n % 2 == 1 (or n % 2 != 0)
a is a multiple of b
a % b == 0
side is not 0
side != 0
price is under 20
price < 20
int n = 14;
boolean even = n % 2 == 0;
boolean multipleOfFive = n % 5 == 0;
System.out.println(even + " " + multipleOfFive);
true false
For "at most" use <=, for "at least" use >=, and for "more than" or "fewer than" use > and <. A boundary mistake, such as > where >= was meant, is an off-by-one error in the decision.
Worked example · a boundary
A ride requires riders to be at least 48 inches tall. Which riders pass?
int h1 = 47;
int h2 = 48;
int h3 = 49;
System.out.println(h1 >= 48);
System.out.println(h2 >= 48);
System.out.println(h3 >= 48);
System.out.println(h2 > 48);
false
true
true
false
A rider of exactly 48 inches passes with >= but fails with >. Always test the boundary value itself: it is where most Boolean bugs hide.
Exam focus
Expect to evaluate Boolean expressions that mix arithmetic and comparison, and to choose which operator expresses a description. The usual errors: > for >=, using = for comparison, and forgetting integer division inside an expression. Remember that == on references compares the references (Lesson 2.6) and that <, >, <=, and >= are for numbers.
Practice
What is printed?
int a = 5;
int b = 9;
System.out.println(a < b);
System.out.println(a * 2 == b + 1);
System.out.println(b % a != 4);
Show answer
true, true, false. 5 < 9 is true. 10 == 10 is true. 9 % 5 is 4, so 4 != 4 is false.
Which expression is true exactly when n is a positive even number? (Positive means greater than 0.)
A. n % 2 == 0
B. n > 0
C. n % 2 == 0 && n > 0
D. n > 0 || n % 2 == 0
Show answer
C. It needs both conditions, which is what && ("and") expresses (Lesson 2.5). A is true for 0 and negative even numbers, B for odd numbers, and D is true when either part is true.
What is stored in ok?
int items = 10;
boolean ok = items / 3 == 3;
System.out.println(ok);
Show answer
true. 10 / 3 is integer division and equals 3, so the comparison 3 == 3 is true.
A programmer wrote if (score = 100) to test for a perfect score. What goes wrong, and what is the fix?
Show answer
= assigns, and the assignment expression is an int, not a boolean, so the compiler rejects it. The fix is if (score == 100).
Write a Boolean expression that is true when the double variable price is at most 19.99.
A program that can only run straight down the page cannot respond to anything. The if statement is how code decides: it runs one segment of code or another depending on the value of a Boolean expression. Every game that reacts to a click and every form that rejects a bad entry uses it.
Required content · LO 2.3.A
Learning objective.
2.3.A. Develop code to represent branching logical processes by using selection statements and determine the result of these processes.
Essential knowledge.
2.3.A.1. Selection statements change the sequential execution of statements.
2.3.A.2. An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
2.3.A.3. A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
2.3.A.4. A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
Selection statements
Selection statements change the sequential execution of statements. The if statement affects the flow of control by executing different segments of code based on the value of a Boolean expression.
### One-way selection
A one-way selection, an if statement alone, is used when there is a segment of code to execute under a certain condition. The body runs only when the Boolean expression is true; otherwise it is skipped, and execution continues after the closing brace.
int temp = 35;
if (temp < 40) {
System.out.println("Wear a coat");
}
System.out.println("Have a good day");
Wear a coat
Have a good day
### Two-way selection
A two-way selection, an if-else statement, is used when there are two segments of code: one for when the Boolean expression is true and another for when it is false. The body of the if runs when the expression is true, and the body of the else runs when it is false. Exactly one of the two runs.
Figure 2.2. A two-way selection. Exactly one of the two bodies runs, and then both paths join and execution continues with the statement after the if-else.
int score = 55;
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Retake");
}
Retake
Details that matter
The condition is always in parentheses and must be a Boolean expression.
Use braces around every body, even a one-line body. Without braces, an if controls only the single statement that follows it, and an added second line looks as though it belongs to the if but does not.
There is no semicolon after the condition. if (x > 5); ends the statement immediately, so the "body" that follows always runs.
int x = 3;
if (x > 5)
System.out.println("big");
System.out.println("done");
done
Here if (x > 5) controls only the first println. The second prints no matter what, even though its indentation suggests otherwise. The compiler ignores indentation, and so must you when you trace code.
Selection inside methods
Methods often use selection to decide what to return. A return statement ends the method immediately.
public static int absoluteValue(int n) {
if (n < 0) {
return -n;
}
return n;
}
If the if is true the method returns inside the body. If not, execution reaches the second return. A method with a non-void return type must return a value on every possible path, or the compiler rejects it.
Worked example · tracing one-way and two-way selection
Trace the output for each starting value of n.
int n = 7;
int result = 0;
if (n % 2 == 0) {
result = n / 2;
} else {
result = 3 * n + 1;
}
if (result > 20) {
result = 20;
}
System.out.println(result);
20
n
n % 2 == 0
after the first if
result > 20
printed
7
false
3 * 7 + 1 = 22
true
20
8
true
8 / 2 = 4
false
4
40
true
40 / 2 = 20
false
20
The first if-else always runs exactly one body, and the second if is one-way: it may do nothing. The two statements are independent.
Worked example · writing the larger of two values
Write a method max2 that returns the larger of two int values.
public static int max2(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
Tests that matter: each branch (a larger, b larger), and the equal case, which falls into the else and returns b, the same value as a.
Worked example · what the compiler or run shows when braces are missing
A programmer wanted to print two lines when the order is large.
int items = 2;
if (items > 10)
System.out.println("Large order");
System.out.println("Thanks for ordering");
System.out.println("Items: " + items);
Thanks for ordering
Items: 2
Only the first println belongs to the if. The thank-you message prints for every order. Adding braces around both lines fixes it. This is a logic error: the program compiles and runs, and only testing a small order reveals it.
Exam focus
Expect tracing questions where two or three if statements follow one another, so check whether each is independent or paired with an else. Watch for a missing brace, a stray semicolon after the condition, and a method whose branches fail to return a value on every path. When you are asked to complete code, test one input for each branch.
Practice
What is printed?
int a = 6;
if (a > 4) {
a = a + 10;
}
if (a > 12) {
a = a - 5;
}
System.out.println(a);
Show answer
11. The first test is true, so a becomes 16. The second test is true as well (16 > 12), so a becomes 11. Both ifs are independent and both ran.
What is printed?
int a = 6;
if (a > 4) {
a = a + 10;
} else {
a = a - 5;
}
System.out.println(a);
Show answer
16. Now the second block is the else of the first, so only one body runs: the condition is true, a becomes 16, and the else is skipped.
What does this print, and why?
int n = 4;
if (n > 10);
{
System.out.println("big");
}
Show answer
big. The semicolon after the condition ends the if statement, so the if has an empty body. The braced block that follows is an ordinary block that always runs.
Write a method isPositive that returns true if the int parameter is greater than 0 and false otherwise.
public static boolean isPositive(int n) {
if (n > 0) {
return true;
} else {
return false;
}
}
The method above works. A shorter and equivalent version is return n > 0;, because the expression already is true or false.
What is printed when x is 10?
int x = 10;
if (x < 5) {
System.out.println("A");
} else {
System.out.println("B");
}
System.out.println("C");
Show answer
B and C. The condition is false, so the else body runs, and the last statement runs in every case.
Why does this method fail to compile?
public static String sign(int n) {
if (n > 0) {
return "positive";
} else if (n < 0) {
return "negative";
}
}
Show answer
If n is 0 neither condition is true and no return runs, so the method has a path with no return value. The compiler requires a non-void method to return on every path. Adding return "zero"; after the if fixes it.
Real decisions have more than two outcomes: a grade is an A, B, C, D, or F; a ticket price depends on age and on the day. Java builds those decisions by putting if statements inside one another, or by chaining them. This lesson covers both forms and, more importantly, how to tell exactly which branch runs for a given input.
Required content · LO 2.4.A
Learning objective.
2.4.A. Develop code to represent nested branching logical processes and determine the result of these processes.
Essential knowledge.
2.4.A.1. Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
2.4.A.2. The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
2.4.A.3. A multiway selection (if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multiway selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.
Nested if statements
Nested if statements consist of if, if-else, or if-else-if statements within other if, if-else, or if-else-if statements. The Boolean expression of the inner statement is evaluated only if the outer expression is true (or, for an inner statement inside an else, only if the outer expression is false).
int age = 15;
boolean weekend = true;
if (age < 18) {
if (weekend) {
System.out.println("Student weekend price");
} else {
System.out.println("Student weekday price");
}
} else {
System.out.println("Adult price");
}
Student weekend price
Read it as a tree: the first question is age; only if the answer is "under 18" is the second question asked. For an adult the weekend variable is never examined.
Multiway selection: if-else-if
A multiway selection (if-else-if) is used when there is a series of expressions with different segments of code for each condition. It is performed so that no more than one segment of code is executed, based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else, the body of that else runs.
The tests are checked from the top, and the chain stops at the first true one. When score is 84 the first test is false and the second is true, so "B" is assigned and every later test is skipped. Because the earlier tests already failed, each later test can be shorter: reaching score >= 80 means score is already below 90.
### Order matters
Reversing the order of those tests breaks the program:
A 95 is at least 70, so the first test is true and the chain stops there. Put the most restrictive condition first.
### A chain is not the same as separate ifs
int n = 15;
if (n > 5) {
System.out.println("over 5");
}
if (n > 10) {
System.out.println("over 10");
}
if (n > 5) {
System.out.println("chain: over 5");
} else if (n > 10) {
System.out.println("chain: over 10");
}
over 5
over 10
chain: over 5
Separate if statements are each tested, so both messages print. In the chain only the first true branch runs, so "over 10" can never print: n > 5 is true whenever n > 10 is.
Which if does an else belong to?
An else always pairs with the nearest unmatched if above it, no matter how the code is indented. Braces remove all doubt, and the exam's code often includes braces for exactly that reason.
Worked example · tracing a nested decision
Trace the output for each pair of inputs.
int x = 12;
int y = 7;
if (x > 10) {
if (y > 10) {
System.out.println("A");
} else {
System.out.println("B");
}
} else {
System.out.println("C");
}
System.out.println("D");
B
D
x
y
outer test x > 10
inner test y > 10
printed
12
7
true
false
B, D
12
20
true
true
A, D
5
20
false
not evaluated
C, D
Worked example · writing a ticket price method
Tickets cost $6 for children under 13, $9 for ages 13 to 64, and $7 for seniors 65 and over.
public static int ticketPrice(int age) {
if (age < 13) {
return 6;
} else if (age < 65) {
return 9;
} else {
return 7;
}
}
The second test age < 65 is reached only if age >= 13, so it covers exactly ages 13 through 64. Test both sides of each boundary, as the four calls do.
Worked example · a chain with a trailing else versus without
What happens for a value that matches nothing?
int n = 0;
String label = "none";
if (n > 0) {
label = "positive";
} else if (n < 0) {
label = "negative";
}
System.out.println(label);
none
When no condition is true and there is no trailing else, the chain does nothing at all, so label keeps its starting value. Giving the variable a sensible starting value before the chain is a good habit, and a trailing else is the right place for a catch-all case.
Exam focus
Expect to be given an input and asked which branch runs, or what is printed, for code that nests if statements or chains them with else if. Decide first whether you are looking at a chain (at most one body runs, the first true one) or at separate if statements (each is tested). Check the order of the tests, and test the boundary values on both sides.
Practice
What is printed?
int n = 50;
if (n > 10) {
System.out.println("A");
} else if (n > 40) {
System.out.println("B");
} else {
System.out.println("C");
}
Show answer
A. The first test is true, so the chain stops. The else if test (which is also true) is never evaluated.
What is printed?
int n = 50;
if (n > 10) {
System.out.println("A");
}
if (n > 40) {
System.out.println("B");
} else {
System.out.println("C");
}
Show answer
A and B. These are two separate statements. The first if is one-way and prints A. The second is an if-else and prints B because 50 is greater than 40.
Which values of t print warm?
int t = 20;
if (t < 0) {
System.out.println("freezing");
} else if (t < 15) {
System.out.println("cold");
} else if (t < 25) {
System.out.println("warm");
} else {
System.out.println("hot");
}
Show answer
Values from 15 through 24. Reaching the third test means t is not below 0 and not below 15, so t < 25 selects 15 through 24.
What is printed?
int a = 3;
int b = 8;
if (a > 5) {
if (b > 5) {
System.out.println("both");
}
} else {
System.out.println("neither");
}
System.out.println("end");
Show answer
neither and then end. The else pairs with the outer if, because the inner if has its own braces. The outer test a > 5 is false, so the else body runs, and the inner test is never evaluated.
Write a method category that returns "small" for n below 10, "medium" for 10 through 99, and "large" for 100 or more.
public static String category(int n) {
if (n < 10) {
return "small";
} else if (n < 100) {
return "medium";
} else {
return "large";
}
}
A single comparison answers a single question, but real conditions combine questions: the age is between 13 and 19, the entry is not empty and also not too long, a seat is free or the buyer is on the waiting list. Java combines Boolean expressions with three logical operators. This lesson teaches how each one works, in what order they run, and the rule about when the second half of a condition is never evaluated at all.
Required content · LO 2.5.A
Learning objective.
2.5.A. Develop code to represent compound Boolean expressions and determine the result of these expressions.
Essential knowledge.
2.5.A.1. Logical operators ! (not), && (and), and || (or) are used with Boolean expressions. The expression !a evaluates to true if a is false and evaluates to false otherwise. The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise. The expression a || b evaluates to true if a is true, b is true, or both, and evaluates to false otherwise. The order of precedence for evaluating logical operators is ! (not), && (and), then || (or). An expression involving logical operators evaluates to a Boolean value.
2.5.A.2. Short-circuit evaluation occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated.
The logical operators
Operator
Name
The expression is true when
!a
not
a is false
a && b
and
both a and b are true
a || b
or
a is true, b is true, or both
The complete truth table for two Boolean values:
a
b
!a
a && b
a || b
true
true
false
true
true
true
false
false
false
true
false
true
true
false
true
false
false
true
false
false
An expression that uses logical operators evaluates to a Boolean value, so it can be a condition, be printed, or be stored in a boolean variable.
### Order of evaluation
The order of precedence for the logical operators is ! (not) first, then && (and), then || (or). Arithmetic and relational operators run before all three. Parentheses override the order, and a reader appreciates them even when they are not needed.
boolean a = true;
boolean b = false;
boolean c = true;
System.out.println(a || b && c);
System.out.println((a || b) && c);
System.out.println(!a || c);
System.out.println(!(a || c));
System.out.println(a && !b);
true
true
true
false
true
The first line is a || (b && c), which is true || false, which is true. In the fourth line the parentheses make ! apply to the whole a || c (true), giving false.
Short-circuit evaluation
Short-circuit evaluation occurs when the result of an && or || can be determined by evaluating only the first Boolean expression. In that case the second expression is not evaluated.
false && anything is false, so Java never looks at the right side.
true || anything is true, so Java never looks at the right side.
You can watch it happen with a method that announces itself when it runs.
check("B", true) and check("D", false) never ran, so there is no checking B or checking D. Short-circuiting is not only a speed-up; it lets a condition protect itself.
int d = 0;
if (d != 0 && 10 / d > 2) {
System.out.println("big quotient");
} else {
System.out.println("skipped");
}
skipped
Because d != 0 is false, the division is never attempted. With the two tests in the opposite order, the division would run first and throw an ArithmeticException.
Writing compound conditions
Each side of && or || must be a complete Boolean expression. Two mistakes come from borrowing the shorthand of ordinary math.
public class Main {
public static void main(String[] args) {
int x = 5;
if (1 <= x <= 10) {
System.out.println("in range");
}
}
}
Main.java:4: error: bad operand types for binary operator '<='
if (1 <= x <= 10) {
^
first type: boolean
second type: int
1 error
1 <= x is evaluated first and is a boolean, which cannot be compared with 10. The correct range test is x >= 1 && x <= 10. Likewise x == 1 || 2 is rejected, because 2 is not a Boolean expression; write x == 1 || x == 2.
Worked example · evaluating with precedence
Let a be true, b be false, and c be true. Evaluate each expression.
boolean a = true;
boolean b = false;
boolean c = true;
System.out.println(a && b || c);
System.out.println(a && (b || c));
System.out.println(!b && c);
System.out.println(!(b || c));
System.out.println(a || b && !c);
System.out.println(!a || b && c);
true
true
true
false
true
false
Expression
Grouped by precedence
Value
a && b || c
(a && b) || c is false || true
true
a && (b || c)
true && true
true
!b && c
(!b) && c is true && true
true
!(b || c)
!(true)
false
a || b && !c
a || (b && (!c)) is true || false
true
!a || b && c
(!a) || (b && c) is false || false
false
Worked example · writing conditions from descriptions
Write each condition, then test it at the boundaries.
"Between" almost always means && with a lower and an upper test. "Outside" almost always means ||. Choose the operator by asking whether both parts must hold at once (&&) or either one is enough (||).
Worked example · a condition that guards itself
A method decides whether part is more than half of whole, and must not divide by zero.
public static boolean overHalf(int part, int whole) {
return whole != 0 && (double) part / whole > 0.5;
}
The call with a whole of 0 returns false instead of failing: the first test is false, so the division on the right of && is never evaluated. Swapping the two operands would make that call throw an exception.
Exam focus
Expect questions that give values for two or three Boolean variables and ask for the value of a compound expression, and questions that ask which condition correctly describes a stated range. Use the precedence !, then &&, then ||, and write in the parentheses before you evaluate. Short-circuiting appears as a question about whether a statement in the second operand runs, or as the reason a guard test (d != 0 && ...) is safe.
true, false, true. !q is true, so p && !q is true. !p is false and q is false, so the || gives false. p && q is false, and the ! makes it true.
Which expression is true when x is between 0 and 100, inclusive?
A. x >= 0 || x <= 100
B. x > 0 && x < 100
C. x >= 0 && x <= 100
D. 0 <= x <= 100
Show answer
C. A is true for every number, B leaves out 0 and 100, and D does not compile because 0 <= x is a boolean that cannot be compared with 100.
What is printed? Does the method ping run?
public static boolean ping() {
System.out.println("ping");
return true;
}
int n = 5;
if (n > 10 && ping()) {
System.out.println("yes");
} else {
System.out.println("no");
}
Show answer
no, and ping never runs. n > 10 is false, so && short-circuits and the right side is not evaluated.
What is printed?
int a = 4;
int b = 9;
System.out.println(a < 5 || b / 0 > 1);
Show answer
true. a < 5 is true, so the || short-circuits and the division by zero is never evaluated. With && in place of || the code would throw an ArithmeticException.
Write a condition that is true when the String variable answer is neither "yes" nor "no".
!answer.equals("yes") && !answer.equals("no"). Both tests must hold, so the operator is &&. (The equivalent !(answer.equals("yes") || answer.equals("no")) is the subject of Lesson 2.6.)
What is printed?
int x = 6;
System.out.println(x > 2 && x < 10 || x == 0);
System.out.println(x > 2 && (x > 8 || x == 0));
Show answer
true and false. The first groups as (x > 2 && x < 10) || (x == 0), which is true. In the second, the parentheses make the || part false || false, so the whole expression is false.
Two different conditions can mean exactly the same thing: !(score >= 60) and score < 60 accept the same scores. Programmers care, because the shorter or simpler version is easier to read and less likely to hide a bug, and exam questions ask whether two expressions can be swapped. This lesson gives you two tools for proving it: truth tables, and De Morgan's laws.
Required content · LO 2.6.A
Learning objective.
2.6.A. Compare equivalent Boolean expressions.
Essential knowledge.
2.6.A.1. Two Boolean expressions are equivalent if they evaluate to the same value in all cases. Truth tables can be used to prove Boolean expressions are equivalent.
2.6.A.2. De Morgan’s law can be applied to Boolean expressions to create equivalent Boolean expressions. Under De Morgan’s law, the Boolean expression !(a && b) is equivalent to !a || !b and the Boolean expression !(a || b) is equivalent to !a && !b. equals
What equivalent means
Two Boolean expressions are equivalent if they evaluate to the same value in all cases. To show two expressions are equivalent you must check every combination of inputs; to show they are not equivalent, a single input where they disagree is enough. A truth table lists all the combinations and is the standard way to prove it.
Truth tables
With two Boolean variables there are four rows. Here are four expressions side by side.
a
b
!(a && b)
!a || !b
!(a || b)
!a && !b
true
true
false
false
false
false
true
false
true
true
false
false
false
true
true
true
false
false
false
false
true
true
true
true
The third and fourth columns agree in all four rows, and so do the fifth and sixth. The first and fifth columns disagree in rows 2 and 3, so !(a && b) is not equivalent to !(a || b).
De Morgan's laws
The pattern in the table is general. De Morgan's law can be applied to Boolean expressions to create equivalent ones:
!(a && b) is equivalent to !a || !b
!(a || b) is equivalent to !a && !b
To push a ! inside a parenthesis, negate each part and swap&& with ||. The same idea runs backward to factor a ! out.
public static boolean lawAnd(boolean a, boolean b) {
return !(a && b) == (!a || !b);
}
public static boolean lawOr(boolean a, boolean b) {
return !(a || b) == (!a && !b);
}
Each method compares the two sides for one pair of inputs; all eight comparisons are true, which is a truth table in code.
### Negating a relational operator
A ! in front of a single comparison simply flips the operator. Never flip < to >: the flip of < is >=, because the boundary value goes to the other side.
Expression
Equivalent
!(x < 5)
x >= 5
!(x <= 5)
x > 5
!(x == 5)
x != 5
!(x >= 1 && x <= 10)
x < 1 || x > 10
### Simplifying
Equivalent forms let you clean up conditions.
Before
After
Why
done == true
done
a boolean already is true or false
flag == false
!flag
x > 3 && x > 8
x > 8
the second test implies the first
!(age < 13 || age > 19)
age >= 13 && age <= 19
De Morgan, then flip each comparison
Worked example · applying De Morgan's law
Rewrite !(score >= 60 && attendance >= 90) without the leading !.
Negate each part and swap && with ||: score < 60 || attendance < 90. Test the equivalence at one point where the original is true and one where it is false.
In words: the original says "it is not the case that both requirements are met", which is the same as "at least one requirement is missed".
Worked example · two expressions that look alike but are not equivalent
Is !(a && b) equivalent to !a && !b?
a
b
!(a && b)
!a && !b
same?
true
true
false
false
yes
true
false
true
false
no
false
true
true
false
no
false
false
true
true
yes
boolean a = true;
boolean b = false;
System.out.println(!(a && b));
System.out.println(!a && !b);
true
false
One disagreeing row is enough. The classic slip is to push the ! inside without swapping && for ||.
Worked example · simplifying a condition
Simplify !(x < 0 || x > 100) && x != 50 into one expression with no ! in front of a parenthesis.
De Morgan on the first part: !(x < 0 || x > 100) becomes x >= 0 && x <= 100.
The full condition: x >= 0 && x <= 100 && x != 50.
int x = 50;
int y = 30;
System.out.println(!(x < 0 || x > 100) && x != 50);
System.out.println(x >= 0 && x <= 100 && x != 50);
System.out.println(!(y < 0 || y > 100) && y != 50);
System.out.println(y >= 0 && y <= 100 && y != 50);
false
false
true
true
The condition describes "0 through 100, but not 50". The two forms agree for 50 (the one value excluded) and for 30.
Exam focus
Expect questions that give two expressions and ask whether they are equivalent, or that ask which of several expressions is equivalent to a negated condition. Apply De Morgan's law mechanically: negate every part and swap && and ||. Remember that negating < gives >=, not >. When you are unsure, a four-row truth table settles it, and a counterexample settles non-equivalence.
Practice
Which expression is equivalent to !(a || b)?
A. !a || !b
B. !a && !b
C. a && b
D. !(a && b)
Show answer
B. De Morgan's law turns the ! inside, negates each variable, and swaps || for &&.
Which is equivalent to !(x > 4 && y <= 2)?
int x = 6;
int y = 5;
System.out.println(!(x > 4 && y <= 2));
System.out.println(x <= 4 || y > 2);
Show answer
x <= 4 || y > 2. Negate each comparison (> becomes <=, <= becomes >) and swap && for ||. The two lines print the same value for the test inputs, as equivalence requires.
Complete the truth table row: when a is false and b is true, what are a && b, a || b, and !a && b?
boolean a = false;
boolean b = true;
System.out.println((a && b) + " " + (a || b) + " " + (!a && b));
Show answer
false, true, and true. a && b needs both to be true; a || b needs one; and !a is true, so !a && b is true.
Simplify if (found == true && !(count > 0)) to a shorter equivalent condition.
boolean found = true;
int count = 0;
System.out.println(found == true && !(count > 0));
System.out.println(found && count <= 0);
Show answer
found && count <= 0. The comparison found == true is just found, and !(count > 0) is count <= 0.
Are !(x == 1 || x == 2) and x != 1 || x != 2 equivalent? Explain with an input.
int x = 1;
System.out.println(!(x == 1 || x == 2));
System.out.println(x != 1 || x != 2);
Show answer
No. For x equal to 1 the first is false and the second is true. The correct De Morgan form of the first is x != 1 && x != 2; the second expression is true for every x because no number is both 1 and 2.
Rewrite !(n > 10 || n < 0) with no !.
Show answer
n <= 10 && n >= 0. Negate each comparison and swap || for &&: the original says "not above 10 and not below 0", which means 0 through 10.
Comparing two numbers is easy: they are either the same value or not. Comparing two objects is subtler, because there are two different questions you might be asking. Are these two variables referring to the very same object, or do the two objects they refer to look alike? Java gives each question its own tool, and mixing them up is one of the most common sources of wrong answers in the course.
Required content · LO 2.6.B
Learning objective.
2.6.B. Develop code to compare object references using Boolean expressions and determine the result of these expressions.
Essential knowledge.
2.6.B.1. Two different variables can hold references to the same object. Object references can be compared using == and !=.
2.6.B.2. An object reference can be compared with null, using == or !=, to determine if the reference actually references an object.
2.6.B.3. Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class. The equivalency of two objects is most often determined using attributes from the two objects. Outside the course: Overriding the equals method is outside the scope of the AP Computer Science A course and exam.
== and != compare references
Two different variables can hold references to the same object. The operators == and != applied to object references test whether the two references point to the same object, not whether the objects have matching contents.
String a = new String("hi");
String b = new String("hi");
String c = a;
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a == c);
false
true
true
new was called twice, so a and b are two different objects that happen to contain the same characters: == is false and equals is true. c = a copied the reference, so a and c refer to the same object and == is true.
equals compares content, when the class defines it
Classes often define their own equals method, which specifies the criteria for equivalency of two objects of the class. The equivalency is most often decided from the attributes of the two objects. For String, equals compares the characters. For another class, read the documentation: a class that does not define its own equals inherits one that compares references, just like ==. Writing your own equals method is outside the course.
Point p = new Point(2, 3);
Point q = new Point(2, 3);
Point r = p;
System.out.println(p == q);
System.out.println(p.equals(q));
System.out.println(p == r);
false
true
true
This Point class defines equals to compare the two coordinates, so two distinct Point objects with the same coordinates are equal but not identical.
Question
Tool
True when
Are these two references to the same object?
==
both variables hold the same reference
Do these two objects have the same contents?
equals
the class's own criteria for equivalency are met
String literals can share a single object behind the scenes, so == on two literals may appear to work. It is not reliable and never the right test for contents; use equals for Strings.
Comparing with null
An object reference can be compared with null, using == or !=, to determine whether the reference actually refers to an object. Always check before calling a method on a reference that might be null.
Aliases share one object, so a change through either name is seen by both.
Book mine = new Book("Notes", 120);
Book yours = mine;
Book other = new Book("Notes", 120);
System.out.println(mine == yours);
System.out.println(mine == other);
true
false
mine == yours is true because yours = mine copied the reference. other has the same title and page count but is a different object, so mine == other is false. A class that defined equals by comparing attributes would report mine.equals(other) as true; this Book does not, so you must read the documentation.
Worked example · a safe test
A method returns whether a Book exists and is long. Which version is safe?
public static boolean longBook(Book b) {
return b != null && b.isLong();
}
With the operands in the opposite order (b.isLong() && b != null), the call with null would throw a NullPointerException, because the method call happens first. The null test must come first.
Exam focus
Expect questions that create objects with new, assign references, and then ask what ==, !=, and equals print. The rule: == and != ask about identity, equals asks about content when the class defines it. A null test belongs before a method call, joined by &&. Overriding equals is outside the course; reading code that calls it is not.
Practice
What is printed?
String x = new String("cat");
String y = new String("cat");
System.out.println(x == y);
System.out.println(x.equals(y));
Show answer
false and true. The two Strings are separate objects with the same characters.
What is printed?
Book a = new Book("Atlas", 400);
Book b = a;
Book c = new Book("Atlas", 400);
System.out.println((a == b) + " " + (a == c) + " " + (b == c));
Show answer
true false false. Only a and b refer to the same object. c is a different object even though it was created with the same arguments.
Why does this method risk a run-time error, and how do you fix it?
public static boolean isShort(Book b) {
return b.getPages() < 100 && b != null;
}
Show answer
If b is null, b.getPages() runs first and throws a NullPointerException. Put the null test first: b != null && b.getPages() < 100.
A String variable name holds "Ada". Which test correctly asks whether name holds the same characters as "Ada"?
A. name == "Ada"
B. name.equals("Ada")
C. name = "Ada"
D. name.compareTo("Ada")
Show answer
B. equals compares the characters. == compares references, = assigns, and compareTo returns an int, not a boolean.
What is printed?
Point u = new Point(1, 1);
Point v = new Point(1, 1);
Point w = v;
System.out.println(u == v);
System.out.println(u.equals(v));
System.out.println(v == w);
Show answer
false, true, true. Point defines equals by comparing coordinates, so u.equals(v) is true. u and v are different objects, so == is false. w is an alias of v.
What is the difference between x == null and x.equals(null) for a reference x?
Show answer
x == null safely tests whether x refers to an object. x.equals(null) calls a method on x, so it throws a NullPointerException when x is null; it also is not the way to test for null.
Repetition is what makes a computer worth having: add up a thousand numbers, search every line of a file, keep playing until the game is over. The while loop is the simplest loop in Java. You say "as long as this is true, do that", and the computer does it, over and over, faster than you can read. This lesson also covers what goes wrong when a loop is written carelessly: it never ends, or it runs one time too many.
Required content · LO 2.7.A, LO 2.7.B
Learning objectives.
2.7.A. Identify when an iterative process is required to achieve a desired result.
2.7.B. Develop code to represent iterative processes using while loops and determine the result of these processes.
Essential knowledge.
2.7.A.1. Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true.
2.7.A.2. An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
2.7.A.3. The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
2.7.A.4. Off by one errors occur when the iteration statement loops one time too many or one time too few.
2.7.B.1. A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.
Iteration
Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression that controls the loop evaluates to true.
The while statement
A while loop is a type of iterative statement. The Boolean expression is evaluated before each iteration of the loop body, including the first. When it evaluates to true, the body runs. This continues until the expression evaluates to false, whereupon the iteration terminates and execution continues after the loop.
while (condition) {
// body: runs again and again while condition is true
}
Three parts must work together for a while loop to behave:
Initialize the variable the condition depends on, before the loop.
Test it in the condition.
Update it inside the body, in a way that eventually makes the condition false.
int count = 1;
while (count <= 3) {
System.out.println("pass " + count);
count++;
}
System.out.println("after the loop, count = " + count);
pass 1
pass 2
pass 3
after the loop, count = 4
The variable count is the loop control variable. After the last pass it was increased to 4, the test 4 <= 3 came out false, and the loop ended.
Loops that run zero times, and loops that never end
If the condition is false the first time it is evaluated, the body never runs.
int n = 10;
while (n < 5) {
n++;
System.out.println("inside");
}
System.out.println(n);
10
An infinite loop occurs when the Boolean expression always evaluates to true, so the loop never ends. The usual cause is a loop control variable that is never updated, or updated in the wrong direction.
int n = 5;
while (n != 0) {
n = n - 2; // 5, 3, 1, -1, -3 ... never exactly 0
}
Because n starts odd and decreases by 2, it skips over 0 and the test n != 0 is true forever. Testing with n > 0 would fix it.
Off-by-one errors
An off-by-one error occurs when the loop iterates one time too many or one time too few. It almost always comes from the choice between < and <= (or between > and >=), or from starting the counter at the wrong value.
int i = 0;
int c1 = 0;
while (i <= 4) {
c1++;
i++;
}
int j = 0;
int c2 = 0;
while (j < 4) {
c2++;
j++;
}
System.out.println(c1 + " " + c2);
5 4
Counting from 0, i <= 4 runs for 0, 1, 2, 3, and 4: five passes. The test j < 4 stops before 4, so there are four. To count how many times a loop runs, list the values of the loop control variable for which the condition is true.
Worked example · tracing a loop
Trace the loop and give the output.
int i = 1;
int sum = 0;
while (i <= 5) {
sum += i;
i++;
}
System.out.println(sum + " " + i);
Pass
i at the test
test true?
sum after the body
i after the body
1
1
yes
1
2
2
2
yes
3
3
3
3
yes
6
4
4
4
yes
10
5
5
5
yes
15
6
test
6
no
15 6
The loop ran five times and left i at 6, one past the last value used. That leftover is why code after a loop often needs care.
Worked example · taking a number apart with a loop
Add up the digits of 4073.
int n = 4073;
int digitSum = 0;
while (n > 0) {
digitSum += n % 10;
n /= 10;
}
System.out.println(digitSum);
Pass
n at the test
n % 10
digitSum
n after
1
4073
3
3
407
2
407
7
10
40
3
40
0
10
4
4
4
4
14
0
test
0
14
n % 10 takes the last digit and n /= 10 removes it. The loop ends when no digits remain. The number of passes is not known in advance, which is exactly when a while loop is the natural choice.
Worked example · counting how many times
How many times can 3 be subtracted from 100 before what remains is less than 3?
int left = 100;
int times = 0;
while (left >= 3) {
left -= 3;
times++;
}
System.out.println(times + " " + left);
33 1
The loop subtracts 3 thirty-three times (99), leaving 1. This is integer division and remainder, built from repetition: 100 / 3 is 33 and 100 % 3 is 1. When you can predict a loop's answer with arithmetic, you can check your trace.
Exam focus
Expect to be given a loop and asked what it prints, how many times the body runs, or what the variable holds afterward. Trace with a table and test the first and last iteration of the condition. Look for the three standard faults: a condition false at the start (the body never runs), a missing or wrong update (an infinite loop), and a boundary mistake (< against <=). Remember the loop control variable's value after the loop ends.
Practice
What is printed?
int k = 1;
while (k < 20) {
k *= 3;
}
System.out.println(k);
Show answer
27. The value of k goes 1, 3, 9, 27. At 27 the test 27 < 20 is false and the loop ends.
How many times does the body run, and what is n afterward?
int n = 10;
int c = 0;
while (n > 0) {
n -= 3;
c++;
}
System.out.println(c + " " + n);
Show answer
The body runs 4 times and n ends at -2. n is 10, 7, 4, and 1 when the test passes (four passes), and the last pass takes it to -2.
Why does this loop never end, and what is the fix?
int x = 1;
while (x < 10) {
System.out.println(x);
}
Show answer
The loop control variable x is never updated, so x < 10 stays true forever. Add x++; inside the body.
Write a loop that prints the powers of 2 that are below 100, on one line.
int p = 1;
while (p < 100) {
System.out.print(p + " ");
p *= 2;
}
Show answer
The loop prints 1, 2, 4, 8, 16, 32, 64 and stops when p becomes 128. The loop control variable p is both the thing printed and the thing doubled.
What is printed?
int n = 9051;
int digits = 0;
while (n > 0) {
digits++;
n /= 10;
}
System.out.println(digits);
Show answer
4. The value of n goes 9051, 905, 90, 9, 0: four passes, one per digit.
What is printed?
int i = 0;
while (i < 3) {
i++;
System.out.print(i);
}
Show answer
123. Because i is increased before it is printed, the values shown are 1, 2, 3. Moving i++ after the print would show 012.
Most loops count: do this ten times, visit every index, add up the numbers from 1 to 100. A while loop can do that, but you must write the initialization, the test, and the update in three different places and keep them consistent. The for loop puts all three in one line, which makes counting loops shorter and easier to check. This lesson shows exactly how a for loop executes, because the exam asks you to trace them constantly.
Required content · LO 2.8.A
Learning objective.
2.8.A. Develop code to represent iterative processes using for loops and determine the result of these processes.
Essential knowledge.
2.8.A.1. A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
2.8.A.2. In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the increment statement until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
2.8.A.3. A for loop can be rewritten into an equivalent while loop (and vice versa).
The three parts of a for loop
A for loop is a type of iterative statement. The header has three parts, separated by semicolons: the initialization, the Boolean expression, and the update.
for (initialization; Boolean expression; update) {
// body
}
The order of events matters.
The initialization runs exactly once, before the first test. The variable it declares is the loop control variable.
The Boolean expression is evaluated immediately after the initialization and then after every update. If it is false, the loop ends.
If it is true, the body runs.
After the whole body has run, the update executes, and the flow returns to step 2.
Figure 2.3. In for (initialization; test; update), step 1 happens once. After that the test, the body, and the update repeat in that order until the test is false.
for (int i = 0; i < 4; i++) {
System.out.print(i * i + " ");
}
0 1 4 9
The variable i takes the values 0, 1, 2, 3; when the update makes it 4 the test 4 < 4 fails. A variable declared in the header exists only inside the loop, so using it afterward does not compile.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.print(i);
}
System.out.println(i);
}
}
Main.java:6: error: cannot find symbol
System.out.println(i);
^
symbol: variable i
location: class Main
1 error
A for loop is a while loop in disguise
A for loop can be rewritten as an equivalent while loop, and vice versa. The initialization goes before the loop, the test is the condition, and the update goes at the end of the body.
for (int i = 10; i > 0; i -= 3) {
System.out.print(i + " ");
}
System.out.println();
int j = 10;
while (j > 0) {
System.out.print(j + " ");
j -= 3;
}
System.out.println();
10 7 4 1
10 7 4 1
Choose for when you know how the loop control variable moves (counting up or down by a fixed step), and while when the ending depends on something that happens during the loop.
Counting the iterations
For a loop that starts at a and steps by 1, the number of times the body runs is easy to read from the header.
Header
Body runs
Values of i
for (int i = 0; i < 5; i++)
5 times
0, 1, 2, 3, 4
for (int i = 1; i <= 5; i++)
5 times
1, 2, 3, 4, 5
for (int i = 3; i < 10; i++)
7 times (10 - 3)
3 to 9
for (int i = 3; i <= 10; i++)
8 times (10 - 3 + 1)
3 to 10
for (int i = 0; i <= 20; i += 5)
5 times
0, 5, 10, 15, 20
for (int i = 5; i > 0; i--)
5 times
5, 4, 3, 2, 1
Worked example · totals and counts
Add the integers from 1 to 100, and count the even numbers from 1 to 20.
int total = 0;
for (int k = 1; k <= 100; k++) {
total += k;
}
int evens = 0;
for (int k = 1; k <= 20; k++) {
if (k % 2 == 0) {
evens++;
}
}
System.out.println(total + " " + evens);
5050 10
Both loops use the accumulator pattern from Lesson 1.6: the accumulator is initialized before the loop, and the update happens inside. The first loop's total ends at 5050, the sum of 1 through 100. The second combines a loop with a selection to count only the values that qualify.
Worked example · building a String with a loop
Build a row of stars whose length depends on a variable, then count down.
String row = "";
for (int i = 0; i < 5; i++) {
row += "*";
}
System.out.println(row);
for (int i = 3; i >= 1; i--) {
System.out.print(i + "...");
}
System.out.println("go");
*****
3...2...1...go
row += "*" creates a new String each pass (Strings are immutable) and assigns it back, so the String grows by one star per iteration. The second loop counts down with i--, and the test uses >= so the loop includes 1.
Worked example · a semicolon that ends the loop early
What does the following code print?
int count = 0;
for (int i = 0; i < 3; i++);
{
count++;
}
System.out.println(count);
1
The semicolon right after the header is an empty body. The loop runs three times doing nothing, and then the braced block runs exactly once, because it is no longer attached to the loop. As with the stray semicolon after an if, the code compiles and runs; only a trace reveals the mistake.
Exam focus
Expect to trace for loops with different starting points, steps, and tests, and to count the iterations. Use the pattern: list the values of the loop control variable for which the test is true. Watch for < versus <=, a header that counts down, a step other than 1, and a loop whose body changes the loop control variable. Know that a for and a while loop can be written to do the same job, and that a variable declared in the header is not visible after the loop.
Practice
What is printed?
for (int i = 2; i <= 10; i += 4) {
System.out.print(i + " ");
}
Show answer
2 6 10. The values of i are 2, 6, and 10 (all at most 10); the next update gives 14, and the test fails.
How many times does the body of each loop run? (a) for (int i = 5; i < 20; i++) (b) for (int i = 0; i <= 20; i += 5) (c) for (int i = 10; i > 10; i--)
int a = 0;
for (int i = 5; i < 20; i++) {
a++;
}
int b = 0;
for (int i = 0; i <= 20; i += 5) {
b++;
}
int c = 0;
for (int i = 10; i > 10; i--) {
c++;
}
System.out.println(a + " " + b + " " + c);
Show answer
(a) 15 times, since 20 - 5 for a < test; (b) 5 times, for 0, 5, 10, 15, and 20; (c) 0 times, because the test is false at the start.
Rewrite this loop as an equivalent while loop, and show that the output is the same.
for (int n = 1; n < 20; n *= 2) {
System.out.print(n + " ");
}
System.out.println();
int n = 1;
while (n < 20) {
System.out.print(n + " ");
n *= 2;
}
System.out.println();
Show answer
The initialization int n = 1; goes before the while, the test n < 20 becomes its condition, and the update n *= 2; goes at the end of the body. Both loops print 1, 2, 4, 8, 16.
What is printed?
for (int i = 5; i >= 1; i--) {
System.out.print(i);
}
Show answer
54321. The loop counts down from 5 and includes 1 because the test is >=.
What is printed?
String line = "";
for (int i = 0; i < 3; i++) {
line += "ab";
}
System.out.println(line + " " + line.length());
Show answer
ababab 6. The String grows by two characters on each of the 3 passes, so its length is 6.
Why does this loop never stop?
for (int i = 0; i != 5; i += 2) {
System.out.println(i);
}
Show answer
i takes the values 0, 2, 4, 6, 8, and so on, which skips over 5, so i != 5 is always true. Using i < 5 would end the loop.
Standard algorithms: divisors, digits, and counting
Some jobs come up so often that programmers recognize them on sight and write them almost without thinking: is this number divisible by that one, pull the digits out of a number, count how many values meet a rule. These are standard algorithms, and knowing them well means that on the exam you are modifying a pattern you have already seen instead of inventing something under pressure. Lesson 2.9b finishes the list with minimum, maximum, sum, and average.
There are standard algorithms to:
identify if an integer is or is not evenly divisible by another integer,
identify the individual digits in an integer,
determine the frequency with which a specific criterion is met,
determine a minimum or maximum value, and
compute a sum or average.
This lesson covers the first three; the next covers the last two and shows how to combine and adapt them into algorithms of your own.
Required content · LO 2.9.A
Learning objective.
2.9.A. Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.
Essential knowledge.
2.9.A.1. There are standard algorithms to:
identify if an integer is or is not evenly divisible by another integer
identify the individual digits in an integer
determine the frequency with which a specific criterion is met
determine a minimum or maximum value
compute a sum or average
Divisibility
a is evenly divisible by b exactly when a % b == 0. Put that test inside a loop and you can find every multiple, count the divisors, or decide whether a number is prime.
for (int n = 1; n <= 50; n++) {
if (n % 7 == 0) {
System.out.print(n + " ");
}
}
7 14 21 28 35 42 49
A prime number has exactly two divisors, 1 and itself. To test a number, look for any divisor from 2 up to one less than the number.
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; d < n; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
The return false inside the loop ends the method as soon as a divisor is found. The return true after the loop is reached only if no divisor was found.
Digits
The last digit of a non-negative integer is n % 10; removing it is n / 10. A loop repeats this until nothing is left, which visits every digit from right to left.
int n = 4073;
int count = 0;
int evenDigits = 0;
int reversed = 0;
while (n > 0) {
int digit = n % 10;
count++;
if (digit % 2 == 0) {
evenDigits++;
}
reversed = reversed * 10 + digit;
n /= 10;
}
System.out.println(count + " " + evenDigits + " " + reversed);
4 2 3704
Pass
digit
count
evenDigits
reversed
n after
1
3
1
0
3
407
2
7
2
0
37
40
3
0
3
1
370
4
4
4
4
2
3704
0
Reversal works by shifting what has been built one place left (reversed * 10) and adding the new digit.
Frequency: counting how often a criterion is met
To find how many values meet a rule, keep a counter, initialize it to 0, and add 1 inside an if whenever the rule holds.
int count = 0;
for (int n = 1; n <= 50; n++) {
if (n % 3 == 0 || n % 5 == 0) {
count++;
}
}
System.out.println(count);
23
There are 16 multiples of 3 up to 50 and 10 multiples of 5, but 3 values (15, 30, 45) are multiples of both and the || counts each of them once: 16 + 10 - 3 is 23.
Worked example · counting divisors
How many divisors does 36 have, and which are they?
int n = 36;
int divisors = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) {
divisors++;
System.out.print(d + " ");
}
}
System.out.println();
System.out.println(divisors);
1 2 3 4 6 9 12 18 36
9
The loop tests every d from 1 through n inclusive (a divisor can be n itself, so the test is <=), and it uses the divisibility test and a counter together.
Worked example · reading a number's digits
Write a method that returns the sum of the digits of a non-negative integer, then use it to decide whether a number is divisible by 9.
public static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
4073 gives 14. The number 729 has a digit sum of 18, which is divisible by 9, as is 729 itself (81 * 9). The method changes its own copy of n, which is allowed because the parameter received a copy of the argument.
Worked example · a frequency with two conditions
How many integers from 1 to 100 are even and also divisible by 3?
int count = 0;
for (int n = 1; n <= 100; n++) {
if (n % 2 == 0 && n % 3 == 0) {
count++;
}
}
System.out.println(count);
16
A number that is even and divisible by 3 is divisible by 6, and there are 100 / 6, which is 16, multiples of 6 up to 100. Whenever you can predict the answer with arithmetic, use it to check the loop.
Exam focus
Expect to see these patterns inside a longer segment and be asked what the code returns or prints, or to write one as a method. The recurring shape is: initialize, loop, test with %, update a counter or accumulator. Know the digit pair n % 10 and n / 10. Be careful about the loop bounds: a divisor search that stops at n - 1 excludes n itself, and a count from 1 to n includes both ends.
Practice
What is printed?
int n = 5280;
int last = n % 10;
n /= 10;
int next = n % 10;
System.out.println(last + " " + next + " " + n);
Show answer
0 8 528. The last digit of 5280 is 0, and after dividing by 10 the number is 528, whose last digit is 8.
What does this method return for 12? For 13?
public static boolean mystery(int n) {
int count = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) {
count++;
}
}
return count == 2;
}
false for 12 (it has 6 divisors) and true for 13 (divisors 1 and 13). The method tests whether a number is prime.
Write a loop that counts how many multiples of 4 are between 1 and 60, inclusive.
int count = 0;
for (int n = 1; n <= 60; n++) {
if (n % 4 == 0) {
count++;
}
}
System.out.println(count);
Show answer
The loop counts 15 multiples (4, 8, ..., 60), which matches 60 / 4.
What is printed?
int n = 1234;
int result = 0;
while (n > 0) {
result = result * 10 + n % 10;
n /= 10;
}
System.out.println(result);
Show answer
4321. The loop reverses the digits: the running value goes 4, 43, 432, 4321.
What is printed?
int count = 0;
for (int i = 1; i <= 30; i++) {
if (i % 2 == 1 && i % 3 != 0) {
count++;
}
}
System.out.println(count);
Show answer
10. The odd numbers from 1 to 30 are 15 in all; of those, 5 are multiples of 3 (3, 9, 15, 21, 27), so 10 remain.
A programmer counts the digits of n with this loop and gets 0 when n is 0. Is that a bug?
int n = 0;
int digits = 0;
while (n > 0) {
digits++;
n /= 10;
}
System.out.println(digits);
Show answer
It depends on the specification. The loop condition n > 0 is false immediately, so the body never runs and the result is 0, though most people would say 0 has one digit. A standard fix is to test for 0 before the loop and return 1 for that case.
Standard algorithms: minimum, maximum, sum, and average
Lesson 2.9a gave you divisibility, digits, and counting. Two more standard algorithms complete the list: finding the smallest or largest value, and computing a sum or average. When you meet a collection in Unit 4, these two will appear again and again; here you learn them on values produced by a loop. Then you learn the last step: combining standard algorithms into one of your own.
Required content · LO 2.9.A
Learning objective.
2.9.A. Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.
Essential knowledge.
2.9.A.1. There are standard algorithms to:
identify if an integer is or is not evenly divisible by another integer
identify the individual digits in an integer
determine the frequency with which a specific criterion is met
determine a minimum or maximum value
compute a sum or average
Minimum and maximum
To find the largest value, keep a variable max for the largest seen so far. Start it with a value that cannot be beaten (the first value, or the smallest int), compare each new value, and replace max when the new one is larger. The minimum is the same with the comparison reversed.
int max = 0;
int min = 0;
for (int k = 1; k <= 9; k++) {
int value = k * (10 - k);
if (k == 1) {
max = value;
min = value;
}
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
System.out.println(max + " " + min);
25 9
The values are 9, 16, 21, 24, 25, 24, 21, 16, 9. The first value initializes both variables; then each new value either replaces one of them or does not.
The initialization trap. Starting max at 0 fails if every value is negative, because 0 is already larger than all of them and is never replaced. Initializing from the first value, or from Integer.MIN_VALUE for a maximum and Integer.MAX_VALUE for a minimum, is always safe.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int k = -3; k <= 3; k++) {
int value = k * k - 10;
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
System.out.println(max + " " + min);
-1 -10
Every value is negative here (from -10 to -1), so a max initialized to 0 would wrongly stay 0.
Sum and average
A sum uses an accumulator that starts at 0. An average is the sum divided by the count, and it needs a double division, or it loses the fraction (Lesson 1.5).
int sum = 0;
int count = 0;
for (int k = 1; k <= 10; k++) {
sum += k;
count++;
}
System.out.println(sum + " " + count);
System.out.println(sum / count);
System.out.println((double) sum / count);
55 10
5
5.5
The middle line shows the standard mistake: 55 / 10 is integer division and gives 5. Casting one operand to double before the division gives the true average, 5.5.
Combining algorithms into your own
An original algorithm is built by adapting and combining the standard ones. The method is the same every time: decide what to track (a counter, a running maximum, an accumulator), choose the loop that visits what must be visited, and decide what happens on each pass.
Worked example · the largest digit
Find the largest and smallest digits of 48253.
int n = 48253;
int largest = 0;
int smallest = 9;
while (n > 0) {
int digit = n % 10;
if (digit > largest) {
largest = digit;
}
if (digit < smallest) {
smallest = digit;
}
n /= 10;
}
System.out.println(largest + " " + smallest);
8 2
Digits are in the range 0 to 9, so starting largest at 0 and smallest at 9 can never block a real digit: the initialization trap does not arise here. The digit extraction (% 10 and / 10) from Lesson 2.9a feeds the maximum and minimum pattern.
Worked example · Euclid's algorithm
The greatest common divisor of two positive integers is the largest integer that divides both. Euclid's algorithm repeatedly replaces the pair (a, b) with (b, a % b) until b is 0; then a is the answer.
int a = 48;
int b = 18;
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
System.out.println(a);
Pass
a
b
t = a % b
start
48
18
1
18
12
12
2
12
6
6
3
6
0
0
6
The temporary t holds the remainder before a and b are overwritten, the same idea as the swap in Lesson 1.4. When b reaches 0 the loop stops, and a is 6.
Worked example · counting steps until a goal
Start with a positive integer. If it is even, halve it; if it is odd, triple it and add 1. Count the steps until it reaches 1, starting from 6.
int n = 6;
int steps = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps++;
}
System.out.println(steps);
8
The sequence is 6, 3, 10, 5, 16, 8, 4, 2, 1: eight steps. This algorithm combines a while loop (the number of passes is unknown), a selection inside the loop, and a counter. Nothing here is new: it is three standard pieces assembled.
Exam focus
Expect a question that gives a loop and asks what a maximum, minimum, sum, or average ends up as, or that asks you to complete the missing initialization or comparison. The usual traps are an accumulator started at the wrong value, a maximum started at 0, an average computed with integer division, and a comparison that uses > where >= is needed. For original algorithms, identify the standard pieces first, then check how they connect.
Practice
What is printed?
int best = 0;
for (int i = 1; i <= 5; i++) {
int v = 20 - (i - 3) * (i - 3);
if (v > best) {
best = v;
}
}
System.out.println(best);
Show answer
20. The values of v are 16, 19, 20, 19, 16, and the largest is 20 at i equal to 3.
Why does this code print 0 when the values are all negative, and how do you fix it?
int max = 0;
for (int i = 1; i <= 4; i++) {
int v = -i * 3;
if (v > max) {
max = v;
}
}
System.out.println(max);
Show answer
The values -3, -6, -9, -12 are all below the starting max of 0, so the condition is never true. Initialize max from the first value or with Integer.MIN_VALUE.
What is printed?
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i * i;
}
System.out.println(sum);
System.out.println(sum / 4);
System.out.println(sum / 4.0);
Show answer
30, 7, 7.5. The sum of squares 1 + 4 + 9 + 16 is 30. Dividing by the int 4 truncates to 7, and dividing by 4.0 keeps the fraction.
Write a loop that computes the average of the integers from 1 to 6 as a double.
int sum = 0;
for (int i = 1; i <= 6; i++) {
sum += i;
}
double average = (double) sum / 6;
System.out.println(average);
Show answer
The sum is 21, and (double) sum / 6 gives 3.5. Writing sum / 6 would give 3.
What is printed? (Trace a and b.)
int a = 84;
int b = 36;
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
System.out.println(a);
Show answer
12. The pairs are (84, 36), (36, 12), (12, 0), so the greatest common divisor is 12.
Complete the method so that it returns the smallest digit of a positive integer.
public static int smallestDigit(int n) {
int smallest = 9;
while (n > 0) {
int digit = n % 10;
if (digit < smallest) {
smallest = digit;
}
n /= 10;
}
return smallest;
}
Strings are sequences, and a lot of the questions you ask about text mean visiting every character: how many vowels, is it a palindrome, does it contain a digit. The pattern is a for loop that steps an index through the String and takes a one-character substring at each position. This is the single most common structure in the first free-response question on the exam, so it is worth learning as a pattern rather than as separate tricks.
Required content · LO 2.10.A
Learning objective.
2.10.A. Develop code for standard and original algorithms that involve strings and determine the result of these algorithms.
Essential knowledge.
2.10.A.1. There are standard string algorithms to:
find if one or more substrings have a particular property
determine the number of substrings that meet specific criteria
create a new string with the characters reversed
Traversing a String
A traversal visits every position. The index runs from 0 to length() - 1, and you pull out one character at a time with substring(i, i + 1).
String word = "loop";
for (int i = 0; i < word.length(); i++) {
String ch = word.substring(i, i + 1);
System.out.print(ch + "-");
}
l-o-o-p-
Note the loop test: i < word.length(), not <=. The last valid index is length() - 1, and substring(i, i + 1) with i equal to length() would ask for characters that do not exist.
There are standard string algorithms to:
find if one or more substrings have a particular property,
determine the number of substrings that meet specific criteria, and
create a new string with the characters reversed.
Checking a property
A substring has a property if some test on it is true: it is a vowel, it equals some text, it is a digit. A neat way to test membership uses indexOf on a String of the allowed characters: "aeiou".indexOf(ch) != -1 is true when ch is a vowel.
public static boolean hasVowel(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.substring(i, i + 1)) != -1) {
return true;
}
}
return false;
}
The return true inside the loop stops as soon as one vowel is found. The return false after the loop is reached only if every character failed the test. This "any" pattern appears again for arrays in Unit 4.
Counting substrings that meet a criterion
Keep a counter and add 1 for each qualifying substring. A substring is not always one character long: to count occurrences of a longer piece of text, compare a window of that length at every legal starting index.
String s = "banana";
String target = "an";
int count = 0;
for (int i = 0; i <= s.length() - target.length(); i++) {
if (s.substring(i, i + target.length()).equals(target)) {
count++;
}
}
System.out.println(count);
2
The last legal start for a window of length 2 in a String of length 6 is index 4 (substring(4, 6)), so the loop test is i <= 6 - 2. The matches start at indexes 1 and 3.
Building a new String
Start with an empty String and add to it. To reverse, put each new character in front of what has been built, or walk the index backward.
String s = "stressed";
String reversed = "";
for (int i = 0; i < s.length(); i++) {
reversed = s.substring(i, i + 1) + reversed;
}
String same = "";
for (int i = s.length() - 1; i >= 0; i--) {
same += s.substring(i, i + 1);
}
System.out.println(reversed + " " + same);
desserts desserts
A palindrome reads the same forward and backward, so the test is s.equals(reversed).
Worked example · counting vowels
Count the vowels in "education" and build a String without them.
String s = "education";
int vowels = 0;
String rest = "";
for (int i = 0; i < s.length(); i++) {
String ch = s.substring(i, i + 1);
if ("aeiou".indexOf(ch) != -1) {
vowels++;
} else {
rest += ch;
}
}
System.out.println(vowels + " " + rest);
5 dctn
The vowels are e, u, a, i, o. The if/else splits each character into two destinations: counted, or kept.
Worked example · palindromes
Write a method that decides whether a String is a palindrome, and test it.
public static boolean isPalindrome(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed += s.substring(i, i + 1);
}
return s.equals(reversed);
}
equals is case sensitive, so "Level" (capital L) is not equal to its reverse "level". The empty String reads the same in both directions, so it counts as a palindrome. Always include the empty and the one-character case among your tests.
Worked example · the boundary of a window
A programmer counts adjacent equal pairs ("oo" in "balloon") and the program crashes.
String s = "balloon";
int pairs = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 1).equals(s.substring(i + 1, i + 2))) {
pairs++;
}
}
System.out.println(pairs);
2
This version is correct: the test i < s.length() - 1 makes the last start index 5, so i + 2 is 7, the length. With i <= s.length() - 1 instead, the final pass would ask for substring(6, 8) on a String of length 7:
String s = "balloon";
int pairs = 0;
for (int i = 0; i <= s.length() - 1; i++) {
if (s.substring(i, i + 1).equals(s.substring(i + 1, i + 2))) {
pairs++;
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
When the code looks at a character and its neighbor, the last index must stop one early. This single off-by-one is the most common mistake in String traversal.
Exam focus
The String question on the first free-response question, and many multiple-choice items, use exactly these patterns. Read the loop bounds first: i < s.length() for one character, i <= s.length() - k (or i < s.length() - k + 1) for a window of length k. Check what is initialized (a counter at 0, a result String at ""), what is tested, and what is returned. Remember that substring(i, i + 1) is how to take a single character, that equals is case sensitive, and that Strings are immutable, so a built-up result must be reassigned.
Practice
What is printed?
String s = "abcabc";
String t = "";
for (int i = 0; i < s.length(); i += 2) {
t += s.substring(i, i + 1);
}
System.out.println(t);
Show answer
acb. The loop visits indexes 0, 2, and 4, taking the characters a, c, and b.
What does this method return for "Mississippi"?
public static int mystery(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals("s")) {
count++;
}
}
return count;
}
System.out.println(mystery("Mississippi"));
Show answer
4. The method counts the lowercase letter s, which occurs 4 times in "Mississippi".
Write a method countOccurrences that returns how many times target occurs in text. Test it with "abababa" and "aba".
public static int countOccurrences(String text, String target) {
int count = 0;
for (int i = 0; i <= text.length() - target.length(); i++) {
if (text.substring(i, i + target.length()).equals(target)) {
count++;
}
}
return count;
}
The method above counts overlapping matches at indexes 0, 2, and 4, so the result is 3. The loop test uses <= because a window of length target.length() may start as late as text.length() - target.length().
Which loop header visits every character of String s safely?
A. for (int i = 0; i <= s.length(); i++)
B. for (int i = 1; i < s.length(); i++)
C. for (int i = 0; i < s.length(); i++)
D. for (int i = 0; i < s.length() - 1; i++)
Show answer
C. A runs one index past the end and fails with a StringIndexOutOfBoundsException, B skips the first character, and D skips the last.
What is printed?
String word = "robot";
String result = "";
for (int i = 0; i < word.length(); i++) {
String ch = word.substring(i, i + 1);
if (!ch.equals("o")) {
result = ch + result;
}
}
System.out.println(result);
Show answer
tbr. The o characters are skipped, and each kept character is placed in front of the ones already collected, so the order is reversed: r, then b before it, then t.
How many times does the test in the if run, and what is printed, for the String "level"?
String s = "level";
int matches = 0;
for (int i = 0; i < s.length() / 2; i++) {
if (s.substring(i, i + 1).equals(s.substring(s.length() - 1 - i, s.length() - i))) {
matches++;
}
}
System.out.println(matches);
Show answer
The loop runs for i equal to 0 and 1 (5 / 2 is 2), so the test runs twice. It compares l with l, then e with e, and both match, so 2 is printed. The middle character needs no partner.
A single loop walks along a line. To cover a grid, to compare every item with every other item, or to print a triangle, you need a loop inside a loop. Nested iteration is where tracing gets hard: the inner loop restarts every time the outer loop advances, and the number of times a statement runs multiplies. This lesson gives you a method that keeps it manageable.
Required content · LO 2.11.A
Learning objective.
2.11.A. Develop code to represent nested iterative processes and determine the result of these processes.
Essential knowledge.
2.11.A.1. Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.
Loops inside loops
Nested iteration statements are iteration statements that appear in the body of another iteration statement. The rule that governs them is the only rule you need: when a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
System.out.print("*");
}
System.out.println();
}
****
****
****
For each of the 3 values of row, the inner loop runs all 4 times, printing a full row of four stars. Only then does the println end the line and the outer loop move to the next row.
Figure 2.4. A 3 by 4 nested loop. The inner variable j runs through all four values for each value of i, so the body runs 3 * 4 = 12 times, row by row.
If the two loops are independent, the body of the inner loop runs outer count times inner count: here 3 * 4 = 12 times.
When the inner loop depends on the outer one
The inner loop's header may use the outer loop's variable. Then the inner loop does a different amount of work on each pass of the outer loop, and the total is a sum, not a product.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
1
12
123
1234
On the passes where i is 1, 2, 3, and 4 the inner loop runs 1, 2, 3, and 4 times: 1 + 2 + 3 + 4 = 10 executions of the inner body in all.
Using nested loops to compare every pair
To compare every item with every other item, start the inner loop just after the outer index so that each pair is considered once and no item is compared with itself.
String s = "banana";
int equalPairs = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
if (s.substring(i, i + 1).equals(s.substring(j, j + 1))) {
equalPairs++;
}
}
}
System.out.println(equalPairs);
4
The matching pairs are the three a characters (three pairs among them) and the two n characters (one pair).
A common mistake: reusing the loop variable
The inner loop must use a different variable name from the outer loop, because both are alive at the same time.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int i = 0; i < 2; i++) {
System.out.print(i);
}
}
}
}
Main.java:4: error: variable i is already defined in method main(String[])
for (int i = 0; i < 2; i++) {
^
1 error
Worked example · a multiplication table
Print the products from 1 by 1 up to 3 by 3.
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= 3; b++) {
System.out.print(a * b + " ");
}
System.out.println();
}
1 2 3
2 4 6
3 6 9
a
b values
products printed
1
1, 2, 3
1, 2, 3
2
1, 2, 3
2, 4, 6
3
1, 2, 3
3, 6, 9
The outer variable chooses the row, the inner variable chooses the column, and the println after the inner loop ends each row.
Worked example · counting the executions
How many times does the count++ statement run?
int count = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
count++;
}
}
System.out.println(count);
i
inner runs (j from 0 while j < i)
0
0
1
1
2
2
3
3
4
4
10
The total is 0 + 1 + 2 + 3 + 4 = 10. The inner test j < i makes the first pass do no work at all. Comparing the five items of a list pairwise needs exactly this loop shape, and 10 is the number of pairs among five items.
Worked example · tracing the order of output
Trace what is printed.
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i + ":" + j + " ");
}
}
System.out.println();
1:1 1:2 1:3 2:1 2:2 2:3
The values of j run through their whole range for i equal to 1 before i becomes 2. The pair (2, 1) comes right after (1, 3): the inner variable changes fastest.
Exam focus
Expect traces of nested loops, questions that ask how many times a statement runs, and questions that print a grid or triangle. Always fill in a table with one row per outer iteration, and note whether the inner bound depends on the outer variable. Count executions with the product outer * inner for independent loops and the sum of the inner counts when they depend on each other. A println placed inside the inner loop, inside the outer loop but after the inner loop, or after both, produces three very different outputs.
Practice
What is printed?
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("x");
}
System.out.print("-");
}
Show answer
xxx-xxx-. For each of the 2 outer passes the inner loop prints three x characters and then the outer body prints a dash.
How many times is System.out.print("*") executed?
int count = 0;
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 6; j++) {
count++;
}
}
System.out.println(count);
Show answer
24 times, 4 * 6. The loops are independent, so the counts multiply.
What is printed?
for (int i = 1; i <= 3; i++) {
for (int j = i; j <= 3; j++) {
System.out.print(j);
}
System.out.println();
}
Show answer
123, 23, 3 on three lines. The inner loop starts at the current value of i, so it has fewer passes each time.
Write nested loops that print this triangle of stars: one star on the first line, two on the second, three on the third.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
Show answer
The inner bound j <= i makes line i contain i stars, and the println after the inner loop ends each line.
How many pairs of positions i < j exist in a String of length 6, and what does this code print?
int pairs = 0;
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
pairs++;
}
}
System.out.println(pairs);
Show answer
15 pairs. The inner loop runs 5, 4, 3, 2, 1, and 0 times, and 5 + 4 + 3 + 2 + 1 is 15.
What is printed? Explain why the output differs from the previous question about stars.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(j);
System.out.println();
}
}
Show answer
Nine lines with one digit each. The println is inside the inner loop, so a line ends after every digit instead of after every row. Where the line break sits, relative to the loops, controls the shape of the output.
Two correct programs can differ enormously in how long they take. A loop that checks 100 items and a loop that compares every item with every other item are both "correct" for finding duplicates, but one does about a hundred steps and the other almost five thousand. This lesson gives you the simple tool that explains the difference: counting how many times a statement is executed.
Required content · LO 2.12.A
Learning objective.
2.12.A. Calculate statement execution counts and informal run-time comparison of iterative statements.
Essential knowledge.
2.12.A.1. A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements.
Statement execution counts
A statement execution count indicates the number of times a statement is executed by the program. Execution counts are usually calculated informally, by tracing and analyzing the iterative statements. You do not need a formal notation: the skill is to say "this statement runs n times" or "about n * n times", and to compare two code segments on that basis.
You can check a count by adding a counter variable to the code. For each shape of loop, the count follows a pattern.
Code shape
Times the inner statement runs
a loop from 0 up to but not including n
n
a loop from 1 through n
n
two loops one after the other
n + n, or 2n
a loop that steps by 2
about n / 2
nested loops, independent
n * m
nested loops, inner j from 0 to i - 1
0 + 1 + ... + (n - 1), which is n(n - 1)/2
a loop that halves n each pass
about the number of times n can be halved (for 1000, about 10)
int n = 100;
int a = 0;
for (int i = 0; i < n; i++) {
a++;
}
int b = 0;
for (int i = 0; i < n; i += 2) {
b++;
}
int c = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c++;
}
}
System.out.println(a + " " + b + " " + c);
100 50 10000
With n equal to 100 the single loop runs 100 times, the step-by-2 loop runs 50, and the nested loops run 100 * 100.
Comparing two segments
To compare two code segments, find the execution count of the most-repeated statement in each, and see how each count grows as the input gets bigger.
public static int linearCount(int n) {
int steps = 0;
for (int i = 0; i < n; i++) {
steps++;
}
return steps;
}
public static int pairCount(int n) {
int steps = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
steps++;
}
}
return steps;
}
Making the input 10 times bigger makes the first count 10 times bigger but the second count about 100 times bigger. That is the practical meaning of "slower": not how long a single step takes, but how fast the number of steps grows. Checking every pair is fine for 100 items and painful for a million.
Worked example · a dependent inner loop
How many times does the statement in the inner loop run?
int count = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
count++;
}
}
System.out.println(count);
15
i
1
2
3
4
5
inner runs
1
2
3
4
5
The total is 1 + 2 + 3 + 4 + 5 = 15. Changing the inner test to j < i changes the total to 0 + 1 + 2 + 3 + 4 = 10: one fewer on each pass, five fewer overall.
Worked example · a loop that halves
How many times does the body of this loop run for n equal to 1000?
int n = 1000;
int count = 0;
while (n > 1) {
n /= 2;
count++;
}
System.out.println(count);
9
Pass
n after the pass
1
500
2
250
3
125
4
62
5
31
6
15
7
7
8
3
9
1
A loop that cuts the problem in half each time takes very few passes even for huge inputs: doubling n to 2000 adds only one pass. You will meet this behavior again in binary search (Lesson 4.17).
Worked example · two ways to find a duplicate
A list of n values has a duplicate if two positions hold the same value. Compare the counts of two designs without needing the details of the data.
int n = 50;
int onePass = 0;
for (int i = 0; i < n; i++) {
onePass++;
}
int everyPair = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
everyPair++;
}
}
System.out.println(onePass + " " + everyPair);
50 1225
Checking every pair needs 50 * 49 / 2 = 1225 comparisons, against 50 for a single pass. The comparison is not about speed on one machine; it is about how each count grows. When you design an algorithm, ask how many times its busiest statement will run.
Exam focus
The exam asks you to calculate statement execution counts for loops (and nested loops) and to compare two segments that do the same job. Count by listing the values of the loop control variables, not by guessing; handle < against <= and the starting value carefully. For comparisons, say which count is larger and how each grows as n grows. No formal notation is required.
Practice
How many times does the statement run?
int count = 0;
for (int i = 3; i <= 12; i++) {
count++;
}
System.out.println(count);
Show answer
10 times. The values of i are 3 through 12 inclusive, which is 12 - 3 + 1.
How many times does the statement run when n is 40?
int n = 40;
int count = 0;
for (int i = 0; i < n; i += 5) {
count++;
}
System.out.println(count);
Show answer
8 times. The values of i are 0, 5, 10, 15, 20, 25, 30, and 35.
How many times is count++ executed?
int count = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 4; j++) {
count++;
}
}
for (int k = 0; k < 10; k++) {
count++;
}
System.out.println(count);
Show answer
34 times. The nested loops contribute 6 * 4 = 24 and the separate loop adds 10; consecutive loops add, nested loops multiply.
Segment A runs a single loop n times. Segment B runs a loop of n iterations nested inside another loop of n iterations. For n equal to 20, how many times does each inner statement execute, and which is larger?
int n = 20;
int a = 0;
for (int i = 0; i < n; i++) {
a++;
}
int b = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b++;
}
}
System.out.println(a + " " + b);
Show answer
A runs 20 times and B runs 400 times. B is larger, and the gap widens as n grows: for n equal to 1000 it is 1000 against 1,000,000.
How many times is the loop body executed?
int n = 64;
int count = 0;
while (n >= 2) {
n = n / 2;
count++;
}
System.out.println(count);
Show answer
6 times. The value of n goes 64, 32, 16, 8, 4, 2, and 1, and the loop stops when n is below 2.
Which of these segments executes its inner statement more times for n equal to 10: for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) or for (int i = 0; i < n; i++) for (int j = 0; j < i; j++)?
int n = 10;
int p = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p++;
}
}
int q = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
q++;
}
}
System.out.println(p + " " + q);
Show answer
The first runs 100 times and the second runs 45 times (0 + 1 + ... + 9). In the second, the inner loop does less work on each pass because its bound is i instead of n.
Unit 2 review · 10 multiple-choice
Unit 2 review: selection and iteration
Ten exam-style multiple-choice questions in lesson order (boolean expressions and
String comparison, if and nested if, compound conditions and De Morgan's laws, while and for loops,
the accumulator patterns, String traversal, nested iteration and statement counting) with every
printed value taken from a real run of the code.
Multiple choice
A program stores a secret pass phrase and then assembles the phrase the user types, one
piece at a time, before checking it.
What is printed as a result of executing the code segment?
This assumes == compares the letters. For objects,
== asks whether the two variables hold the same address, and the concatenation
on line 3 built a brand-new String object rather than reusing the one named
secret.
Correct. The decisive line is line 3: joining "op" and
"e" at run time produces a new object, so typed and
secret are two different objects that happen to hold the same characters.
== reports false on the addresses while equals reports
true on the contents.
equals compares character by character, and both Strings hold
o, p, e in that order, so the second value cannot be false. Getting this half
wrong usually means treating equals as a synonym for ==.
This has the two comparisons backwards. == is the one that fails
on separately built Strings, and equals is the one that succeeds, which is
exactly why the exam insists on equals for every String comparison.
int x = 5;
if (x > 10);
{
x = x + 1;
}
System.out.println(x);
What is the value of x after the code segment executes?
5 is what you would get if the block belonged to the if. Read the
semicolon at the end of line 2: it closes the if immediately, so the block below
is no longer attached to any condition.
Correct. The semicolon after if (x > 10) is a complete empty
statement, so the if controls nothing at all. The braces that follow are just an
ordinary block that always executes, and x goes from 5 to 6 even though
x > 10 is false.
11 would require the condition to be true and the body to add 6, neither of
which happens. The body adds 1, and the condition is irrelevant because nothing depends
on it.
A semicolon there is legal Java, which is exactly why this bug is dangerous:
the compiler accepts it silently and the program simply does the wrong thing. Removing the
semicolon is the fix.
What is printed as a result of executing the code segment?
This is the result the author probably wanted, and it is what an
if / else if chain would produce. The two if
statements here are independent, though, so the first one does not stop the second from
being tested.
Correct. The 12-pound order is charged twice: 12 is greater than 10, adding
12.0, and it is also greater than 5, adding 8.0, for 20.0. The 7-pound order fails the first
test and passes the second, giving 8.0, and the 3-pound order falls to the
else, giving 4.0. Writing else if in front of the second test would make all three
tiers exclusive.
7 pounds never reaches the 12.0 charge, because 7.0 > 10.0 is
false. The double charge in this method can only happen above 10 pounds, where both
conditions are true at once.
This charges both orders 12.0. The 7-pound order fails
pounds > 10.0, so it never receives the 12.0, and the 12-pound order
passes both tests and receives 12.0 and then 8.0 more, so its charge is larger than the
7-pound order's, not equal to it.
String word = null;
if (word != null && word.length() > 2) {
System.out.println("long");
}
else {
System.out.println("skipped");
}
What is printed as a result of executing the code segment?
long requires both operands of && to be
true, and the first one is already false because word holds null.
A false left operand settles an && on its own.
Correct. && short-circuits: once
word != null evaluates to false, the whole condition is known to be false and
word.length() is never evaluated. The else branch runs and prints
skipped. This ordering is the standard null guard, and reversing the two
operands would break it.
Calling length() on null would indeed throw a
NullPointerException, but that call never happens here. Short-circuiting is
what protects it, which is the entire reason the null test is written first.
An if with an else always takes exactly one of its
two branches, so something is always printed. A false condition sends control to the
else, it does not skip the statement altogether.
The method below is being rewritten so that it returns its answer directly instead of
returning true or false from an if-else.
public static boolean isSafe(int x, int y) {
if (!(x > 10 && y > 10)) {
return true;
}
else {
return false;
}
}
public static boolean isSafe(int x, int y) {
/* missing code */
}
Which replacement for /* missing code */ makes the method work as intended for all int values of x and y?
Negating && gives ||, not
&&. Testing both versions on every pair from 0 through 20 shows 220
disagreements, the first at x = 0, y = 11, where the original
returns true and this replacement returns false.
Correct. De Morgan's law turns !(x > 10 && y > 10)
into !(x > 10) || !(y > 10), and negating each relational operator gives
x <= 10 || y <= 10. Checked against the original on all 441 pairs from 0
through 20, it agrees every time, and returning the condition directly is always better
than if (c) return true; else return false;.
This drops the outer ! and changes && to
|| while keeping the original > tests, which negates
nothing correctly. It disagrees with the original on 221 of the 441 pairs from 0 through
20; at x = 0, y = 0 the original returns true while this
returns false.
The shape is right but the boundary is wrong. The negation of
x > 10 is x <= 10, not x < 10, so the
value 10 is mishandled. At x = 10, y = 10 the original returns
true and this returns false; the two disagree on 21 of the 441 pairs from 0 through 20.
int n = 4073;
int count = 0;
while (n > 0) {
n = n / 10;
count++;
}
How many times does the body of the loop execute?
3 counts the divisions that leave something behind and forgets the last one.
The fourth pass starts with n equal to 4, and 4 > 0 is true, so
the body runs a fourth time before the condition finally fails.
Correct. Integer division walks n through 4073, 407, 40, 4, then
0. The pass that decides the answer is the fourth: n is 4, the condition is
still true, the body runs and makes n zero, and the fifth test fails. The
result is the number of digits in 4073.
5 counts one test too many. The pass that sets n to 0 is the
fourth; the fifth time the condition is checked it is false, so no fifth body executes:
count bodies, not tests.
The loop stops when n reaches 0, and it does not need to go
negative. Integer division of a positive number by 10 always shrinks it, so this loop is
guaranteed to terminate; it is deleting the update line that would make it infinite.
int sum = 0;
for (int i = 3; i < 30; i = i + 3) {
sum = sum + i;
}
System.out.println(sum);
Which of the following code segments produces the same output as the code segment above?
Changing < to <= lets i reach 30
and adds one extra term, so this prints 165 instead of 135. The bound in a
for header must survive the translation unchanged.
Updating before accumulating skips the first value and picks up an extra one
at the end: this adds 6 through 30 and prints 162. In a for loop the update
runs after the body, so the body must come first here too.
Correct. A for loop is a while loop with its three
parts moved: initialization before the loop, the same condition in the header, and the update
as the last statement of the body. Both segments add 3, 6, 9, and on up to 27 and print 135.
Moving the update outside the braces means i stays 3 forever and
the condition never becomes false. Compiled and run, this segment never terminates and prints
nothing at all.
public static int largest(int low, int high) {
int max = 0;
for (int n = low; n <= high; n++) {
int value = 12 - n * n;
if (value > max) {
max = value;
}
}
return max;
}
What does the call largest(4, 7) return?
12 is the constant in the formula, not a value the formula produces here.
value would only be 12 if n were 0, and this call starts
n at 4.
Correct. The four values are 12 - 16, 12 - 25,
12 - 36 and 12 - 49, or -4, -13, -24 and -37. Every one of them
fails value > max on the very first comparison, so max never
moves off its starting 0 and the method returns a number the formula never produced. Start
the running maximum at the first data value instead.
-4 is the true largest value, and it is what the method should
return, but it never gets stored, because -4 is not greater than the initial 0. This is the
gap the question is testing.
-37 is the smallest of the four values and the last one computed. The
if only overwrites max with something larger, so the final value
computed has no special status.
String word = "class";
String result = "";
for (int i = 0; i < word.length(); i++) {
result = word.substring(i, i + 1) + result;
}
System.out.println(result);
What is printed as a result of executing the code segment?
class is what you get from
result = result + word.substring(i, i + 1);, with the accumulator on the left.
The order of the two operands around + is the whole difference between copying
a String and reversing it.
Correct. Each new character is glued to the front of what has been
built so far, so result grows c, lc, alc, salc, ssalc. The decisive pass is the
last one, i = 4: the s at index 4 goes in front of salc and
produces ssalc.
This loses the first character, which would happen if the loop started at
i = 1. The header starts at 0, and index 0 is the c, so all five characters are
visited.
The largest value i reaches is 4, so the last call is
substring(4, 5), which is legal on a five-character String: the second
argument may equal the length. The condition i < word.length() is what keeps
it in bounds.
int count = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
count++;
}
}
System.out.println(count);
How many times does the body of the inner loop execute?
25 is 5 times 5, the count you get when the inner bound is the same constant
as the outer one. Here the inner condition is j < i, so the inner loop runs a
different number of times on each outer pass.
20 would be 5 times 4, which treats the inner loop as running 4 times every
pass. It runs 4 times only on the final pass, when i is 4.
Correct. The inner loop runs 0 times when i is 0, then 1, 2, 3
and 4 times, and 0 + 1 + 2 + 3 + 4 is 10: the formula n * (n - 1) / 2 with
n equal to 5. The first outer pass is the one people miss: an empty inner loop
still counts as an outer pass. Even so, this shape grows like n squared, so
doubling n roughly quadruples the count.
15 is 1 + 2 + 3 + 4 + 5, which would be right if the inner condition were
j <= i. With j < i the inner body runs exactly
i times on each pass, so the sum starts at 0 and stops at 4.
A large program is too big for anyone to hold in their head all at once. The tool every programmer uses to cope is abstraction: deciding which details matter for the problem at hand, hiding the rest, and giving the result a name. Everything in this unit (classes, methods, constructors, access rules) is abstraction put to work. This lesson comes first because it explains why the code in the next lessons is shaped the way it is, and because the exam asks you to design a class before you write one.
Required content · LO 3.1.A
Learning objective.
3.1.A. Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.
Essential knowledge.
3.1.A.1. Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
3.1.A.2. Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. Data abstraction manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data.
3.1.A.3. An attribute is a type of data abstraction that is defined in a class outside any method or constructor. An instance variable is an attribute whose value is unique to each instance of the class. A class variable is an attribute shared by all instances of the class.
3.1.A.4. Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. Through method decomposition, a programmer breaks down larger behaviors of the class into smaller behaviors by creating methods to represent each individual smaller behavior. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for code reuse, which helps manage complexity.
3.1.A.5. Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
3.1.A.6. Using procedural abstraction in a program allows programmers to change the internals of a method (to make it faster, more efficient, use less storage, etc.) without needing to notify method users of the change as long as the method signature and what the method does is preserved.
3.1.A.7. Prior to implementing a class, it is helpful to take time to design each class including its attributes and behaviors. This design can be represented using natural language or diagrams.
What abstraction is
Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows you to focus on the idea. A road map is an abstraction: it hides the trees and shows the roads. When you drive with it you do not care about the trees.
Programs use two kinds.
### Data abstraction
Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. It manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data. A String is a data abstraction: you use it as "some text" and never need to know how its characters are stored.
An attribute is a type of data abstraction that is defined in a class outside any method or constructor. There are two kinds.
An instance variable is an attribute whose value is unique to each instance of the class. Every Student object has its own name.
A class variable is an attribute shared by all instances of the class. All Student objects share one count of how many students exist.
### Procedural abstraction
Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. You have used it all along: Math.sqrt(49) gives 7.0, and you have never needed to see how. Two ideas make it work in your own code.
Method decomposition. A programmer breaks down larger behaviors of a class into smaller behaviors by creating methods to represent each individual smaller behavior.
Generalizing with parameters. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. Using parameters allows a procedure to be reused with a range of input values, or arguments. This allows for code reuse, which helps manage complexity.
Because the user of a method relies only on what it does, a programmer can change the internals of a method (to make it faster, more efficient, use less storage) without notifying the method's users, as long as the method signature and what the method does are preserved.
Designing a class before writing it
Before implementing a class, it helps to design it: decide what it represents, what data each object must hold (its attributes), and what each object must be able to do (its behaviors). A design can be written in natural language or drawn as a diagram. A class diagram has the class name at the top, the attributes in the middle, and the behaviors at the bottom.
Figure 3.1. A class diagram: the name on top, the attributes in the middle, and the behaviors at the bottom. Nothing in the diagram says how the methods work, only what they are called, what they take, and what they return.
Worked example · from a description to a design
A school tracks students. Each student has a name, a grade level from 9 to 12, and a count of credits earned. A student can report the name, earn more credits, and say whether the student has enough credits (at least 20) to be a senior.
Part of the design
Name
Type or signature
class
Student
attribute (instance variable)
name
String
attribute
gradeLevel
int
attribute
credits
int
behavior (accessor)
getName
String getName()
behavior (mutator)
addCredits
void addCredits(int amount)
behavior
hasSeniorCredits
boolean hasSeniorCredits()
Reading the description gives the design: nouns that describe each object become attributes; verbs and questions become behaviors. Notice what the design leaves out: nothing says how credits is stored or how hasSeniorCredits decides. Those are implementation details, hidden behind the signatures.
Worked example · method decomposition and parameters
The first version repeats the same two lines for each purchase. The second extracts them into a method with parameters.
Item: pen
Price: 2 x 3 = 6
Item: book
Price: 12 x 2 = 24
public static void printLine(String item, int price, int qty) {
System.out.println("Item: " + item);
System.out.println("Price: " + price + " x " + qty + " = " + (price * qty));
}
printLine("pen", 2, 3);
printLine("book", 12, 2);
Item: pen
Price: 2 x 3 = 6
Item: book
Price: 12 x 2 = 24
The output is identical, but the second program has one place to fix a mistake instead of two, and a third purchase costs one line, not two. The parameters item, price, and qty generalize the code to a range of arguments.
Worked example · changing the internals without telling the users
A method sumTo(n) returns 1 + 2 + ... + n. Here is a version that loops.
public static int sumTo(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
Every caller keeps working with no change, even though the loop is gone. That freedom is the payoff of procedural abstraction: users depend on what, never on how.
Exam focus
Expect conceptual questions: which description is an example of data abstraction or procedural abstraction, what decomposition accomplishes, why a method with parameters is more reusable, the difference between an instance variable and a class variable, and what a programmer is allowed to change without telling the users of a method (the internals; never the signature or the behavior). For design questions you are given a description and asked for the attributes and behaviors a class needs. Use the nouns-and-verbs rule, and keep the design free of implementation details.
Practice
A programmer uses Math.sqrt without knowing how it computes the root. Which kind of abstraction does this show?
Show answer
Procedural abstraction: the method is used knowing what it does, not how it does it.
A class Game has a String variable title that is different for each game and an int variable gamesCreated that counts all games ever made. Which is the instance variable and which is the class variable?
Show answer
title is an instance variable, since each Game object has its own value. gamesCreated is a class variable, because one value is shared by all instances of the class.
Why is sumTo(int n) more reusable than a block that adds the numbers 1 through 10 directly?
public static int sumTo(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
System.out.println(sumTo(10) + " " + sumTo(3));
Show answer
The parameter n generalizes the procedure: the same code works for any range of arguments (10 and 3 here) instead of for one hard-coded value.
A method's author changes its body to run faster but keeps the same signature and the same results. Must the callers of the method be changed?
Show answer
No. As long as the method signature and what the method does are preserved, users of the method are not affected, which is a benefit of procedural abstraction.
List the attributes and behaviors you would design for a class Ticket that stores an event name and a price, can report its price, and can apply a discount in percent.
Show answer
Attributes: eventName (a String) and price (a number, double). Behaviors: double getPrice() and void applyDiscount(int percent). The design does not say how the discount is calculated.
Method decomposition means breaking a large behavior into smaller ones. Name two benefits.
Show answer
Each smaller method can be named, understood, tested, and reused on its own, and shared steps are written once instead of being duplicated, so a change is made in one place. Both help manage complexity.
Programs are not private experiments. They run people's bank accounts, decide which posts appear first, and store addresses and photographs. A program that does exactly what its programmer intended can still hurt someone. This lesson is different from the others in the unit: there is little code, and the questions are about judgment. The exam includes such questions, and you answer them the way you answer any other: by applying precise definitions to a concrete case.
Required content · LO 3.2.A
Learning objective.
3.2.A. Explain the social and ethical implications of computing systems.
Essential knowledge.
3.2.A.1. System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions.
3.2.A.2. The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use.
3.2.A.3. Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source and free to use. Incorporation of code that is not published as open source requires the programmer to obtain permission and often purchase the code before integrating it into their program.
Reliability
System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions: typical values, boundary values, and invalid or unexpected ones. A program tested only on the inputs its author thought of will eventually meet one the author did not.
Impact on society, the economy, and culture
The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use. A way to reason about a program's impact is to ask four questions.
What need does the program fill, and who benefits?
Who could be harmed, even if no one intended it?
What could the program be used for beyond its purpose?
What would go wrong if the program were wrong?
Legal and intellectual property concerns
Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source, free to use. Incorporating code that is not published as open source requires the programmer to obtain permission, and often to purchase the code, before integrating it into a program. Code does not become free to copy because it is easy to copy.
Worked example · testing under a variety of conditions
A quiz program reports the percent of questions answered correctly.
public static int percent(int correct, int total) {
return correct * 100 / total;
}
A reliable program is tested with more than the typical case.
Exception in thread "main" java.lang.ArithmeticException: / by zero
The first three calls pass (75, 0, 100), and the fourth fails: a quiz with no questions makes the program crash. Testing found it. The fix is a design decision: either return a defined value (such as 0) when total is 0, or document a precondition that total is positive. A reliable system decides, and says which.
Worked example · an unintended harmful effect
A phone app shows other runners nearby and publishes each runner's route so friends can cheer them on. It is popular and encourages people to exercise.
Question
Answer for this program
What need does it fill, and who benefits?
Motivation and community for people who exercise.
Who could be harmed?
Runners whose home and daily schedule can be deduced from public routes.
What could it be used for beyond its purpose?
Someone could use the route data to follow a person or to learn when a house is empty.
What if the program is wrong?
A bug that shows routes that were meant to be private causes the same harm without any intent.
The program is both beneficial (it helps people stay active) and harmful (it puts personal privacy at risk). Neither effect cancels the other; the programmer's job is to see the harmful possibilities in advance and design against them, for example with private routes by default.
Worked example · reusing code that belongs to someone else
A student is building a game to sell. She finds a ready-made sorting method on a website. The page shows the code but says nothing about a license. A second method she found is in a library whose page says "released as open source and free to use."
Code
Status
What she should do
The method on the site with no license information
Not published as open source
Obtain the owner's permission (and perhaps pay) before putting it in a program she will sell. Without permission, using it is a legal and intellectual property problem.
The library marked open source and free to use
Published as open source
She may use it within the stated terms. Open source means free to use, and it still helps to credit the author.
Being able to see code, or to copy it with two keystrokes, does not give permission to use it. Whether it was published as open source, or sold with a license, decides.
Exam focus
Expect short scenarios followed by four answers, asking which statement is true: an unintended harmful effect of a program, a privacy risk of collecting personal data, a reason to test with more inputs, or what must be done before including someone's code. Use the exact definitions: reliability is performing as expected under stated conditions without failure, and testing under a variety of conditions maximizes it; harmful effects may be unintended; code not published as open source needs permission. Choose the answer that applies the definition, not the one that sounds most dramatic.
Practice
A programmer tests a program with only the three inputs that she used while writing it, and it works. Which statement best describes the program's reliability?
A. It is fully reliable because it passed every test.
B. Reliability is unknown, because it was not tested under a variety of conditions.
C. It is unreliable because three tests are too few.
D. Reliability does not depend on testing.
Show answer
B. Reliability means performing as expected under stated conditions without failure, and a program must be tested with a variety of conditions (typical, boundary, and invalid) to maximize it. Three familiar inputs say little about the rest.
A program is written to recommend which job applications to look at first. It was trained on past hiring decisions, and it now ranks applicants from some neighborhoods lower. Which statement describes this?
A. An unintended harmful effect of a program built to solve a problem.
B. A guaranteed benefit of automation.
C. An intellectual property violation.
D. A run-time error.
Show answer
A. The program was meant to help, but it can harm a group of people in a way no one intended. This is an unintended harmful effect (and an example of the bias covered in Lesson 4.1).
A company wants to include a sorting routine it found in someone's private (not open source) project. What must it do first?
Show answer
Obtain permission from the owner, and probably pay for it. Code that is not published as open source cannot be integrated into a program without that permission.
A developer says, "My weather app has helped millions, so it cannot cause harm." Explain the flaw.
Show answer
Programs can have both beneficial and harmful effects at the same time. Benefit to many people does not rule out harm, such as a privacy risk or a wrong forecast that people rely on.
For the method below, name one input value that tests the boundary and one that tests an invalid case.
The boundary values are half(0) and half(1): both give 0, because the fraction is dropped, so they sit where the behavior changes. A typical case is half(7), which gives 3. This method has no invalid input that makes it fail, so there is no division-by-zero case to find.
Programs often reuse open source libraries. Which two things should a programmer check before reusing code from the internet?
Show answer
Whether the code is published as open source or otherwise licensed for the use the programmer plans, and whether it is reliable (tested under a variety of conditions) for the way it will be used.
You have been using classes written by other people. From here on you write them. A class is a blueprint with three kinds of parts: the data each object holds, the constructors that create objects, and the methods that define what objects can do. This lesson shows the shape of a class and the one rule that governs all of it: who is allowed to touch what.
Required content · LO 3.3.A
Learning objective.
3.3.A. Develop code to designate access and visibility constraints to classes, data, constructors, and methods.
Essential knowledge.
3.3.A.1. Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
3.3.A.2. In this course, classes are always designated public and are declared with the keyword class.
3.3.A.3. In this course, constructors are always designated public.
3.3.A.4. Instance variables belong to the object, and each object has its own copy of the variable.
3.3.A.5. Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.
3.3.A.6. Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class.
The parts of a class
public class BankAccount {
private String owner;
private int balance;
public BankAccount(String name, int start) {
owner = name;
balance = start;
}
public String getOwner() {
return owner;
}
public int getBalance() {
return balance;
}
public void deposit(int amount) {
balance += amount;
}
}
The class header is public class BankAccount. In this course classes are always designated public and are declared with the keyword class.
The instance variablesowner and balance hold the object's data. They belong to the object, and each object has its own copy.
The constructorBankAccount(String, int) has the same name as the class and sets up a new object. In this course constructors are always public.
The methodsgetOwner, getBalance, and deposit define behaviors.
BankAccount a = new BankAccount("Ada", 100);
BankAccount b = new BankAccount("Ben", 40);
a.deposit(25);
System.out.println(a.getOwner() + " " + a.getBalance());
System.out.println(b.getOwner() + " " + b.getBalance());
Ada 125
Ben 40
Depositing into a changed only a's balance. The two objects have separate copies of the instance variables.
Encapsulation: public and private
Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private set the access of classes, data, constructors, and methods:
private restricts access to the declaring class.
public allows access from classes outside the declaring class.
Member
Declared as
Accessible from the same class
Accessible from another class
instance variable
private
yes
no
constructor
public
yes
yes
method
public
yes
yes
method
private
yes
no
Access to attributes should be kept internal to the class in order to accomplish encapsulation. It is good programming practice to designate instance variables as private unless the class specification states otherwise. Other classes then work with the object only through its public methods, which means the class can change how it stores balance (say, in cents) without breaking any code that uses it.
Access to behaviors can be internal or external to the class. A public method can be called from anywhere, and a private method can only be called from inside the class. Private methods are typically helpers: pieces of a larger behavior that outsiders have no business calling.
public class SafeAccount {
private int balance;
public SafeAccount(int start) {
balance = start;
}
private boolean isValid(int amount) {
return amount > 0;
}
public void deposit(int amount) {
if (isValid(amount)) {
balance += amount;
}
}
public int getBalance() {
return balance;
}
}
SafeAccount s = new SafeAccount(10);
s.deposit(5);
s.deposit(-3);
System.out.println(s.getBalance());
15
The public deposit calls the private isValid, and the negative deposit is quietly refused. The outside code never sees isValid.
What the compiler says when you break the rule
BankAccount acct = new BankAccount("Cy", 5);
System.out.println(acct.balance);
Main.java:2: error: balance has private access in BankAccount
Reaching in to a private variable is a compile-time error. Only the class's own methods may read or change it. The same error appears for a private method: s.isValid(4) from outside the class fails with isValid(int) has private access in SafeAccount.
Worked example · reading a class
Decide which statements compile, from a class Main that is separate from BankAccount.
Statement
Compiles?
Why
BankAccount x = new BankAccount("Di", 20);
yes
the constructor is public
x.deposit(5);
yes
deposit is public
int b = x.getBalance();
yes
getBalance is public
int c = x.balance;
no
balance is private
x.balance = 1000;
no
balance is private
String o = x.getOwner();
yes
getOwner is public
The class designer decided that the only legal ways to change a balance are the public methods. A bank wants that: nobody can set balance to a million dollars without a deposit.
Worked example · every object has its own copy
Trace the state of two objects.
BankAccount p = new BankAccount("Eve", 50);
BankAccount q = new BankAccount("Eve", 50);
p.deposit(10);
q.deposit(20);
p.deposit(5);
System.out.println(p.getBalance() + " " + q.getBalance());
After the statement
p's balance
q's balance
construction
50
50
p.deposit(10)
60
50
q.deposit(20)
60
70
p.deposit(5)
65
70
65 70
The two objects were created from the same blueprint with the same arguments, yet they never interfere. Each has its own owner and its own balance.
Worked example · completing a class from its specification
Write a class Light that stores whether it is on (starting off), can be switched, and can report its state.
public class Light {
private boolean on;
public Light() {
on = false;
}
public void toggle() {
on = !on;
}
public boolean isOn() {
return on;
}
}
Light lamp = new Light();
lamp.toggle();
System.out.println(lamp.isOn());
lamp.toggle();
System.out.println(lamp.isOn());
true
false
Instance variable private, constructor public, methods public: the standard pattern. The state of on can be read only through isOn() and changed only through toggle().
Exam focus
Expect to read a class and decide whether a statement in another class compiles, and to complete the declaration of a class so that it follows the course's conventions: public class, private instance variables, public constructors, public methods (unless the specification says a helper is private). The question is nearly always who can access what: remember that private means "only inside this class". Questions about copies ask what each object holds after several method calls.
Practice
Why does the line System.out.println(acct.balance); not compile when it is in another class?
Show answer
balance is a private instance variable, so it can only be accessed from inside BankAccount. Other classes must use a public method such as getBalance().
Which keyword should normally be used for the instance variables of a class in this course?
Show answer
private, unless the class specification states otherwise. This keeps the object's data inside the class, which is encapsulation.
What is printed?
Light a = new Light();
Light b = new Light();
a.toggle();
System.out.println(a.isOn() + " " + b.isOn());
Show answer
true false. Each Light has its own on. Toggling a does not affect b.
A class has a private method isValid(int). Which of these may call it? (a) another method in the same class, (b) code in main of a different class
Show answer
(a) only. A private method can be called only from inside the class that declares it; a call from another class does not compile.
Complete the class so that Counter stores a count that starts at 0, can be increased by one, and can report its value.
public class Counter {
private int count;
public Counter() {
count = 0;
}
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
Counter c = new Counter();
c.increment();
c.increment();
System.out.println(c.getCount());
Show answer
The class above: a private int count, a public constructor that sets it to 0, a public void increment() that adds 1, and a public int getCount() that returns it.
Give one reason to make instance variables private even if no one is trying to misuse them.
Show answer
The class can change how it stores its data (for example from dollars to cents) without breaking any other code, because other classes only use the public methods. Private data also prevents accidental illegal changes, such as setting a balance to a nonsense value.
A constructor has one job: to make sure that a brand-new object starts out in a sensible state. Without one, an object would begin with whatever Java puts in its instance variables by default, and every program that creates the object would have to fix it up. This lesson covers how constructors set up an object's state, how overloaded constructors give callers choices, what Java does when you write none, and the one hazard that appears when a constructor is handed another object.
Required content · LO 3.4.A
Learning objective.
3.4.A. Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.
Essential knowledge.
3.4.A.1. An object’s state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a has-a relationship between the object and its instance variables.
3.4.A.2. A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
3.4.A.3. When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object.
3.4.A.4. When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor.
3.4.A.5. The default value for an attribute of type int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null.
State and the constructor
An object's state refers to its attributes and their values at a given time, and it is defined by the instance variables belonging to the object. An object has its instance variables, which is called a has-a relationship.
A constructor is used to set the initial state of an object, and it should give an initial value to every instance variable. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide the data used to initialize the instance variables.
public class Pet {
private String name;
private int energy;
public Pet(String petName, int startEnergy) {
name = petName;
energy = startEnergy;
}
public Pet(String petName) {
name = petName;
energy = 10;
}
public String getName() {
return name;
}
public int getEnergy() {
return energy;
}
}
Pet rex = new Pet("Rex", 7);
Pet mia = new Pet("Mia");
System.out.println(rex.getName() + " " + rex.getEnergy());
System.out.println(mia.getName() + " " + mia.getEnergy());
Rex 7
Mia 10
The class has two constructors, so they are overloaded: the arguments decide which runs. new Pet("Mia") uses the one-parameter constructor, which supplies the default starting energy of 10.
When you write no constructor
When no constructor is written, Java provides a no-parameter constructor, called the default constructor, and the instance variables are set to default values according to their type.
Type of the instance variable
Default value
int
0
double
0.0
boolean
false
any reference type (such as String)
null
public class Blank {
private int count;
private double ratio;
private boolean flag;
private String label;
public String describe() {
return count + " " + ratio + " " + flag + " " + label;
}
}
Blank b = new Blank();
System.out.println(b.describe());
0 0.0 false null
The null is the dangerous default: calling a String method on label before it is assigned throws a NullPointerException. This is one reason a constructor should initialize every instance variable.
Writing any constructor removes the default one. If you write only a constructor with parameters, a call with no arguments no longer compiles.
public class Lamp {
private int watts;
public Lamp(int w) {
watts = w;
}
}
Lamp l = new Lamp();
Main.java:2: error: constructor Lamp in class Lamp cannot be applied to given types;
A constructor that receives an object
When a mutable object, one whose state can change, is passed to a constructor, the instance variable should be initialized with a copy of the referenced object. If the constructor stores the reference instead, the instance variable and the caller's variable refer to the same object, and later changes made by the caller silently change the new object's state.
public class Point {
private int x;
private int y;
public Point(int px, int py) {
x = px;
y = py;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
}
public class CopyPin {
private Point spot;
public CopyPin(Point p) {
spot = new Point(p.getX(), p.getY());
}
public int getX() {
return spot.getX();
}
}
public class AliasPin {
private Point spot;
public AliasPin(Point p) {
spot = p;
}
public int getX() {
return spot.getX();
}
}
Point origin = new Point(1, 1);
CopyPin safe = new CopyPin(origin);
AliasPin risky = new AliasPin(origin);
origin.move(5, 5);
System.out.println(safe.getX() + " " + risky.getX());
1 6
CopyPin built its own Point, so moving origin did not touch it. AliasPin kept the caller's object, so it moved too. When a class should own its data, copy it.
Worked example · writing constructors from a specification
Write a class Rectangle with a width and a height. One constructor takes both; another takes one side and makes a square.
public class Rectangle {
private int width;
private int height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
public Rectangle(int side) {
width = side;
height = side;
}
public int area() {
return width * height;
}
}
Rectangle r = new Rectangle(3, 5);
Rectangle s = new Rectangle(4);
System.out.println(r.area() + " " + s.area());
15 16
Both constructors initialize both instance variables. A constructor that left height unset would leave it at the default 0 and make area() return 0.
Worked example · a constructor that forgets a variable
What is printed?
public class Tag {
private String text;
private int size;
public Tag(String t) {
text = t;
}
public int getSize() {
return size;
}
public String getText() {
return text;
}
}
Tag tag = new Tag("sale");
System.out.println(tag.getText() + " " + tag.getSize());
sale 0
The constructor sets only text, so size keeps the default value 0 for an int. No error is reported: this is a logic error. A constructor should state the initial value of every instance variable.
Worked example · which constructor runs
Trace the calls and give each object's state.
public class Seat {
private int row;
private boolean taken;
public Seat() {
row = 1;
taken = false;
}
public Seat(int r) {
row = r;
taken = false;
}
public Seat(int r, boolean t) {
row = r;
taken = t;
}
public String info() {
return row + ":" + taken;
}
}
Seat a = new Seat();
Seat b = new Seat(7);
Seat c = new Seat(9, true);
System.out.println(a.info() + " " + b.info() + " " + c.info());
1:false 7:false 9:true
Call
Constructor
row
taken
new Seat()
no parameters
1
false
new Seat(7)
one int
7
false
new Seat(9, true)
int, boolean
9
true
Exam focus
Expect to be given a class and a new call and asked for the state of the object afterward, or to complete a constructor so that it initializes all the instance variables from its parameters. Know the defaults (0, 0.0, false, null) and that writing any constructor removes the default one. For a class whose constructor receives an object that can change, the correct code copies it.
Practice
What is the state of the object after the code runs?
public class Cup {
private int ounces;
private boolean full;
public Cup(int o) {
ounces = o;
}
public String info() {
return ounces + " " + full;
}
}
Cup c = new Cup(12);
System.out.println(c.info());
Show answer
12 false. The constructor sets ounces; full was never assigned, so it keeps the default value for boolean, which is false.
A class has the single constructor public Book(String t, int p). Does new Book("Atlas") compile?
Show answer
No. Only a constructor with the signature Book(String, int) exists, and Java does not supply the default one once any constructor is written. The call has the wrong number of arguments.
Write the constructor for a Student class with private String name; and private int grade; that sets both from parameters.
public class Student {
private String name;
private int grade;
public Student(String studentName, int studentGrade) {
name = studentName;
grade = studentGrade;
}
public String info() {
return name + " " + grade;
}
}
The constructor above: public Student(String studentName, int studentGrade) with the two assignments. The parameters have names different from the instance variables here (Lesson 3.9 covers this).
What are the default values of the instance variables of a class that has no constructor and these fields: int a; double b; boolean c; String d;?
Show answer
a is 0, b is 0.0, c is false, and d is null.
Why should a class that receives a Point in its constructor store a copy of the point and not the point itself?
Show answer
If the class stores the caller's reference, later changes the caller makes to that Point also change the class's data, because both refer to the same object. A copy gives the class its own Point that nobody else can change.
Which constructor runs for new Rectangle(6), and what is the area of the result?
public class Rectangle {
private int width;
private int height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
public Rectangle(int side) {
width = side;
height = side;
}
public int area() {
return width * height;
}
}
System.out.println(new Rectangle(6).area());
Show answer
The one-parameter constructor, Rectangle(int), runs, because the call supplies one int. It makes a 6 by 6 square, with area 36.
Constructors build objects; methods are what objects do. This lesson is about the two shapes a method can have, one that does something and one that gives back an answer, and about the return statement, which is more powerful than it looks because it ends the method on the spot.
Required content · LO 3.5.A
Learning objective.
3.5.A. Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.
Essential knowledge.
3.5.A.1. A void method does not return a value. Its header contains the keyword void before the method name.
3.5.A.2. A non-void method returns a single value. Its header includes the return type in place of the keyword void.
3.5.A.3. In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value.
3.5.A.4. The return keyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed. Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor.
Void and non-void methods
A void method does not return a value. Its header contains the keyword void before the method name.
A non-void method returns a single value. Its header includes the return type in place of the keyword void.
public void spend(int amount) // void: does something, returns nothing
public int getCash() // non-void: returns an int
public boolean trySpend(int amount) // non-void: returns a boolean
In a non-void method, a return expression compatible with the return type is evaluated, and the value is returned. This is return by value: the caller receives the value, not a link to anything in the object.
The return statement
The return keyword is used to return the flow of control to the point where the method or constructor was called.
Any code that is sequentially after a return statement will never be executed.
Executing a return inside a selection or iteration statement halts that statement and exits the method or constructor.
That second rule gives a very common pattern: an early return from inside a loop or an if.
public class Wallet {
private int cash;
public Wallet(int start) {
cash = start;
}
public int getCash() {
return cash;
}
public void spend(int amount) {
cash -= amount;
}
public boolean trySpend(int amount) {
if (amount > cash) {
return false;
}
cash -= amount;
return true;
}
public int daysLeft(int perDay) {
return cash / perDay;
}
}
Wallet w = new Wallet(20);
System.out.println(w.trySpend(5));
System.out.println(w.trySpend(50));
System.out.println(w.getCash());
System.out.println(w.daysLeft(4));
true
false
15
3
trySpend(5) passes the test, subtracts, and returns true. trySpend(50) fails the test and returns false immediately, so the line cash -= amount; never runs. Callers use the returned value to learn what happened.
A non-void method must return a value on every path through the code, or the compiler rejects it. Code placed after a return is a compile-time error because it can never execute.
public class Main {
public static int five() {
return 5;
System.out.println("done");
}
public static void main(String[] args) {
System.out.println(five());
}
}
As soon as a divisor is found, return d leaves both the if and the loop, and the method ends: it does not keep looking. If the loop finishes with no divisor, the number is prime and the final return n runs. Without that last return the method would not compile, because the loop might finish.
Worked example · void against non-void
A caller reacts to each kind differently.
public static void shout(String s) {
System.out.println(s + "!");
}
public static String twice(String s) {
return s + s;
}
shout("hey");
String t = twice("ha");
System.out.println(t);
shout(twice("ok"));
hey!
haha
okok!
shout is void, so it is called as a statement by itself and cannot be assigned to anything. twice is non-void, so its result is stored, printed, or passed on to another method.
Worked example · which return runs
Trace each call.
public static String grade(int score) {
if (score >= 90) {
return "A";
}
if (score >= 80) {
return "B";
}
return "C";
}
No else is needed: a return already ends the method, so anything after an if that returns is reached only when the condition was false.
Exam focus
Expect to write or complete a method from a specification, and to trace calls that return from inside an if or a loop. Check the return type against what you return, make sure every path returns a value, and note that a return ends the method at once, so nothing after it runs. Void methods return nothing and are called as statements. A method that returns a value that the caller ignores has no effect on the caller.
Practice
What is printed?
public static int mystery(int n) {
if (n > 5) {
return 1;
}
return 2;
}
System.out.println(mystery(9) + mystery(3));
Show answer
3. mystery(9) returns 1 and mystery(3) returns 2, and the sum of the two returned values is 3.
Why does this method not compile?
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n < 0) {
return -1;
}
}
Show answer
When n is 0 neither condition is true and no return runs, so the method has a path with no return value. Add return 0; as the last statement, or turn the last test into an else.
Write a method contains that returns true if the String s contains the letter ch (one character), and false otherwise.
public static boolean contains(String s, String ch) {
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals(ch)) {
return true;
}
}
return false;
}
16 and then 104. For 8, y is 16, the if returns it, and y += 100; never runs. For 2, y is 4, the if is skipped, and the method returns 104.
What is the difference between return; in a void method and return 5; in an int method?
Show answer
In a void method, return; ends the method without giving a value back. In an int method, return 5; evaluates the expression, ends the method, and gives that int value to the caller. A void method may not return a value, and a non-void method must.
The call w.getCash(); appears alone on a line. Is that an error, and is it useful?
Show answer
It is not an error: the call compiles and runs, and the returned value is discarded. It is useless, because the method has no effect other than returning a value, and nothing was done with it.
Private instance variables raise a question: if outside code cannot touch them, how does it ever learn what they hold, or change them? The answer is two families of public methods: accessors, which report, and mutators, which change. This lesson also nails down what happens to an argument when a method changes its parameter, a source of wrong answers every year.
Required content · LO 3.5.A
Learning objective.
3.5.A. Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.
Essential knowledge.
3.5.A.5. An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method.
3.5.A.6. A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method.
3.5.A.7. Methods with parameters receive values through those parameters and use those values in accomplishing the method’s task.
3.5.A.8. When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.
Accessors
An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method. It does not change the object.
public int getScore() {
return score;
}
An accessor does not have to return a stored variable as is. It can compute something from the object's state, as long as it only reports.
Mutators
A mutator (or modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method. Because it is public code, a mutator can also check its argument before changing anything, which a direct assignment to a public variable could never do.
public void addPoints(int pts) {
if (pts > 0) {
score += pts;
}
}
Parameters
Methods with parameters receive values through those parameters and use those values in accomplishing the method's task. When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.
public class Player {
private String name;
private int score;
public Player(String playerName) {
name = playerName;
score = 0;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void addPoints(int pts) {
if (pts > 0) {
score += pts;
}
}
public void reset() {
score = 0;
}
public void setName(String newName) {
name = newName;
}
public boolean isLeading(int target) {
return score > target;
}
public void bump(int amount) {
amount = amount * 2;
score += amount;
}
}
Player p = new Player("Ana");
p.addPoints(10);
p.addPoints(-4);
int boost = 3;
p.bump(boost);
System.out.println(p.getName() + " " + p.getScore() + " " + boost);
p.reset();
p.setName("Ben");
System.out.println(p.getName() + " " + p.getScore() + " " + p.isLeading(0));
Ana 16 3
Ben 0 false
Statement
score
Note
construction
0
p.addPoints(10)
10
mutator, argument accepted
p.addPoints(-4)
10
mutator refuses a nonpositive amount
p.bump(boost)
16
amount is a copy of 3, doubled to 6, added to score
reset()
0
mutator
Inside bump, the statement amount = amount * 2 changed only the parameter. The caller's boost is still 3, because the parameter was initialized with a copy of the argument.
Worked example · classify the methods
For the Player class, say what each method is and what it can change.
Method
Kind
Changes the object?
getName()
accessor
no
getScore()
accessor
no
addPoints(int)
mutator, void
yes, score
reset()
mutator, void
yes, score
setName(String)
mutator, void
yes, name
isLeading(int)
accessor (it computes from score)
no
bump(int)
mutator, void
yes, score; the parameter copy changes too, which is invisible to the caller
An accessor is non-void because it must give something back. A mutator is usually void, because its job is the change.
Worked example · a primitive parameter is a copy
Does the caller's variable change?
public class Doubler {
public int doubleIt(int n) {
n = n * 2;
return n;
}
public void tryToChange(int n) {
n = 99;
}
}
Doubler d = new Doubler();
int x = 4;
int y = d.doubleIt(x);
d.tryToChange(x);
System.out.println(x + " " + y);
4 8
doubleIt modified its own copy and returned it; the caller got the answer through the return value, not through the parameter. tryToChange changed a copy that was thrown away. The only way a method gives a primitive result back is return.
Worked example · writing an accessor and a mutator with a check
Write a class Thermostat whose temperature starts at 65 and can be set only between 50 and 90.
public class Thermostat {
private int temp;
public Thermostat() {
temp = 65;
}
public int getTemp() {
return temp;
}
public void setTemp(int t) {
if (t >= 50 && t <= 90) {
temp = t;
}
}
}
Thermostat th = new Thermostat();
th.setTemp(72);
th.setTemp(120);
th.setTemp(49);
System.out.println(th.getTemp());
72
Only the first call passes the check. The mutator protects the object from an illegal state, which is possible because the instance variable is private and every change must go through this method.
Exam focus
Expect questions that ask you to write an accessor or mutator for a given instance variable, to decide whether a method is an accessor or a mutator, and to trace a method that modifies its parameter (the argument is unchanged when it is a primitive). An accessor returns a value and does not change the object. A mutator changes instance variables and is often void. The return value is the only way for a method to hand back a primitive result.
Practice
Write an accessor for private int level; and a mutator that raises the level by 1.
public class Game {
private int level = 1;
public int getLevel() {
return level;
}
public void levelUp() {
level++;
}
}
Game g = new Game();
g.levelUp();
g.levelUp();
System.out.println(g.getLevel());
Show answer
public int getLevel() { return level; } is the accessor, and public void levelUp() { level++; } is the mutator. After two calls the level is 3.
What is printed?
public class Box {
private int size;
public Box(int s) {
size = s;
}
public void grow(int by) {
by = by + 1;
size += by;
}
public int getSize() {
return size;
}
}
Box b = new Box(10);
int n = 5;
b.grow(n);
System.out.println(b.getSize() + " " + n);
Show answer
16 5. The parameter by is a copy of 5, increased to 6, and added to size (10 + 6). The caller's n is unchanged.
Is getTemp() an accessor or a mutator? How can you tell?
Show answer
An accessor: it is non-void, it returns the value of an instance variable, and it does not change the object.
Why is a mutator such as setTemp better than making temp public?
Show answer
A mutator can check its argument and refuse a bad value, so the object cannot be put into an illegal state. A public variable could be assigned any value by any code.
A method void swapTo(int a, int b) is meant to swap two caller variables. Will it work?
public class Swapper {
public void swapTo(int a, int b) {
int t = a;
a = b;
b = t;
}
}
Swapper s = new Swapper();
int p = 1;
int q = 2;
s.swapTo(p, q);
System.out.println(p + " " + q);
Show answer
No. The parameters a and b are copies of the arguments. Swapping the copies leaves p and q unchanged, so the output is 1 2.
Which method would you add to Player to report whether the player's score is at least n?
A. public void atLeast(int n) { score >= n; }
B. public boolean atLeast(int n) { return score >= n; }
C. public int atLeast(int n) { return score >= n; }
D. public boolean atLeast() { return score >= n; }
Show answer
B. It reports a Boolean answer, so it is an accessor that returns boolean and takes the number as a parameter. A is not a valid statement, C returns the wrong type, and D uses n without declaring it as a parameter.
Lesson 3.5b showed that a method cannot change a caller's int, because it works on a copy. People then assume the same is true for objects, and they are half right, which is the dangerous kind of right. This lesson is about what a parameter really is when the argument is an object, what a method can and cannot do to it, and why a method that returns an object hands over the object itself and not a duplicate.
Required content · LO 3.6.A
Learning objective.
3.6.A. Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.
Essential knowledge.
3.6.A.1. When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
3.6.A.2. When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
3.6.A.3. Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method’s enclosing class.
Parameters that are object references
When an argument is an object reference, the parameter is initialized with a copy of that reference. It does not create a new independent copy of the object. Two consequences follow, and they pull in opposite directions.
The parameter and the caller's variable now refer to the same object. If the object is mutable, the method or constructor can use the reference to alter the state of the object, and the caller sees the change.
The parameter itself is still a copy. If the method assigns a new object to the parameter, only the copy of the reference changes; the caller's variable still refers to the original.
Figure 3.2. Left: x and the parameter b refer to one Box, so a mutator called through b changes what x sees. Right: assigning a new Box to b moves only b's arrow; x still refers to the original.
It is good programming practice not to modify mutable objects that are passed as parameters unless the specification requires it.
public class Box {
private int size;
public Box(int s) {
size = s;
}
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;
}
public boolean sameSize(Box other) {
return size == other.size;
}
}
public static void doubleSize(Box b) {
b.setSize(b.getSize() * 2);
}
public static void replace(Box b) {
b = new Box(99);
}
Box x = new Box(4);
doubleSize(x);
System.out.println(x.getSize());
replace(x);
System.out.println(x.getSize());
8
8
doubleSize followed the reference and changed the object itself, so x shows 8. replace pointed its own copy of the reference at a new Box; the caller's x still refers to the old one, so it still shows 8. Changing what the object holds is visible to the caller; changing which object the parameter refers to is not.
Returning references
When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. The caller and the method now share the object.
public static Box bigger(Box a, Box c) {
if (a.getSize() >= c.getSize()) {
return a;
}
return c;
}
Box p = new Box(8);
Box q = new Box(20);
Box big = bigger(p, q);
System.out.println(big == q);
big.setSize(1);
System.out.println(q.getSize());
true
1
big is another name for q: the method returned the very object, so changing it through big changes q.
### The risk of an accessor that returns a mutable object
An accessor that returns a reference to a private mutable object gives every caller a handle on the class's own data.
public class Point {
private int x;
private int y;
public Point(int px, int py) {
x = px;
y = py;
}
public int getX() {
return x;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
}
public class Marker {
private Point spot;
public Marker(int px, int py) {
spot = new Point(px, py);
}
public Point getSpot() {
return spot;
}
public int getX() {
return spot.getX();
}
}
Marker m = new Marker(2, 2);
Point p = m.getSpot();
p.move(10, 0);
System.out.println(m.getX());
12
The marker's spot is private, yet the caller moved it, because getSpot returned the reference and not a copy. A class that must protect its state returns a copy, or returns only the primitive values (as getX does).
Access to private data of a parameter
Methods cannot access the private data and methods of a parameter that holds a reference to an object, unless the parameter is the same type as the method's enclosing class.Box.sameSize(Box other) may read other.size because both objects are Box objects, and the code is inside the Box class. A method in a different class may not.
public class Gauge {
public boolean isSmall(Box other) {
return other.size < 5;
}
}
Main.java:3: error: size has private access in Box
Worked example · what the method can and cannot change
Trace each statement.
Box a = new Box(3);
Box b = new Box(5);
doubleSize(a);
replace(b);
System.out.println(a.getSize() + " " + b.getSize());
System.out.println(a.sameSize(b));
6 5
false
Statement
a object
b object
construction
size 3
size 5
doubleSize(a)
size 6 (the object was changed)
size 5
replace(b)
size 6
size 5 (only the parameter's reference changed)
sameSize compares 6 with 5, so it is false.
Worked example · two names for one object
Predict the output.
Box first = new Box(10);
Box second = first;
Box third = bigger(first, new Box(2));
third.setSize(third.getSize() + 5);
System.out.println(first.getSize() + " " + second.getSize() + " " + third.getSize());
15 15 15
second is an alias of first. bigger returns its first argument (10 is at least 2), so third is another name for the same object. There is only one object that matters, and its size became 15.
Worked example · protecting a class's data
What is the difference between these two accessors?
public class Pair {
private Point first;
public Pair(int x, int y) {
first = new Point(x, y);
}
public Point leaky() {
return first;
}
public Point safe() {
return new Point(first.getX(), 0);
}
public int firstX() {
return first.getX();
}
}
leaky() returned the stored object, so the move changed the pair's state. safe() built a new Point, so moving it by 100 changed nothing the pair owns. Returning a copy keeps control of the data inside the class.
Exam focus
Expect to trace methods that take object parameters, deciding whether the caller's object changes. Follow one rule: a method that calls a mutator on the parameter changes the shared object; a method that merely assigns a new object to the parameter changes nothing outside. For returns, the caller gets the original object unless the method creates a copy. Remember the private-access exception: a method may reach into the private data of a parameter only when the parameter is of the same type as the class the method is in.
Practice
What is printed?
public static void change(Box b) {
b.setSize(50);
}
Box k = new Box(1);
change(k);
System.out.println(k.getSize());
Show answer
50. b holds a copy of the reference to the same Box, so the mutator changed the object that k also refers to.
What is printed?
public static void reset(Box b) {
b = new Box(0);
}
Box k = new Box(7);
reset(k);
System.out.println(k.getSize());
Show answer
7. The assignment b = new Box(0) moved only the parameter's copy of the reference. The caller's k still refers to the original object.
What is printed?
Box m = new Box(3);
Box n = bigger(m, new Box(3));
System.out.println(n == m);
Show answer
true. When the sizes are equal, bigger returns its first argument, and the method returns the reference itself, so n and m refer to the same object.
Why does this method in a class Gauge fail to compile, while the same line inside Box would work?
public boolean isSmall(Box other) {
return other.size < 5;
}
Show answer
size is private in Box. A method may read the private data of a parameter only if the parameter is the same type as the method's own class. Gauge is a different class, so it must call a public accessor such as other.getSize().
A class stores a Point and has the accessor public Point getPoint() { return p; }. What can a caller do that the class author may not have wanted?
Show answer
The accessor returns the stored reference, so a caller can call a mutator such as move on it and change the object's private state. Returning a copy of the Point, or only its coordinates, prevents this.
True or false: if a method receives an int parameter and an object parameter, changes to both are visible to the caller.
Show answer
False. The int parameter is a copy of the value, so changing it is invisible. Changes made to the object's state through the object parameter are visible, because the parameter is a copy of the reference to the same object.
Instance variables belong to objects: ten tickets, ten seat numbers. Some facts belong to the whole class instead: how many tickets have been sold, what a ticket costs. Java marks those with the keyword static. This lesson covers the variables and methods that are shared by every object, and the restrictions that follow from the fact that a class method has no particular object.
Required content · LO 3.7.A, LO 3.7.B
Learning objectives.
3.7.A. Develop code to define behaviors of a class through class methods.
3.7.B. Develop code to declare the class variables that belong to the class.
Essential knowledge.
3.7.A.1. Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
3.7.A.2. Class methods can access or change the values of class variables and can call other class methods.
3.7.B.1. Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
3.7.B.2. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
3.7.B.3. When a variable is declared final, its value cannot be modified.
Class variables
Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. A class variable is designated with the keyword static before the variable type. A public class variable is accessed from outside the class using the class name and the dot operator, since it is associated with a class, not with the objects of the class.
When a variable is declared final, its value cannot be modified. A class constant is typically public static final, written in capital letters.
public class Ticket {
public static final int PRICE = 12;
private static int sold = 0;
private int seat;
public Ticket() {
sold++;
seat = sold;
}
public int getSeat() {
return seat;
}
public static int getSold() {
return sold;
}
public static int revenue() {
return sold * PRICE;
}
public static int seatTotal(Ticket a, Ticket b) {
return a.getSeat() + b.getSeat();
}
}
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
Ticket t3 = new Ticket();
System.out.println(Ticket.getSold());
System.out.println(t3.getSeat());
System.out.println(Ticket.revenue());
System.out.println(Ticket.PRICE);
System.out.println(Ticket.seatTotal(t1, t2));
3
3
36
12
3
sold is one variable shared by all three tickets, and each constructor call adds one to it. seat is an instance variable, so each ticket has its own: 1, 2, and 3.
Kind of variable
Declared with
Copies
Accessed with
instance variable
no static
one per object
an object (inside its class, directly)
class variable
static
one for the whole class
the class name (inside the class, directly)
constant
static final
one, unchangeable
the class name
Class methods
A class method (with static in its header) belongs to the class and is called with the class name. Because it is not running on behalf of any particular object, it has restrictions.
Class methods can access or change the values of class variables, and can call other class methods.
Class methods cannot access or change the values of instance variables, or call instance methods, unless they are passed an instance of the class via a parameter.
Ticket.seatTotal(a, b) works because the two tickets arrive as parameters and the method calls getSeat() on them. Ticket.getSold() works because sold is a class variable.
public class Gate {
private int open = 3;
public static int getOpen() {
return open;
}
}
Main.java:5: error: non-static variable open cannot be referenced from a static context
The method getOpen is static and has no object, so there is no open for it to read.
Worked example · a shared counter and private numbers
Two classes from the same blueprint, in different orders of creation.
Ticket a = new Ticket();
Ticket b = new Ticket();
System.out.println(a.getSeat() + " " + b.getSeat() + " " + Ticket.getSold());
Ticket c = new Ticket();
System.out.println(a.getSeat() + " " + c.getSeat() + " " + Ticket.getSold());
1 2 2
1 3 3
After
a.seat
b.seat
c.seat
sold (shared)
two tickets
1
2
2
third ticket
1
2
3
3
The first ticket's seat stays 1 forever, while sold keeps counting. Every object sees the same sold; each object sees its own seat.
Worked example · constants cannot change
What does the compiler do with an attempt to change PRICE?
Ticket.PRICE = 15;
Main.java:2: error: cannot assign a value to static final variable PRICE
A final variable is assigned once. Because PRICE is static as well as final, there is exactly one copy, shared by every ticket, and it can never be changed. Using a named constant instead of the number 12 also means that a price change is made in one place.
Worked example · which of these is legal inside a class method?
Inside public static int mystery() of the Ticket class, decide each statement.
Statement
Legal?
Why
return sold;
yes
sold is a class variable
return seat;
no
seat is an instance variable, and no object was passed in
return getSold() + 1;
yes
calls another class method
return getSeat();
no
calls an instance method with no object
Ticket t = new Ticket(); return t.getSeat();
yes
now there is an object to call the instance method on
return PRICE * 2;
yes
a class constant
A class method may work with any object it creates or receives, and it may use anything that belongs to the class. What it may not do is use "the current object", because there isn't one.
Exam focus
Expect questions that ask for the value of a class variable after several objects have been created, and questions that ask whether a statement in a static method compiles. The test for compiling is simple: does the statement use an instance variable or an instance method without an object? Remember that all objects share a class variable, that a final variable cannot be reassigned, and that a public class variable is reached through the class name.
Practice
What is printed?
public class Counter {
private static int total = 0;
private int mine = 0;
public void hit() {
total++;
mine++;
}
public int getMine() {
return mine;
}
public static int getTotal() {
return total;
}
}
Counter a = new Counter();
Counter b = new Counter();
a.hit();
a.hit();
b.hit();
System.out.println(a.getMine() + " " + b.getMine() + " " + Counter.getTotal());
Show answer
2 1 3. mine is separate for each object (2 and 1), and total is shared (3 hits in all).
Which keyword makes a variable shared by all objects of a class, and which prevents it from being changed?
Show answer
static makes the variable a class variable, shared by all objects, and final prevents it from being modified after it is assigned.
Why does this method not compile?
public class Cup {
private int ounces;
public static void fill() {
ounces = 8;
}
}
Show answer
fill is a class method, so there is no particular Cup object, and a class method cannot access or change an instance variable. ounces belongs to individual objects.
A class has public static final double RATE = 0.5;. How should code in another class refer to it, and may that code assign to it?
Show answer
Use the class name with the dot operator, for example Loan.RATE. It may not assign to it, because the variable is final.
What is printed?
public class Id {
private static int next = 100;
private int id;
public Id() {
id = next;
next++;
}
public int getId() {
return id;
}
}
Id i1 = new Id();
Id i2 = new Id();
System.out.println(i1.getId() + " " + i2.getId());
Show answer
100 101. Each object copies the shared counter into its own id and then increases the counter, so every object gets a unique number.
True or false: a class method can call an instance method if it is passed an object of the class as a parameter.
Show answer
True. A class method can call instance methods and read instance variables of an object that it has been given, through a parameter or by creating the object. It cannot use them without an object.
Where is a variable visible? The answer is not "everywhere after it is declared." Java confines each variable to a region of the code, and using a name outside its region is a compile-time error. Worse, a name can be quietly reused, so that a local variable hides an instance variable with the same name, and a constructor looks right while doing nothing. This lesson draws the boundaries and shows the one bug that comes from them every year.
Required content · LO 3.8.A
Learning objective.
3.8.A. Explain where variables can be used in the code.
Essential knowledge.
3.8.A.1. Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
3.8.A.2. When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.
Local variables and blocks
Local variables are variables declared in the headers or bodies of blocks of code. A local variable can only be accessed in the block in which it is declared. A block is any section of code enclosed in braces: a method body, an if body, a loop body. Since constructors and methods are blocks of code, the parameters to a constructor or method are also local variables.
These variables may only be used within the constructor or method, and cannot be declared public or private: access modifiers belong to instance variables and class variables, never to locals.
public class Main {
public static void main(String[] args) {
int total = 0;
if (total == 0) {
int bonus = 5;
total += bonus;
}
System.out.println(bonus);
}
}
Main.java:8: error: cannot find symbol
System.out.println(bonus);
^
symbol: variable bonus
location: class Main
1 error
bonus lives only inside the braces of the if. After the closing brace it no longer exists. A variable declared in a for header lives only inside that loop.
Kind of variable
Declared
Visible
instance variable
in the class, outside any method
in every method and constructor of the class
class variable (static)
in the class, outside any method
in the whole class
parameter
in a method or constructor header
only in that method or constructor
local variable
inside a block
only in that block, after its declaration
Hiding: a local with the same name as an instance variable
When there is a local variable or parameter with the same name as an instance variable, the name refers to the local variable or parameter in the body of the constructor or method. The instance variable is hidden there.
public class Probe {
private int x = 5;
public int a(int x) {
return x * 2;
}
public int b() {
int x = 100;
return x + 1;
}
public int c() {
return x + 1;
}
}
Probe p = new Probe();
System.out.println(p.a(10) + " " + p.b() + " " + p.c());
20 101 6
In a, the parameter x (10) hides the instance variable. In b, the local x (100) hides it. Only c has no local of that name, so x there is the instance variable, 5.
### The classic bug
Naming a constructor parameter the same as an instance variable is natural and legal, and it is a trap.
public class Score {
private int points;
public Score(int points) {
points = points;
}
public int getPoints() {
return points;
}
}
Score s = new Score(7);
System.out.println(s.getPoints());
0
Inside the constructor, both points names mean the parameter, so the statement assigns the parameter to itself, and the instance variable keeps its default value 0. No error is reported. Lesson 3.9 shows how to refer to the instance variable explicitly. Until then the safe habit is to give the parameter a different name, such as startPoints.
Worked example · where is each name visible?
Decide what each line of this class refers to.
public class Demo {
private int count = 1;
public int run(int n) {
int total = 0;
for (int i = 0; i < n; i++) {
int step = i + count;
total += step;
}
return total;
}
}
Demo d = new Demo();
System.out.println(d.run(3));
6
Name
Kind
Where it can be used
count
instance variable
anywhere in Demo's methods
n
parameter
all of run
total
local
from its declaration to the end of run
i
local to the for header
only inside the loop
step
local to the loop body
only inside the loop body, one pass at a time
The loop adds 1, 2, and 3 (each i + count), and the total is 6. Writing return step; after the loop would not compile.
Worked example · fixing the shadowing bug
The constructor below was written to store the amount, and it does not. Fix it with a different parameter name.
public class Account {
private int balance;
public Account(int startBalance) {
balance = startBalance;
}
public int getBalance() {
return balance;
}
}
With distinct names, balance in the constructor is the instance variable and startBalance is the parameter. The assignment now copies the argument into the object.
Worked example · a local variable cannot have an access modifier
Why does this fail?
public class Main {
public static void main(String[] args) {
private int n = 3;
}
}
Main.java:3: error: illegal start of expression
private int n = 3;
^
Main.java:5: error: class, interface, enum, or record expected
}
^
2 errors
The second message is a side effect: after the first error the compiler loses track of the braces, so only the first message points at the real mistake. public and private apply to the members of a class: instance variables, class variables, constructors, and methods. A variable declared inside a method is local, with its scope fixed by the block, and it cannot be given an access modifier.
Exam focus
Expect a question that asks which statement uses a variable outside its scope, which variable a name refers to when there is a local or parameter with the same name as an instance variable, and what the constructor above actually stores. The rule is that the nearest declaration wins: a local or parameter hides an instance variable of the same name. Locals live only in their block, and parameters count as locals.
Practice
What is printed?
public class Tank {
private int level = 40;
public int a(int level) {
return level + 1;
}
public int b() {
return level + 1;
}
}
Tank t = new Tank();
System.out.println(t.a(10) + " " + t.b());
Show answer
11 41. In a, level is the parameter (10). In b, no local has that name, so level is the instance variable (40).
Why does this code not compile?
for (int i = 0; i < 3; i++) {
int sq = i * i;
}
System.out.println(sq);
Show answer
sq was declared inside the loop body, so it exists only there. After the closing brace, the name is out of scope and the compiler reports that it cannot find the symbol.
A constructor is public Dial(int level) { level = level; }. After new Dial(8), what does the instance variable level hold?
public class Dial {
private int level;
public Dial(int level) {
level = level;
}
public int getLevel() {
return level;
}
}
System.out.println(new Dial(8).getLevel());
Show answer
0, the default for an int. Both names in the assignment refer to the parameter, so the instance variable is never assigned. The fix is a different parameter name, or this.level = level; (Lesson 3.9).
In which part of the code is a method's parameter visible?
Show answer
Only inside that method (or constructor). Parameters are local variables, so their scope is the body of the method.
Can the same local variable name be declared in two separate loops one after the other?
for (int i = 0; i < 2; i++) {
System.out.print(i);
}
for (int i = 0; i < 3; i++) {
System.out.print(i);
}
Show answer
Yes. Each i exists only inside its own loop, so the two declarations do not overlap. The output is 01 followed by 012.
What is wrong with writing public int count = 0; inside a method body?
Show answer
A local variable cannot be declared public or private. Access modifiers belong to instance and class variables, constructors, and methods.
In the last lesson a parameter named points hid the instance variable named points, and the constructor silently stored nothing. What was missing was a way to say the instance variable of this very object. Java has one: the keyword this. It also solves a second problem, handing "myself" to another method.
Required content · LO 3.9.A
Learning objective.
3.9.A. Develop code for expressions that are self-referencing and determine the result of these expressions.
Essential knowledge.
3.9.A.1. Within an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object— the object whose method or constructor is being called.
3.9.A.2. The keyword this can be used to pass the current object as an argument in a method call.
3.9.A.3. Class methods do not have a this reference.
What this is
Within an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object, the object whose method or constructor is being called. If ada.greet() is running, this is ada; if the next call is ben.greet(), this is ben.
### Reaching a hidden instance variable
this.name is always the instance variable called name, even when a parameter or local with the same name hides the plain name. That is why programmers can give constructor parameters the same names as the instance variables.
public class Score {
private int points;
public Score(int points) {
this.points = points;
}
public int getPoints() {
return points;
}
}
System.out.println(new Score(7).getPoints());
7
In this.points = points, the left side is the object's instance variable and the right side is the parameter. The bug from Lesson 3.8 is gone.
### Passing the current object
The keyword this can be used to pass the current object as an argument in a method call. A method can hand itself to another object.
public class Team {
private int members = 0;
private String last = "none";
public void add(Player p) {
members++;
last = p.getName();
}
public int getMembers() {
return members;
}
public String getLast() {
return last;
}
}
public class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void join(Team t) {
t.add(this);
}
public boolean beats(Player other) {
return this.score > other.score;
}
public boolean isSame(Player other) {
return this == other;
}
}
Team squad = new Team();
Player ada = new Player("Ada", 90);
Player ben = new Player("Ben", 70);
ada.join(squad);
ben.join(squad);
System.out.println(squad.getMembers() + " " + squad.getLast());
System.out.println(ada.beats(ben) + " " + ben.beats(ada));
System.out.println(ada.isSame(ada) + " " + ada.isSame(ben));
2 Ben
true false
true false
When ada.join(squad) runs, this is ada, so t.add(this) hands the team ada herself. In ada.beats(ben) the method compares this.score (Ada's) with other.score (Ben's); reading other.score is allowed because other has the same type as the class (Lesson 3.6). In isSame, this == other asks whether the two references are the very same object.
Class methods have no this
Class methods do not have a this reference, because a class method is called on the class, not on an object.
public class Gauge {
private int level = 2;
public static int broken() {
return this.level;
}
}
Main.java:5: error: non-static variable this cannot be referenced from a static context
Worked example · fixing the constructor with this
The class below has the shadowing bug. Rewrite the constructor with this and show the difference.
public class Box {
private int width;
private int height;
public Box(int width, int height) {
this.width = width;
this.height = height;
}
public int area() {
return width * height;
}
}
Box b = new Box(3, 4);
System.out.println(b.area());
12
Expression in the constructor
Means
this.width
the instance variable
width (alone)
the parameter
With the plain width = width; of Lesson 3.8 the area would be 0, because neither instance variable would be set.
Worked example · comparing this with another object
A Card is "higher" than another card if its rank is greater.
public class Card {
private int rank;
public Card(int rank) {
this.rank = rank;
}
public boolean higherThan(Card other) {
return this.rank > other.rank;
}
public boolean sameCardAs(Card other) {
return this == other;
}
}
Card queen = new Card(12);
Card king = new Card(13);
Card alsoQueen = new Card(12);
Card again = queen;
System.out.println(king.higherThan(queen));
System.out.println(queen.higherThan(alsoQueen));
System.out.println(queen.sameCardAs(alsoQueen));
System.out.println(queen.sameCardAs(again));
true
false
false
true
king.higherThan(queen) compares 13 with 12. queen and alsoQueen have the same rank but are different objects, so sameCardAs is false; again is another name for queen, so it is true.
Worked example · an object that registers itself
A Light adds itself to a Panel when it is created, and the Panel counts how many it knows.
public class Panel {
private int count = 0;
public void register(Light l) {
count++;
}
public int getCount() {
return count;
}
}
public class Light {
public Light(Panel p) {
p.register(this);
}
}
Panel panel = new Panel();
Light l1 = new Light(panel);
Light l2 = new Light(panel);
System.out.println(panel.getCount());
2
Inside the Light constructor, this is the light being built. Passing it to register lets the panel hold a reference to each light. Notice that the constructor can pass this before it has finished its other work; for a simple class like this one there is none.
Exam focus
Expect to read a constructor or method and decide what this refers to, what this.x = x assigns, and whether a statement that uses this compiles. Remember: this is the current object, this.name reaches an instance variable hidden by a parameter, this can be an argument, and class methods have none. Questions about references combine this with the rules of Lesson 3.6: within the class, a method may read the private data of another object of the same class.
Practice
What is stored in the instance variable size after new Cube(5)?
public class Cube {
private int size;
public Cube(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
System.out.println(new Cube(5).getSize());
Show answer
5. this.size is the instance variable, and size on the right is the parameter, so the argument is copied into the object.
What does this refer to when x.show() is running?
Show answer
this refers to the object x, the current object whose method is being called. A call y.show() would make this refer to y.
Why does this method not compile?
public static int twice() {
return this.value * 2;
}
Show answer
The method is static, so it belongs to the class and no current object exists. Class methods do not have a this reference.
Write a method isOlderThan(Person other) for a class with a private int age, using this.
public class Person {
private int age;
public Person(int age) {
this.age = age;
}
public boolean isOlderThan(Person other) {
return this.age > other.age;
}
}
Person a = new Person(30);
Person b = new Person(25);
System.out.println(a.isOlderThan(b) + " " + b.isOlderThan(a));
Show answer
return this.age > other.age;. Both age variables can be read, because other has the same type as the enclosing class. The call a.isOlderThan(b) is true because 30 is greater than 25.
What is printed?
public class Echo {
public Echo me() {
return this;
}
}
Echo e = new Echo();
Echo f = e.me();
System.out.println(e == f);
Show answer
true. The method returns this, which is the reference to the very object it was called on, so f and e refer to the same object.
What is the difference between this.balance = balance; and balance = balance; in a constructor whose parameter is named balance?
Show answer
this.balance = balance; copies the parameter into the instance variable. balance = balance; assigns the parameter to itself, because the parameter hides the instance variable, so the instance variable keeps its default value.
Unit 3 review · 10 multiple-choice
Unit 3 review: Class Creation
Ten exam-style questions on a code stimulus, running from class design and
constructors through references, static members, scope and this to
mutators and shadowing: click an option to see why it is right or wrong, and read the stimulus
line by line before you choose.
Multiple choice
public class Student {
private String name;
private int points;
public Student(String startName) {
name = startName;
points = 0;
}
public int getPoints() {
return points;
}
public void addPoints(int earned) {
int capped = earned;
if (capped > 10) {
capped = 10;
}
points = points + capped;
}
}
// inside main, in a different class
Student s = new Student("Ana");
s.addPoints(7);
s.addPoints(25);
s.points = 40;
System.out.println(s.getPoints());
What is the result of compiling and running the code segment in main?
17 is what this segment would print with the fourth line deleted:
addPoints(7) adds 7, and addPoints(25) is pulled down to 10 by
the local variable capped, so the field holds 7 + 10. Nothing runs, though,
because the program is rejected before it is ever executed.
40 assumes s.points = 40; is a legal statement. It is not:
points is declared private, so only code written inside
Student may name it, and main lives in another class.
32 is 7 + 25, the total you would get if addPoints stored
earned directly. It does not, the cap is enforced through
capped, and in any case the segment never compiles.
Correct. javac reports
error: points has private access in Student and stops. That is exactly what
private buys you: the cap inside addPoints is the only way
points can ever enter the object, so no caller can leave it in a state the class
forbids.
public class Locker {
private int number;
private boolean assigned;
public Locker(int startNumber) {
number = startNumber;
assigned = false;
}
public int getNumber() {
return number;
}
}
Which of the following statements, placed in main, causes a compile-time error?
This matches the only constructor the class has, one int
argument, so it compiles and builds a locker numbered 214. The constructor's name and
parameter list are the whole contract.
Creating an array of objects runs no constructor at all. It makes three
slots holding null, which compiles cleanly; the error would come later, at
run time, if you called a method through one of those null slots.
Correct. Java supplies a free no-argument constructor only to a class that
declares no constructor whatsoever. Locker declares one, so the free one is
gone and javac answers constructor Locker in class Locker cannot be
applied to given types; required: int, found: no arguments.
Zero is an ordinary int argument, so this compiles and stores
0 in number. A value being unusual is not the same as a value being
illegal: only a mutator or constructor that validates could reject it.
public class Thermostat {
private String room;
private int target;
public Thermostat(String startRoom, int startTarget) {
room = startRoom;
target = clamp(startTarget);
}
public int getTarget() {
return target;
}
public void setTarget(int degrees) {
target = clamp(degrees);
}
private int clamp(int degrees) {
if (degrees < 50) {
return 50;
}
if (degrees > 85) {
return 85;
}
return degrees;
}
}
Thermostat t = new Thermostat("Lab 2", 90);
System.out.print(t.getTarget() + " ");
t.setTarget(45);
System.out.print(t.getTarget() + " ");
t.setTarget(70);
System.out.println(t.getTarget());
What is printed as a result of executing the code segment?
Correct. The first value decides it: new Thermostat("Lab 2", 90)
passes 90 through clamp, which returns 85 because 90 is above the ceiling.
setTarget(45) is then pulled up to the floor of 50, and 70 is inside the
legal range so it is stored untouched.
This is the output of a class that stores whatever it is handed. Both the
constructor and the mutator call clamp, so 90 and 45 never reach the field
unchanged: that is the whole reason the field is private.
90 for the first value assumes the constructor assigns
startTarget directly. It does not: it calls the same helper the mutator
calls. Writing the rule once, in a private helper, is what keeps the two entry points
from drifting apart.
45 for the second value assumes the clamping happens only at construction.
setTarget also calls clamp, and 45 is below 50, so the field
becomes 50. A range stated in a specification applies at every door into the object.
public static void grow(Rectangle r, double factor) {
r.setWidth(r.getWidth() * factor);
}
public static void replace(Rectangle r) {
r = new Rectangle(1.0, 1.0);
}
public static void main(String[] args) {
Rectangle a = new Rectangle(3.0, 4.0);
Rectangle b = a;
grow(a, 2.0);
replace(a);
System.out.println(a.getWidth() + " " + b.getWidth());
}
What is printed as a result of executing main?
This treats b = a; as copying the rectangle. It copies the
reference, so a and b are two arrows pointing at one object,
and a change made through either arrow is visible through the other.
3.0 for both says grow could not reach the caller's object. It
could: r is a copy of the reference, and r.setWidth(...)
follows that reference to the very same rectangle a names.
Correct. The decisive call is grow, which sets the shared
object's width to 6.0 through the copied reference. replace then only
repoints its own parameter r at a new rectangle, and that arrow dies at the
closing brace, so both a and b still report 6.0.
1.0 assumes replace can change which object a
refers to. A method can change an object you hand it, but it can never change which
object your variable points at: assigning to a parameter moves only the method's own
arrow.
public class Ticket {
private static int nextId = 1000;
private int id;
private String holder;
public Ticket(String startHolder) {
holder = startHolder;
id = nextId;
nextId++;
}
public int getId() {
return id;
}
public static void resetIds() {
nextId = 1000;
}
}
Ticket a = new Ticket("Ana");
Ticket b = new Ticket("Bo");
Ticket.resetIds();
Ticket c = new Ticket("Cy");
System.out.println(a.getId() + " " + b.getId() + " " + c.getId());
What is printed as a result of executing the code segment?
This is the output with the resetIds() call deleted. The call
is there, and it assigns 1000 to the one shared counter, so the third ticket cannot
receive 1002.
All three equal would mean each object has its own copy of
nextId. It is declared static, so there is exactly one copy for
the whole class, and the first two tickets took different numbers out of it.
Correct. The third value is where the answer is decided:
resetIds() moved the shared counter back to 1000, so Cy's ticket takes 1000
again. It did nothing to Ana's ticket, whose id was copied out of the
counter two statements earlier and has been her own instance variable ever since.
These are the numbers you get if the constructor increments before it
assigns. It assigns first (id = nextId;) and then advances the counter, so
the first ticket issued gets the starting value 1000.
public class Profile {
public int longestGap(int[] days) { // line 2
for (int i = 1; i < days.length; i++) { // line 3
int best = 0; // line 4
int gap = days[i] - days[i - 1]; // line 5
if (gap > best) { // line 6
best = gap; // line 7
}
}
return best; // line 10
}
}
The method is intended to return the largest gap between consecutive values of
days, but the class does not compile. Which change makes it compile and work
as intended for every array of length at least 2?
Swapping > for >= changes only which of two
equal gaps wins, and the class still will not compile. The error is not about the
comparison at all.
Returning gap fails twice over: gap is also
declared inside the loop body, so it is out of scope at line 10, and even in scope it
would report the last gap rather than the largest one.
Seeding the running maximum with an element is sometimes the right habit,
but the declaration is still inside the loop, so it resets on every pass and is still out
of scope at line 10. The class does not compile either way.
Correct. javac says cannot find symbol: variable best
at line 10, because a local variable declared inside the loop body dies at that body's
closing brace. Declared above the loop, best is initialized once, survives
every pass, and is still in scope at the return, on {1, 3, 8, 9, 15} the
fixed method returns 6.
public class Label {
private String text;
public Label(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
text = text; // line 13
}
}
Label c = new Label("draft");
c.setText("FINAL");
System.out.println(c.getText()); // prints draft
Which of the following replacements for line 13 makes setText work
as intended, so that the segment prints FINAL?
Both sides now name the field, so the statement copies the field onto
itself and the parameter is never read. It compiles without a murmur and still prints
draft: assigning a variable to itself breaks no rule of Java.
Correct. Inside the method the bare name text means the
parameter, because a parameter shadows a field of the same name;
this.text always means the field of the object the method was called on. So
the left side is the field, the right side is the argument, and the run prints
FINAL.
This is the original bug pointed the other way: it copies the field into
the parameter, which is discarded when the method returns. The field is never written,
so the output stays draft.
Qualifying a field with the class name only works for a
static field, and text is an instance variable. This one does
not even compile: non-static variable text cannot be referenced from a static
context.
public class PunchPass {
private String owner;
private int punches;
private int freeRides;
public PunchPass(String owner) {
this.owner = owner;
punches = 0;
freeRides = 0;
}
public void buy() {
/* to be implemented */
}
public String getStatus() {
return owner + " " + punches + "/3, " + freeRides + " free";
}
}
One purchase adds one punch; every third punch becomes one free ride and the
punch count returns to zero. Which implementation of buy() makes getStatus()
return Maya 1/3, 2 free on a new pass after seven calls, and behave correctly for any number
of calls?
Correct. The fifth and the sixth calls decide it: the sixth call takes the
counter to 3, which awards the second free ride and resets the counter, so the seventh
call leaves exactly one punch on a pass holding two free rides;
Maya 1/3, 2 free.
The free-ride count is right, but the punch count is not: without
punches = 0; the counter keeps climbing, so after seven calls
getStatus() returns Maya 7/3, 2 free. The specification says the count returns to zero, and
getStatus makes the omission visible.
Nothing ever resets the counter, so from the third purchase onward
every call awards another free ride. After seven calls the status is
Maya 7/3, 5 free, and a pass advertising seven punches out of three is the
tell that the reset is missing.
Assigning freeRides = 1; instead of incrementing it throws
away every ride already earned, so the count can never exceed one. After seven calls the status is
Maya 1/3, 1 free, which is right on the punches and wrong on the rides.
public class Thermostat {
private int target;
public Thermostat(int target) {
this.target = target;
}
public void raise(int amount) {
target += amount;
}
public int getTarget() {
return target;
}
}
Thermostat a = new Thermostat(68);
Thermostat b = a;
b.raise(3);
Thermostat c = new Thermostat(a.getTarget());
c.raise(2);
System.out.println(a.getTarget() + " " + b.getTarget() + " " + c.getTarget());
What is printed when the code above is run?
This treats b as a separate thermostat, but
Thermostat b = a; copies the reference, not the object. There is one object
with two names, so raising it through b changes what a reports.
Correct. a and b refer to one object, which goes
from 68 to 71. c is a new object built from the value 71, and raising it
by 2 gives 73 without touching the first object.
This lets c share the first object too. But
new Thermostat(a.getTarget()) builds a second object that only started with
the same number; it holds its own target, so raising c leaves 71 behind.
This adds the 3 twice, once through each name. A second name for an object
is not a second copy of the object, so the 3 is added only once.
public class Counter {
private int count = 0;
public void add(int count) {
count = count + 1;
}
public int get() {
return count;
}
}
Counter k = new Counter();
k.add(5);
k.add(5);
System.out.println(k.get());
What is printed when the code above is run?
This would be the answer if add incremented the instance
variable once per call. But the assignment inside add never reaches the field.
This would require the parameter's value to be added to the field. The
statement adds 1 to the parameter, and only the parameter.
Correct. The parameter count shadows the instance variable inside
add, so count = count + 1; changes only the local copy, which
disappears when the method returns. The field stays 0. Writing
this.count = this.count + 1; would reach the field.
This adds the arguments to the field and then adds 1 for each call, but the
code never touches the field at all: both the read and the write use the parameter.
Unit 4 is about collections of data, and everything a program concludes from data is only as good as the data itself. Before the Java for arrays and lists, this lesson asks the questions a careful programmer asks first: who could be hurt by collecting this data, is the data any good, is it even the right data, and how will the algorithm look at it? The exam asks about these ideas in plain-language scenarios, and the answers use precise vocabulary.
Required content · LO 4.1.A, LO 4.1.B, LO 4.1.C, LO 4.2.A
Learning objectives.
4.1.A. Explain the risks to privacy from collecting and storing personal data on computer systems.
4.1.B. Explain the importance of recognizing data quality and potential issues when using a data set.
4.1.C. Identify an appropriate data set to use in order to solve a problem or answer a specific question.
4.2.A. Represent patterns and algorithms that involve data sets found in everyday life using written language or diagrams.
Essential knowledge.
4.1.A.1. When using a computer, personal privacy is at risk. When developing new programs, programmers should attempt to safeguard the personal privacy of the user.
4.1.B.1. Algorithmic bias describes systemic and repeated errors in a program that create unfair outcomes for a specific group of users.
4.1.B.2. Programmers should be aware of the data set collection method and the potential for bias when using this method before using the data to extrapolate new information or drawing conclusions.
4.1.B.3. Some data sets are incomplete or contain inaccurate data. Using such data in the development or use of a program can cause the program to work incorrectly or inefficiently.
4.1.C.1. Contents of a data set might be related to a specific question or topic and might not be appropriate to give correct answers or extrapolate information for a different question or topic.
4.2.A.1. A data set is a collection of specific pieces of information or data.
4.2.A.2. Data sets can be manipulated and analyzed to solve a problem or answer a question. When analyzing data sets, values within the set are accessed and utilized one at a time and then processed according to the desired outcome.
4.2.A.3. Data can be represented in a diagram by using a chart or table. This visual can be used to plan the algorithm that will be used to manipulate the data.
Privacy
When using a computer, personal privacy is at risk. Programs collect and store names, locations, messages, and habits, and once data is stored it can be copied, sold, leaked, or misused. When developing new programs, programmers should attempt to safeguard the personal privacy of the user: collect only what the program needs, protect what is stored, and tell the user what is collected.
Data quality and bias
Algorithmic bias describes systemic and repeated errors in a program that create unfair outcomes for a specific group of users. It can enter through the data or through the design.
A programmer should be aware of the data set collection method and the potential for bias in that method before using the data to extrapolate new information or to draw conclusions. A survey answered only by people who happened to hear about it represents only those people.
Some data sets are incomplete or contain inaccurate data. Using such data in the development or use of a program can cause the program to work incorrectly or inefficiently.
The contents of a data set might be related to a specific question or topic and might not be appropriate to give correct answers, or to extrapolate information, for a different question or topic. Data about favorite sports in one town does not answer a question about sports in another country.
What a data set is
A data set is a collection of specific pieces of information, or data. Data sets can be manipulated and analyzed to solve a problem or answer a question. When analyzing a data set, the values within the set are accessed and used one at a time and then processed according to the desired outcome: counted, added, compared, filtered.
Data can be shown in a diagram, such as a chart or table. The visual can be used to plan the algorithm that will manipulate the data, and in Java a table often becomes an array or list in the lessons that follow.
Worked example · choosing an appropriate data set
A school wants to decide how many buses to run next year. It has four data sets available. Which one answers the question, and why?
Data set
Collected from
Useful for the question?
Enrollment counts by neighborhood for this year
school records
Yes: shows where students live and how many there are
Favorite lunch items
a cafeteria survey
No: unrelated to transportation
Test scores by grade
the testing office
No: about academics, not distance or numbers
Enrollment counts from a school in another state
a public report
Weak: a different community, so it may not extrapolate
The first data set is related to the question. The fourth data set is the right type of data, but it describes a different population, so conclusions from it may not apply. A data set can be accurate and still be the wrong choice.
Worked example · incomplete data gives a wrong answer
A weather program averages four daily temperature readings. The sensor failed on day 3 and the system stored -1 where no reading arrived.
int day1 = 82;
int day2 = 90;
int day3 = -1;
int day4 = 88;
double wrong = (day1 + day2 + day3 + day4) / 4.0;
System.out.println(wrong);
64.75
The average is far too low, because -1 was treated as a real temperature. The correct approach is to leave out the missing value, both from the sum and from the count.
int day1 = 82;
int day2 = 90;
int day3 = -1;
int day4 = 88;
int sum = 0;
int count = 0;
if (day1 != -1) {
sum += day1;
count++;
}
if (day2 != -1) {
sum += day2;
count++;
}
if (day3 != -1) {
sum += day3;
count++;
}
if (day4 != -1) {
sum += day4;
count++;
}
System.out.println((double) sum / count);
86.66666666666667
Nothing in the first program failed: it compiled, ran, and printed a plausible number. Bad data produces wrong results quietly.
Worked example · planning an algorithm with a table
Orders are recorded in a table. The task: count the orders over $50.
Order
1
2
3
4
5
Amount
30
75
50
120
20
The plan processes the values one at a time, and a second table tracks what the algorithm does:
Value looked at
Over 50?
Count so far
30
no
0
75
yes
1
50
no (50 is not over 50)
1
120
yes
2
20
no
2
The answer is 2. Drawing the table first made the boundary visible: an order of exactly 50 is not over 50. Planning with a table is cheap, and it exposes boundary mistakes before any code exists.
Exam focus
Expect scenario questions with four answers: which situation shows a risk to privacy, which describes algorithmic bias, why a program with incomplete or inaccurate data works incorrectly, and which data set is most appropriate for a stated question. Pick the answer that applies the definition exactly. For data set questions, ask whether the data relates to the question and whether it comes from the right population. A diagram or table of the data is a valid way to plan an algorithm before coding.
Practice
A fitness app stores each user's exact location every minute and shares it with advertisers. Which concept does this raise?
Show answer
Privacy. Collecting and storing personal data puts personal privacy at risk, and a programmer should safeguard it, for example by collecting less and by not sharing without permission.
A hiring tool was built from ten years of past hiring decisions, and it ranks applicants from one group lower even though qualifications are equal. What is this called, and what is one cause?
Show answer
Algorithmic bias: systemic and repeated errors that create unfair outcomes for a specific group. One cause is data that reflects past unfair decisions, so the program repeats them.
A survey about library hours is posted only on the library's own website. Why might its results be unreliable for deciding hours for all students?
Show answer
The collection method has potential bias: only students who already use the library website respond, so the data may not represent students who rarely visit.
Which data set is most appropriate to find the average number of students absent on Mondays at one school: (a) daily attendance records for that school, (b) a national map of schools, (c) a list of student birthdays?
Show answer
(a). Only daily attendance data for that school relates to the question. The other two data sets exist but cannot answer it.
Why does this program print a misleading result?
int a = 70;
int b = 80;
int missing = 0;
System.out.println((a + b + missing) / 3.0);
Show answer
The value 0 stands for "no data" but is averaged as a real value, giving 50.0 when the true average of the two real values is 75.0. Incomplete or inaccurate data used by a program causes it to work incorrectly.
Draw the plan: a table lists the lengths 4, 9, 6, 9. In words, how would an algorithm find how many values are 9?
Show answer
Look at each value one at a time. Keep a count that starts at 0, and add 1 whenever the value being looked at is 9. For this table the count ends at 2.
Until now every value in a program has needed its own variable. For three test scores that is fine; for three hundred, or for a number you do not know until the program runs, it is impossible. An array is the first structure that lets a program hold a whole collection of related values under a single name and reach each one by number. Almost every free-response question on the exam uses one.
Required content · LO 4.3.A
Learning objective.
4.3.A. Develop code used to represent collections of related data using one-dimensional (1D) array objects.
Essential knowledge.
4.3.A.1. An array stores multiple values of the same type. The values can be either primitive values or object references.
4.3.A.2. The length of an array is established at the time of creation and cannot be changed. The length of an array can be accessed through the length attribute.
4.3.A.3. When an array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
4.3.A.4. Initializer lists can be used to create and initialize arrays.
4.3.A.5. Square brackets [] are used to access and modify an element in a 1D array using an index.
4.3.A.6. The valid index values for an array are 0 through one less than the length of the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException.
What an array is
An array stores multiple values of the same type. The values can be primitive values or object references. Each stored value is an element, and each element is located by its index, which starts at 0.
Figure 4.1. An array holds values of one type in numbered cells. The first index is 0, so the last valid index is one less than the length.
The length of an array is established at the time of creation and cannot be changed. You read it with the length attribute, written with no parentheses: scores.length. (A String's length() has parentheses; an array's length does not.)
Creating arrays
There are two ways. With new, you state the type and the size, and every element is set to the default value for its type (0 for int, 0.0 for double, false for boolean, null for a reference type). With an initializer list, you supply the values, and the length is the number of values.
Square brackets [] are used to access and modify an element using its index: marks[2] reads the third element and marks[2] = 91; replaces it. The valid indexes run from 0 through length - 1. Using an index outside that range throws an ArrayIndexOutOfBoundsException at run time.
int[] marks = {88, 72, 95, 60};
System.out.println(marks[4]);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
The last valid index of marks is 3. Whenever you see marks[marks.length], marks[-1], or a loop that runs one step too far, expect this exception.
The type of an array is part of the declaration, and the compiler checks each element against it:
int[] marks = {88, 72, 95, 60};
marks[0] = "ninety";
Main.java:3: error: incompatible types: String cannot be converted to int
Arrays are objects
An array variable holds a reference to the array. Assigning one array variable to another copies the reference, so both variables refer to the same array, and a change through either one is seen through both. Giving a variable a new array makes it refer to a different array and leaves the old one unchanged.
int[] x = {1, 2, 3};
int[] y = x;
y[0] = 99;
System.out.println(x[0]);
y = new int[5];
System.out.println(x.length + " " + y.length);
99
3 5
Worked example · filling an array with a loop
Create an array of five integers where each element is the square of its index.
int[] a = new int[5];
for (int i = 0; i < a.length; i++) {
a[i] = i * i;
}
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4]);
0 1 4 9 16
i
0
1
2
3
4
a[i] after the loop
0
1
4
9
16
The loop test is i < a.length, never <=: an index equal to the length is one past the last element. Using a.length rather than the number 5 keeps the loop correct if the size changes.
Worked example · an array of objects starts empty
An array of a reference type holds null until each element is assigned an object.
Book[] shelf = new Book[3];
shelf[0] = new Book("Atlas", 400);
System.out.println(shelf[0].getTitle() + " " + shelf[1]);
System.out.println(shelf[1].getTitle());
Exception in thread "main" java.lang.NullPointerException
The first println prints Atlas null, because slot 0 holds a Book and slot 1 still holds the default null. The second line asks a null slot for its title, which throws a NullPointerException. Creating the array did not create any Book objects; it created three empty slots.
alias = original copied the reference, so the change at index 1 is visible through original. other is a separate array with the same contents, so it is untouched and original == other is false: the == operator compares references, not contents.
Exam focus
Expect questions that create an array with new and an initializer list and ask for the contents or the length, questions about default values (0, 0.0, false, null), and questions that end in an ArrayIndexOutOfBoundsException. Remember: the length is fixed, length has no parentheses for an array, and the valid indexes are 0 through length - 1. An array of objects starts full of null, and two array variables can refer to one array.
The length is 3, and the last element is at index w.length - 1, which is 2, holding "blue".
What happens when this code runs?
int[] a = {4, 8, 15};
for (int i = 0; i <= a.length; i++) {
System.out.print(a[i] + " ");
}
Show answer
The loop prints 4 8 15 and then fails with an ArrayIndexOutOfBoundsException. The test i <= a.length lets i reach 3, which is not a valid index.
What is printed?
int[] p = {1, 2, 3};
int[] q = p;
q[2] = 50;
p = new int[2];
System.out.println(q.length + " " + q[2] + " " + p.length);
Show answer
3 50 2. q still refers to the original array, whose element 2 was changed to 50. Assigning a new array to p leaves q alone.
What are the default values of the elements of new double[2], new boolean[2], and new String[2]?
Show answer
0.0 for the double elements, false for the boolean elements, and null for the String elements.
Why does int[] a = new int[3]; a.length(); not compile?
Show answer
The length of an array is the attribute length, written without parentheses. length() with parentheses is the String method, so the compiler cannot find a method called length() for an array.
A collection is only useful if you can go through it. Traversing an array means using repetition to visit all of its elements, or an ordered sequence of them. The patterns in this lesson are the skeleton of nearly every array algorithm: once you can traverse, finding a largest value, counting matches, and summing become short additions to the loop.
Required content · LO 4.4.A
Learning objective.
4.4.A. Develop code used to traverse the elements in a 1D array and determine the result of these traversals.
Essential knowledge.
4.4.A.1. Traversing an array is when repetition statements are used to access all or an ordered sequence of elements in an array.
4.4.A.2. Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
4.4.A.3. An enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
4.4.A.4. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
4.4.A.5. When an array stores object references, the attributes can be modified by calling methods on the enhanced for loop variable. This does not change the object references stored in the array.
4.4.A.6. Code written using an enhanced for loop to traverse elements in an array can be rewritten using an indexed for loop or a while loop.
Two loops for one job
Traversing an array with an indexedfor loop (or a while loop) accesses the elements using their indices.
int[] a = {3, 8, 1, 6};
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
3 8 1 6
An enhanced for loop has a header with a variable, called the enhanced for loop variable, and the name of the array. In each iteration the variable is assigned a copy of an element, one at a time, without an index.
int[] a = {3, 8, 1, 6};
for (int v : a) {
System.out.print(v + " ");
}
3 8 1 6
Read the header as "for each int v in a". The enhanced loop cannot go backward, cannot skip, and has no index. In exchange it cannot run off the end. Code written with an enhanced for loop can always be rewritten with an indexed for loop or a while loop.
Assigning to the loop variable does nothing
Because the loop variable holds a copy, assigning a new value to it does not change the value stored in the array.
int[] a = {3, 8, 1, 6};
for (int v : a) {
v = v * 2;
}
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 10;
}
for (int v : a) {
System.out.print(v + " ");
}
30 80 10 60
The first loop doubled copies and discarded them. The second loop changed the real elements, because a[i] = ... assigns to the array itself. To modify primitive elements you need the index.
Arrays of objects
When an array stores object references, the enhanced loop variable is a copy of the reference. Calling a method on it that changes the object's state changes the same object stored in the array. This does not change which reference is stored in the array.
Book[] shelf = {new Book("A", 100), new Book("B", 200)};
for (Book b : shelf) {
b.setPages(b.getPages() + 10);
}
for (Book b : shelf) {
b = new Book("Z", 1);
}
System.out.println(shelf[0].getTitle() + " " + shelf[0].getPages());
System.out.println(shelf[1].getTitle() + " " + shelf[1].getPages());
A 110
B 210
The first loop followed each reference and changed the real Book objects (+10 pages). The second loop pointed its own copy of the reference at new objects and threw them away: the array still holds the original books.
Partial and reversed traversals
A traversal may access "an ordered sequence of elements", not necessarily all of them in order. Changing the loop header changes the sequence.
int[] a = {10, 20, 30, 40, 50};
for (int i = a.length - 1; i >= 0; i--) {
System.out.print(a[i] + " ");
}
System.out.println();
for (int i = 0; i < a.length; i += 2) {
System.out.print(a[i] + " ");
}
System.out.println();
int k = 0;
while (k < a.length && a[k] != 30) {
k++;
}
System.out.println(k);
50 40 30 20 10
10 30 50
2
The last loop is a while traversal that stops early: the first condition k < a.length guards the second so the array is never read out of range (the short-circuit rule from Lesson 2.5).
Worked example · indexed or enhanced?
For each task, which loop is the right tool?
Task
Loop
Why
print every element
enhanced
no index needed
add up the elements
enhanced
reads each value once
double every element in place
indexed
must assign to a[i]
print the elements backward
indexed
enhanced cannot go backward
print every other element
indexed
needs to step by 2
find the first index of a value
indexed
the answer is an index
int[] a = {4, 7, 4, 9};
int total = 0;
for (int v : a) {
total += v;
}
int first = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == 4 && first == -1) {
first = i;
}
}
System.out.println(total + " " + first);
24 0
When the question is "what is the value", an enhanced loop is simplest. When the question is "where" or "change it", you need the index.
Worked example · tracing an indexed loop with an update
Each step uses the value just written by the previous step, so the array ends up holding running totals. Starting the loop at i = 1 avoids a[-1].
Exam focus
Expect to trace both kinds of loops, and to answer what the array holds after a loop that assigns to the enhanced loop variable (nothing changes for primitives). For arrays of objects, know the difference between calling a mutator on the loop variable (changes the object) and assigning a new object to it (changes nothing). Check the loop bounds: i < a.length, a starting index of 1 when a[i - 1] is used, and a step other than 1.
Practice
What is printed?
int[] a = {2, 4, 6};
for (int v : a) {
v += 1;
}
System.out.println(a[0] + " " + a[1] + " " + a[2]);
Show answer
2 4 6. The loop variable v is a copy of each element, so the changes are lost and the array is unchanged.
What is printed?
int[] a = {2, 4, 6};
for (int i = 0; i < a.length; i++) {
a[i] += 1;
}
System.out.println(a[0] + " " + a[1] + " " + a[2]);
Show answer
3 5 7. Using the index assigns to the elements themselves.
Rewrite this enhanced loop as an indexed loop that does the same thing.
int[] nums = {1, 2, 3};
int sum = 0;
for (int n : nums) {
sum += n;
}
int sum2 = 0;
for (int i = 0; i < nums.length; i++) {
sum2 += nums[i];
}
System.out.println(sum + " " + sum2);
Show answer
The indexed loop for (int i = 0; i < nums.length; i++) { sum2 += nums[i]; } visits the same elements. Both versions compute 6.
What does this code print?
int[] a = {9, 8, 7, 6, 5};
for (int i = a.length - 1; i >= 0; i -= 2) {
System.out.print(a[i] + " ");
}
Show answer
5 7 9. The index runs 4, 2, 0, so the elements printed are the last, the middle, and the first.
After this loop, what is p[0].getPages()?
Book[] p = {new Book("A", 100)};
for (Book b : p) {
b.setPages(250);
}
System.out.println(p[0].getPages());
Show answer
250. The loop variable is a copy of the reference, and setPages changes the same object that the array holds.
Why is an enhanced for loop a poor choice to set every element of an int array to 0?
Show answer
The loop variable is a copy of each element, so assigning 0 to it changes nothing in the array. An indexed loop with a[i] = 0; is needed.
You have the loop. This lesson adds the standard things programs do with it. For arrays, the exam's algorithms fall into two families, and each is a handful of lines you should be able to write without thinking. This first lesson covers finding extreme values, computing sums and averages, and asking questions about elements: does at least one have a property, do all of them, how many.
There are standard algorithms that use array traversals to:
determine a minimum or maximum value,
compute a sum or average,
determine if at least one element has a particular property,
determine if all elements have a particular property,
determine the number of elements having a particular property,
access all consecutive pairs of elements,
determine the presence or absence of duplicate elements,
shift or rotate elements left or right, and
reverse the order of the elements.
The first five are here. The last four are in Lesson 4.5.
Required content · LO 4.5.A
Learning objective.
4.5.A. Develop code for standard and original algorithms for a particular context or specification that involves arrays and determine the result of these algorithms.
Essential knowledge.
4.5.A.1. There are standard algorithms that utilize array traversals to:
determine a minimum or maximum value
compute a sum or average
determine if at least one element has a particular property
determine if all elements have a particular property
determine the number of elements having a particular property
access all consecutive pairs of elements
determine the presence or absence of duplicate elements
shift or rotate elements left or right
reverse the order of the elements
Minimum and maximum, sum and average
Initialize the running maximum from the first element, then compare the rest. A maximum initialized to 0 fails if every element is negative.
public static int findMax(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
public static int findMin(int[] a) {
int min = a[0];
for (int v : a) {
if (v < min) {
min = v;
}
}
return min;
}
public static int sum(int[] a) {
int total = 0;
for (int v : a) {
total += v;
}
return total;
}
public static double average(int[] a) {
return (double) sum(a) / a.length;
}
findMax starts its loop at index 1, because index 0 already seeded the maximum. average casts before dividing so that the fraction survives.
Does at least one element have a property? Do all?
The any pattern returns true as soon as one element passes the test, and false only after the whole array has been checked. The all pattern returns false as soon as one element fails the test, and true only after everything passed. The two are mirror images, and the common error is to mix them up.
public static boolean anyNegative(int[] a) {
for (int v : a) {
if (v < 0) {
return true;
}
}
return false;
}
public static boolean allPositive(int[] a) {
for (int v : a) {
if (v <= 0) {
return false;
}
}
return true;
}
public static int badMax(int[] a) {
int max = 0;
for (int v : a) {
if (v > max) {
max = v;
}
}
return max;
}
int[] temps = {-5, -2, -9};
System.out.println(badMax(temps));
System.out.println(findMax(temps));
0
-2
The data are all negative, so none beats the starting 0, and badMax returns a value that is not in the array. findMax seeds from a[0], so its answer is always an element of the array. When the array can be empty, you must also check a.length first, since a[0] would fail.
Worked example · mixing up any and all
What happens if the all pattern is written like the any pattern?
public static boolean buggyAll(int[] a) {
for (int v : a) {
if (v > 0) {
return true;
}
}
return false;
}
int[] p = {3, -1, 5};
System.out.println(buggyAll(p));
System.out.println(allPositive(p));
true
false
buggyAll returns true as soon as it sees the first positive element, so it answers "is at least one element positive?", not "are all elements positive?". The array contains -1, so the correct answer is false. In the all pattern, the early return belongs in the failing case.
Worked example · combining a count and a sum
Report how many elements exceed the average.
public static int countAboveAverage(int[] a) {
double avg = average(a);
int count = 0;
for (int v : a) {
if (v > avg) {
count++;
}
}
return count;
}
The average is 6.2 and the values above it are 9, 9, and 7. The method makes two passes: one inside average to compute the sum and one in the loop to count. Building a new algorithm out of the standard ones, as here, is the usual way to solve a harder problem.
Exam focus
Expect to read a method like these and say what it returns, to complete the missing line (the initialization, the comparison, or the return), or to write one as a method. Check three things in every one: what the accumulator or maximum starts as, which comparison is used (> or >=), and where the return sits relative to the loop. The any pattern returns true inside the loop, and the all pattern returns false inside the loop.
Practice
What does this method return for {3, 7, 7, 2}?
public static int mystery(int[] a) {
int best = a[0];
int where = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] > best) {
best = a[i];
where = i;
}
}
return where;
}
1. The method returns the index of the first largest value. The second 7 is not greater than the current best, so the index does not change.
Write a method that returns the average of an int array as a double.
public static double mean(int[] a) {
int total = 0;
for (int v : a) {
total += v;
}
return (double) total / a.length;
}
System.out.println(mean(new int[] {1, 2, 4}));
Show answer
The method above sums the elements and divides by the length with a double division. Returning total / a.length would have used integer division and returned 2.0.
Complete the method so that it returns true if every element is even.
public static boolean allEven(int[] a) {
for (int v : a) {
if (v % 2 != 0) {
return false;
}
}
return true;
}
This is the all pattern: return false on the first odd element, and true only after every element passed. An empty array returns true, since no element fails.
What is printed?
int[] a = {5, 12, 8, 12, 3};
int count = 0;
for (int v : a) {
if (v >= 8) {
count++;
}
}
System.out.println(count);
Show answer
3. The values 12, 8, and 12 satisfy v >= 8. The 8 counts because the test uses >=.
Why does this method sometimes return the wrong minimum?
public static int minOf(int[] a) {
int min = 0;
for (int v : a) {
if (v < min) {
min = v;
}
}
return min;
}
System.out.println(minOf(new int[] {4, 6, 9}));
Show answer
The minimum is seeded with 0, so for an array of positive values nothing is ever smaller and the method returns 0, which is not in the array. Seed min from a[0].
A method returns true as soon as it finds a value larger than 100. Which pattern is it, and what does it report?
Show answer
The any pattern. It reports whether at least one element is larger than 100, and the true return sits inside the loop.
Lesson 4.4 covered extremes, sums, and counts. The last four standard array algorithms change how the loop looks at the array: it examines two neighbors at once, compares each element with the ones after it, or moves elements to new positions. Each has a loop bound that is easy to get wrong by one, and that is exactly where the exam tests you.
Required content · LO 4.5.A
Learning objective.
4.5.A. Develop code for standard and original algorithms for a particular context or specification that involves arrays and determine the result of these algorithms.
Essential knowledge.
4.5.A.1. There are standard algorithms that utilize array traversals to:
determine a minimum or maximum value
compute a sum or average
determine if at least one element has a particular property
determine if all elements have a particular property
determine the number of elements having a particular property
access all consecutive pairs of elements
determine the presence or absence of duplicate elements
shift or rotate elements left or right
reverse the order of the elements
Consecutive pairs
To access all consecutive pairsa[i] and a[i + 1], the loop must stop one early, at i < a.length - 1. Otherwise a[i + 1] runs off the end.
public static int countIncreases(int[] a) {
int count = 0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i + 1] > a[i]) {
count++;
}
}
return count;
}
The pairs are (3,5), (5,4), (4,8), (8,9): three of the four are increases.
Duplicates
To find out whether any value appears twice, compare each element with every element after it. That needs a loop inside a loop: the inner loop starts at i + 1, so an element is never compared with itself or with a pair already checked.
public static boolean hasDuplicate(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
return true;
}
}
}
return false;
}
Starting the inner loop at 0 would compare each element with itself and report a duplicate in every array.
Shifting and rotating
To shift elements left, copy each element from its right neighbor, going from the front. To rotate left, save the first element, shift, and place the saved value at the end.
public static void shiftLeft(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
}
public static void rotateLeft(int[] a) {
int first = a[0];
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
a[a.length - 1] = first;
}
public static void rotateRight(int[] a) {
int last = a[a.length - 1];
for (int i = a.length - 1; i > 0; i--) {
a[i] = a[i - 1];
}
a[0] = last;
}
A shift loses the first value and leaves a duplicate of the last. Direction matters: shifting left copies from the front, but shifting right must go from the back, or the first copy overwrites a value that has not been moved yet.
Reversing
To reverse in place, swap the first and last, then the second and second-to-last, and stop at the middle. Swapping needs a temporary variable.
public static void reverse(int[] a) {
for (int i = 0; i < a.length / 2; i++) {
int temp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = temp;
}
}
If the loop ran all the way to a.length, every pair would be swapped twice and the array would end up unchanged.
Worked example · why shift-right must run backward
A programmer shifts right from the front.
int[] a = {1, 2, 3, 4};
for (int i = 1; i < a.length; i++) {
a[i] = a[i - 1];
}
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3]);
1 1 1 1
i
statement
array after
1
a[1] = a[0]
1, 1, 3, 4
2
a[2] = a[1]
1, 1, 1, 4
3
a[3] = a[2]
1, 1, 1, 1
Each step copied the value that the previous step had just written. Going from the back (rotateRight above) copies each element before it is overwritten.
The broken version overwrote b[0] before saving it, so the 5 was lost. The temporary holds the first value while the two slots are reassigned.
Worked example · counting equal neighbors
Count how many consecutive pairs hold equal values.
public static int equalNeighbors(int[] a) {
int count = 0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] == a[i + 1]) {
count++;
}
}
return count;
}
The pairs (2,2), (2,2), and (5,5) match, so the answer is 3, not 2: overlapping pairs each count. Writing the loop bound as i < a.length would throw an ArrayIndexOutOfBoundsException on the last pass.
Exam focus
Expect to trace one of these on a small array and give the contents afterward, or to fill in the loop bound or the missing statement. The bound a.length - 1 goes with a[i + 1]; the inner duplicate loop starts at i + 1; a right shift runs from the back; and a reversal stops at a.length / 2 and uses a temporary. When the array is changed by a method, the caller sees the change, because the array is passed as a reference.
Practice
What does the array hold after rotateLeft on {7, 8, 9}?
int[] a = {7, 8, 9};
int first = a[0];
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
a[a.length - 1] = first;
System.out.println(a[0] + " " + a[1] + " " + a[2]);
Show answer
8 9 7. Each element moves one place left, and the saved first value goes to the end.
What is printed?
int[] a = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < a.length / 2; i++) {
int t = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = t;
}
System.out.println(a[0] + " " + a[5]);
Show answer
6 1. The array is reversed, so the first element is now 6 and the last is 1.
Why does this method throw an exception for any non-empty array?
public static int bad(int[] a) {
int c = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == a[i + 1]) {
c++;
}
}
return c;
}
System.out.println(bad(new int[] {1, 1}));
Show answer
On the last pass i is a.length - 1, so a[i + 1] is a[a.length], which is out of bounds. The bound should be i < a.length - 1.
What does hasDuplicate return for {3, 1, 3}, and which pair does it find?
int[] a = {3, 1, 3};
boolean found = false;
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
found = true;
}
}
}
System.out.println(found);
Show answer
true. At i = 0 and j = 2 the elements a[0] and a[2] are both 3.
How many comparisons does the inner duplicate loop make for an array of length 4?
Show answer
6: the pairs are (0,1), (0,2), (0,3), (1,2), (1,3), and (2,3), that is 3 + 2 + 1.
A programmer swaps a[0] and a[1] with a[0] = a[1]; a[1] = a[0];. What goes wrong?
Show answer
The first assignment overwrites the old a[0], so the second assignment copies the new value back. Both slots end up equal to the original a[1]. A temporary variable must hold a[0] first.
So far every value in a program has been typed into the source code. Real programs read their data from files: records, measurements, or text. The course uses a small, fixed set of tools for this. You will see them on the exam as a program fragment to read, not as something you have to memorize character by character.
Required content · LO 4.6.A
Learning objective.
4.6.A. Develop code to read data from a text file.
Essential knowledge.
4.6.A.1. A file is storage for data that persists when the program is not running. The data in a file can be retrieved during program execution.
4.6.A.2. A file can be connected to the program using the File and Scanner classes.
4.6.A.3. A file can be opened by creating a File object, using the name of the file as the argument of the constructor.
File(String str) is the File constructor that accepts a String file name to open for reading, where str is the pathname for the file.
4.6.A.4. When using the File class, it is required to indicate what to do if the file with the provided name cannot be opened. One way to accomplish this is to add throws IOException to the header of the method that uses the file. If the file name is invalid, the program will terminate.
4.6.A.5. The File and IOException classes are part of the java.io package. An import statement must be used to make these classes available for use in the program.
4.6.A.6. The following Scanner methods and constructor—including what they do and when they are used—are part of the Java Quick Reference: B ullet Scanner(File f) is the Scanner constructor that accepts a File for reading.
int nextInt() returns the next int read from the file or input source if available. If the next int does not exist or is out of range, it will result in an InputMismatchException.
double nextDouble() returns the next double read from the file or input source. If the next double does not exist, it will result in an InputMismatchException.
boolean nextBoolean() returns the next boolean read from the file or input source. If the next boolean does not exist, it will result in an InputMismatchException.
String nextLine() returns the next line of text as a String read from the file or input source; can return the empty string if called immediately after another Scanner method that is reading from the file or input source.
String next() returns the next String read from the file or input source.
boolean hasNext() returns true if there is a next item to read in the file or input source; returns false otherwise.
void close() closes this scanner. X EXCLUSION STATEMENT—Accepting input from the keyboard is outside the scope of the AP Computer Science A course and exam.
4.6.A.7. Using nextLine and the other Scanner methods together on the same input source sometimes requires code to adjust for the methods’ different ways of handling whitespace. X EXCLUSION STATEMENT—Writing or analyzing code that uses both nextLine and other Scanner methods on the same input source is outside the scope of the AP Computer Science A course and exam.
4.6.A.8. The following additional String method— including what it does and when it is used—is part of the Java Quick Reference:
String[] split(String del) returns a String array where each element is a substring of this String, which has been split around matches of the given expression del. X EXCLUSION STATEMENT—The parameter del uses a format called a regular expression. Writing or analyzing code that uses any of the special properties of regular expressions (e.g., \\*, \\.) is outside the scope of the AP Computer Science A course and exam.
4.6.A.9. A while loop can be used to detect if the file still contains elements to read by using the hasNext method as the condition of the loop.
4.6.A.10. A file should be closed when the program is finished using it. The close method from Scanner is called to close the file.
Reading a file
A file is a stream of text. To read a text file, the program creates a File object for the file name, and a Scanner that reads from it. The classes File and Scanner are in java.io and java.util, so both packages are imported.
The Scanner methods used are:
hasNext(), which returns true if there is another item to read,
nextLine(), which returns the rest of the current line as a String,
next(), which returns the next whitespace-separated item as a String,
nextInt(), which returns the next item as an int, and
close(), which releases the file when the program is done.
Opening a file can fail, for example when it does not exist. Java treats that as a checked problem, so a method that creates the Scanner must declare throws IOException in its header.
Ada 91
Ben 78
Cy 85
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
File f = new File("scores.txt");
Scanner sc = new Scanner(f);
int total = 0;
int count = 0;
while (sc.hasNext()) {
String name = sc.next();
int score = sc.nextInt();
total += score;
count++;
}
sc.close();
System.out.println(count + " " + total);
}
}
3 254
The loop uses hasNext() as its condition so the program stops when the data run out. Calling next() when nothing is left would throw an exception.
A file that is not there
If the named file does not exist, creating the Scanner throws a FileNotFoundException, which is a kind of IOException.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("missing.txt"));
System.out.println("never reached");
}
}
Exception in thread "main" java.io.FileNotFoundException
Reading line by line
When each line is one record, read it with nextLine() and break it into parts with split. The String method split(delimiter) returns an array of the pieces between delimiters.
String line = "Ada,91,north";
String[] parts = line.split(",");
System.out.println(parts.length + " " + parts[0] + " " + parts[1]);
int score = Integer.parseInt(parts[1]);
System.out.println(score + 1);
3 Ada 91
92
The pieces are Strings, so a number must be converted with Integer.parseInt (Lesson 4.7).
Worked example · totaling a column
Read each line of temps.txt, split on commas, and total the second field.
Mon,70
Tue,74
Wed,68
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("temps.txt"));
int sum = 0;
while (sc.hasNext()) {
String line = sc.nextLine();
String[] parts = line.split(",");
sum += Integer.parseInt(parts[1]);
}
sc.close();
System.out.println(sum);
}
}
212
Each pass takes the whole line, splits it into two pieces, and adds the second piece after converting it. The sum is 70 + 74 + 68 = 212.
Worked example · counting lines that match
Count the lines of names.txt that start with "A".
Ana
Bo
Al
Cy
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("names.txt"));
int count = 0;
while (sc.hasNext()) {
String name = sc.nextLine();
if (name.substring(0, 1).equals("A")) {
count++;
}
}
sc.close();
System.out.println(count);
}
}
2
The loop is the same count pattern from Lesson 4.4, with the elements coming from the file instead of an array. Because a file can be long, reading and counting one item at a time is how such programs are written.
Worked example · reading into an array of Strings
Collect the words of a file in an ArrayList (introduced in Lesson 4.8).
sun moon star
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("words.txt"));
ArrayList<String> words = new ArrayList<String>();
while (sc.hasNext()) {
words.add(sc.next());
}
sc.close();
System.out.println(words.size() + " " + words.get(2));
}
}
3 star
Data of unknown length is a natural fit for a list, since an array's length must be fixed before the first element is stored.
Exam focus
Expect a short program that opens a file, loops with hasNext(), and uses next, nextLine, nextInt or split to process the data. You may be asked what it prints for a given file, why it throws an exception, or why the method header needs throws IOException. Remember to close the Scanner, and to convert a String piece to a number with Integer.parseInt before doing arithmetic.
Practice
Why does a method that creates new Scanner(new File("data.txt")) need throws IOException in its header?
Show answer
The file might not exist or might not be readable, and Java requires a method that can cause such an error either to handle it or to declare it with throws.
What exception is thrown if new Scanner(new File("nofile.txt")) runs and the file does not exist?
Show answer
A FileNotFoundException, which is a kind of IOException.
What does the loop condition sc.hasNext() do?
Show answer
It returns true while there is another item to read, so the loop stops after the last item.
What is printed?
String line = "red,green,blue";
String[] p = line.split(",");
System.out.println(p.length + " " + p[2]);
Show answer
3 blue. split(",") gives an array of three Strings, and index 2 holds "blue".
A file has the lines 4 and 9 and 5. What does a program that adds each line with Integer.parseInt total?
Show answer
18. Each line is converted to an int and added: 4 + 9 + 5.
Why must parseInt be applied to parts[1] before adding it to an int total?
Show answer
The elements returned by split are Strings. Adding a String to an int would build text, and a String cannot be assigned to an int sum without converting it.
Java has two different kinds of values: primitives like int, and objects. A collection such as an ArrayList can only hold objects, not primitives. To bridge this gap, Java supplies a wrapper class for each primitive type: an object that holds one primitive value.
Required content · LO 4.7.A
Learning objective.
4.7.A. Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.
Essential knowledge.
4.7.A.1. The Integer class and Double class are part of the java.lang package. An Integer object is immutable, meaning once an Integer object is created, its attributes cannot be changed. A Double object is immutable, meaning once a Double object is created, its attributes cannot be changed.
4.7.A.2. Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is:
passed as a parameter to a method that expects an object of the corresponding wrapper class
assigned to a variable of the corresponding wrapper class
4.7.A.3. Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is:
passed as a parameter to a method that expects a value of the corresponding primitive type
assigned to a variable of the corresponding primitive type
The two wrapper classes in the course
The Integer class and the Double class are part of the java.lang package, so no import is needed. An Integer object holds an int, and a Double object holds a double.
Autoboxing and unboxing
Autoboxing is the automatic conversion that the Java compiler makes between a primitive value and the corresponding wrapper class object. For example, converting an int to an Integer. Unboxing is the automatic conversion the other way, from the wrapper object to the primitive value.
Integer boxed = 5;
int plain = boxed;
Double d = 2.5;
double e = d + 1;
System.out.println(boxed + " " + plain + " " + e);
5 5 3.5
The assignment Integer boxed = 5; boxes the value, and int plain = boxed; unboxes it. The compiler also does it in arithmetic and in method calls, which is how an ArrayList<Integer> can be used with plain int values.
Autoboxing does not cross types: an int can be boxed to Integer but not to Double.
Double d = 5;
Main.java:3: error: incompatible types: int cannot be converted to Double
Useful members
The wrapper classes provide constants and methods:
Integer.MIN_VALUE and Integer.MAX_VALUE are the smallest and largest int values.
Integer.parseInt(String s) returns the int that the String represents.
Double.parseDouble(String s) returns the double that the String represents.
intValue() and doubleValue() return the primitive value of an Integer or Double.
parseInt on text that is not a whole number throws a NumberFormatException.
int n = Integer.parseInt("4.5");
Exception in thread "main" java.lang.NumberFormatException
Comparing wrapper objects
Two Integer variables hold references, so == compares whether they are the same object. To compare values, use equals, or unbox first.
Integer a = 1000;
Integer b = 1000;
System.out.println(a.equals(b)); // true: same value
Rely on equals for objects and == only for primitives.
Worked example · MAX_VALUE as a starting minimum
A method finds the smallest value in an ArrayList<Integer>. Seeding with Integer.MAX_VALUE guarantees every real element is smaller (or equal).
public static int smallest(ArrayList<Integer> list) {
int min = Integer.MAX_VALUE;
for (int v : list) {
if (v < min) {
min = v;
}
}
return min;
}
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(40);
nums.add(7);
nums.add(19);
System.out.println(smallest(nums));
7
The loop variable int v unboxes each Integer. The same idea with Integer.MIN_VALUE seeds a maximum. For an empty list the method would return Integer.MAX_VALUE, which shows why the starting value matters.
Worked example · converting text to numbers
A line holds "12 7.5". Add the two numbers.
String line = "12 7.5";
String[] parts = line.split(" ");
int whole = Integer.parseInt(parts[0]);
double part = Double.parseDouble(parts[1]);
System.out.println(whole + part);
19.5
The pieces are Strings. Each is converted with the parse method that matches its type, then the int is promoted to double in the addition.
Worked example · boxing happens in method calls
An ArrayList<Integer> method takes the object, but we pass a primitive.
ArrayList<Integer> list = new ArrayList<Integer>();
int x = 8;
list.add(x);
list.add(15);
int back = list.get(0);
System.out.println(back + list.get(1));
23
list.add(x) boxes the int, and int back = list.get(0) unboxes the result. In back + list.get(1) the second Integer is unboxed so the addition is arithmetic, not text.
Exam focus
Expect questions that identify autoboxing and unboxing in a line of code, use Integer.parseInt or Double.parseDouble, or use Integer.MAX_VALUE and Integer.MIN_VALUE as seeds for a minimum or maximum. Know that Integer and Double hold a primitive value, that the compiler converts automatically between them and the primitives, and that parseInt throws an exception when the text is not an int.
Practice
What is autoboxing?
Show answer
The automatic conversion the compiler makes from a primitive value to its wrapper class object, such as an int to an Integer.
What is printed?
Integer a = 6;
int b = a * 2;
System.out.println(b);
Show answer
12. The Integer is unboxed for the multiplication, and the result is an int.
Which value is used to start a search for the minimum so that any real element is smaller?
Show answer
Integer.MAX_VALUE. Every other int is at most that large, so the first comparison always replaces it.
What does Integer.parseInt("17") + 3 evaluate to?
System.out.println(Integer.parseInt("17") + 3);
Show answer
20. The String "17" becomes the int 17, then 3 is added.
Why does Integer.parseInt("abc") throw an exception?
Show answer
The text does not represent an int, so the method throws a NumberFormatException.
Why is the declaration Double d = 5; rejected by the compiler?
Show answer
The int 5 can be autoboxed only to an Integer, not to a Double. Writing 5.0 makes the value a double that boxes correctly.
An array has a fixed length, so a program that adds and removes items as it runs has to build something larger each time. The ArrayList class solves this: a list that grows and shrinks as needed, with methods for the common operations. It appears in at least one free-response question every year.
Required content · LO 4.8.A
Learning objective.
4.8.A. Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.
Essential knowledge.
4.8.A.5. The following ArrayList methods— including what they do and when they are used—are part of the Java Quick Reference:
int size() returns the number of elements in the list.
boolean add(E obj) appends obj to end of list; returns true.
void add(int index, E obj) inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size.
E get(int index) returns the element at position index in the list.
E set(int index, E obj) replaces the element at position index with obj; returns the element formerly at position index.
E remove(int index) removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index.
4.8.A.6. The indices for an ArrayList start at 0 and end at the number of elements - 1.
Creating a list
An ArrayList object is mutable and contains object references. Its size is the number of elements it currently holds. The class is in java.util, so the program must import it. The type of the elements is given in angle brackets, the generic type, and the compiler enforces it. A new list is empty. The list can hold only objects, so a list of numbers uses Integer or Double (autoboxing makes this painless).
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> nums = new ArrayList<Integer>();
System.out.println(names.size() + " " + nums.size());
0 0
The methods
Method
What it does
int size()
returns the number of elements
boolean add(E obj)
appends obj to the end, returns true
void add(int index, E obj)
inserts obj at index, moving later elements one to the right
E get(int index)
returns the element at index
E set(int index, E obj)
replaces the element at index and returns the old element
E remove(int index)
removes the element at index, moving later elements one to the left, and returns it
The valid indexes for get, set, and remove are 0 through size() - 1. For the two-argument add the indexes run 0 through size(), since adding at size() appends. Any other index throws an IndexOutOfBoundsException.
ArrayList<String> list = new ArrayList<String>();
list.add("b");
list.add("d");
list.add(1, "c");
list.add(0, "a");
System.out.println(list);
String old = list.set(2, "C");
System.out.println(old + " " + list);
String gone = list.remove(0);
System.out.println(gone + " " + list + " " + list.size());
[a, b, c, d]
c [a, b, C, d]
a [b, C, d] 3
A list prints in square brackets, and the generated text is for tracing only. Notice how the positions shift: after add(1, "c") the old "d" moved to index 2, and after remove(0) everything moved left.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(5);
System.out.println(list.get(1));
Exception in thread "main" java.lang.IndexOutOfBoundsException
Arrays and lists compared
array
ArrayList
size
fixed at creation
changes with add and remove
size expression
a.length
list.size()
read element
a[i]
list.get(i)
write element
a[i] = v
list.set(i, v)
element types
primitives or objects
objects only
remove with Integer lists
For ArrayList<Integer>, list.remove(2) removes the element at index 2, because the argument is an int. This is a classic trap.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.remove(2);
System.out.println(list);
[10, 20]
The program removed the position 2 (the value 30), not the value 2. The course exam does not ask you to remove by value for Integer lists.
Worked example · tracing a list
Trace the list after each statement.
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(4);
a.add(9);
a.add(1, 7);
a.set(0, a.get(2) + a.get(1));
a.remove(1);
System.out.println(a);
statement
list after
a.add(4)
[4]
a.add(9)
[4, 9]
a.add(1, 7)
[4, 7, 9]
a.set(0, a.get(2) + a.get(1))
[16, 7, 9]
a.remove(1)
[16, 9]
[16, 9]
The set used 9 + 7, which is 16, and remove(1) took out the 7. Each row of the table is the whole list, which is the safest way to trace.
Worked example · swapping two elements of a list
Swap positions 0 and 2 using get and set.
ArrayList<String> s = new ArrayList<String>();
s.add("x");
s.add("y");
s.add("z");
String temp = s.get(0);
s.set(0, s.get(2));
s.set(2, temp);
System.out.println(s);
[z, y, x]
It is the array swap with get and set in place of the brackets. Because set returns the old element, a one-line variant is possible, but the temporary version is clearest.
Worked example · a list parameter changes the caller's list
A list passed to a method is a reference, so the method can change it.
The method received a reference to the same list, so its additions are visible to the caller. This is the same behavior as for an array or any other object.
Exam focus
Expect to trace a sequence of add, add(index, ...), set, and remove and write the final list, and to say which statement throws an IndexOutOfBoundsException. Know each method's return value, that size() has parentheses, that elements after an insertion move right and after a removal move left, and that remove(int) takes an index. Use the table of array versus list when a question asks which structure to choose.
Practice
What does the list contain after this code?
ArrayList<String> w = new ArrayList<String>();
w.add("one");
w.add("two");
w.add("three");
w.remove(1);
w.add(0, "zero");
System.out.println(w);
Show answer
[zero, one, three]. Removing index 1 takes out "two", then "zero" is inserted at the front.
What is printed?
ArrayList<Integer> v = new ArrayList<Integer>();
v.add(3);
v.add(5);
int old = v.set(0, 8);
System.out.println(old + " " + v.get(0) + " " + v.size());
Show answer
3 8 2. set returns the old element 3, the list now starts with 8, and the size is unchanged at 2.
Which line throws an exception, and which one?
ArrayList<String> t = new ArrayList<String>();
t.add("a");
t.add(2, "b");
Show answer
The third line: add(2, "b") on a list of size 1 uses an index that is larger than size(), so it throws an IndexOutOfBoundsException.
State two differences between an array and an ArrayList.
Show answer
An array has a fixed length and an ArrayList can grow and shrink; an array is read with a[i] and a.length, while a list uses get(i) and size(). A list holds only objects.
What does the list [4, 6, 8] look like after list.remove(2) when it is an ArrayList<Integer>?
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(6);
list.add(8);
list.remove(2);
System.out.println(list);
Show answer
[4, 6]. The argument is treated as an index, so the element at index 2 is removed.
Why can ArrayList<int> not be written?
Show answer
An ArrayList can hold only objects, not primitives. The wrapper type Integer is used instead, and autoboxing converts between int and Integer.
Traversing a list looks like traversing an array, with get(i) and size() in place of brackets and length. The difference that matters is that a list can change size while you walk it. Removing elements in the middle of a traversal is a famous source of bugs, and the exam asks about it directly.
Required content · LO 4.9.A
Learning objective.
4.9.A. Develop code used to traverse the elements of an ArrayList and determine the results of these traversals.
Essential knowledge.
4.9.A.1. Traversing an ArrayList is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an ArrayList.
4.9.A.2. Deleting elements during a traversal of an ArrayList requires the use of special techniques to avoid skipping elements.
4.9.A.3. Attempting to access an index value outside of its range will result in an IndexOutOfBoundsException.
4.9.A.4. Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.
The two loops
Traversing an ArrayList means using iteration (or recursion) to access all, or an ordered sequence, of its elements. An indexed loop uses get; an enhanced for loop gives a copy of each element, with the same rules as for arrays.
ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Ben");
names.add("Cy");
for (int i = 0; i < names.size(); i++) {
System.out.print(names.get(i) + " ");
}
System.out.println();
for (String s : names) {
System.out.print(s.length() + " ");
}
Ada Ben Cy
3 3 2
An index outside 0 through size() - 1 throws an IndexOutOfBoundsException.
Deleting during a traversal
When an element is removed, every later element moves one position left. A loop that moves forward then skips the element that slid into the removed spot.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
list.add(6);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) % 2 == 0) {
list.remove(i);
}
}
System.out.println(list);
[4, 5]
Every number except 5 was even, yet 4 survived. After 2 was removed at index 0, the 4 slid into index 0, and the loop moved on to index 1 without ever looking at it. There are two standard repairs.
Repair 1: go backward. Removing the element at index i only moves elements that have a larger index, which the loop has already passed.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
list.add(6);
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) % 2 == 0) {
list.remove(i);
}
}
System.out.println(list);
[5]
Repair 2: do not advance after a removal. Move the index only when nothing was removed.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
list.add(6);
int i = 0;
while (i < list.size()) {
if (list.get(i) % 2 == 0) {
list.remove(i);
} else {
i++;
}
}
System.out.println(list);
[5]
Do not resize inside an enhanced for loop
Changing the size of an ArrayList while traversing it with an enhanced for loop can cause a ConcurrentModificationException. Therefore, when using an enhanced for loop to traverse a list, you should not add or remove elements.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (int v : list) {
if (v == 1) {
list.remove(0);
}
}
Exception in thread "main" java.util.ConcurrentModificationException
Replacing an element with set is fine, since it does not change the size, but the loop variable is a copy, so the safe way is an indexed loop.
Worked example · why the forward loop skips
Trace the forward removal loop on [3, 3, 7], removing every 3.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(3);
list.add(7);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 3) {
list.remove(i);
}
}
System.out.println(list);
i
size()
get(i)
action
list after
0
3
3
remove
[3, 7]
1
2
7
keep
[3, 7]
2
2
loop ends
[3, 7]
[3, 7]
The second 3 slid into index 0 and was never examined. The backward loop visits indexes 2, 1, 0 and removes both 3s.
Worked example · removing words of one letter
Remove every String of length 1 from a list.
public static void removeShort(ArrayList<String> words) {
for (int i = words.size() - 1; i >= 0; i--) {
if (words.get(i).length() == 1) {
words.remove(i);
}
}
}
ArrayList<String> w = new ArrayList<String>();
w.add("a");
w.add("tree");
w.add("b");
w.add("c");
w.add("sky");
removeShort(w);
System.out.println(w);
[tree, sky]
Three consecutive removals are the case where the forward loop fails worst, and the backward loop handles it with no special code.
Worked example · inserting while traversing
Insert a copy of each element right after it.
ArrayList<String> list = new ArrayList<String>();
list.add("x");
list.add("y");
for (int i = 0; i < list.size(); i += 2) {
list.add(i + 1, list.get(i));
}
System.out.println(list);
[x, x, y, y]
Each insertion pushes the original next element right, so the index advances by 2 to land on the next original. The size grows as the loop runs, so the test i < list.size() is checked against the current size each time.
Exam focus
Expect a loop that removes elements and a question asking what the list holds afterward, usually showing the skipped-element error. Know both repairs (backward, or advance only without a removal), that the loop test uses size() which changes as elements are removed, and that adding or removing inside an enhanced for loop can throw a ConcurrentModificationException.
Practice
What does this code print?
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(5);
a.add(5);
a.add(8);
for (int i = 0; i < a.size(); i++) {
if (a.get(i) == 5) {
a.remove(i);
}
}
System.out.println(a);
Show answer
[5, 8]. After the first 5 is removed, the second 5 slides into index 0 and the loop moves to index 1 without checking it.
Rewrite the loop in the previous question so that it removes both 5s.
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(5);
a.add(5);
a.add(8);
for (int i = a.size() - 1; i >= 0; i--) {
if (a.get(i) == 5) {
a.remove(i);
}
}
System.out.println(a);
Show answer
Going backward gives [8]: removing an element only shifts elements the loop has already passed.
What error can occur when this loop runs, and why?
for (String s : words) {
if (s.equals("no")) {
words.remove(s);
}
}
Show answer
A ConcurrentModificationException. The list's size changes while an enhanced for loop is traversing it, which the loop does not allow.
What is printed?
ArrayList<String> s = new ArrayList<String>();
s.add("a");
s.add("b");
s.add("c");
int i = 0;
while (i < s.size()) {
if (s.get(i).equals("b")) {
s.remove(i);
} else {
i++;
}
}
System.out.println(s);
Show answer
[a, c]. The index advances only when nothing is removed, so no element is skipped.
Why must the test in a removal loop be i < list.size() rather than a number saved before the loop?
Show answer
The size shrinks as elements are removed. A saved starting size would let the index go past the end and throw an IndexOutOfBoundsException.
True or false: replacing an element with list.set(i, value) inside an indexed loop can cause a skipped element.
Show answer
False. set does not change the size or move any other element, so the traversal is not disturbed.
Every array algorithm from Lessons 4.4 and 4.5 works on a list with the syntax swapped. The standard ArrayList algorithms are the same set: minimum or maximum, sum or average, any, all, count, consecutive pairs, duplicates, shifting or rotating, and reversing. A list adds two things: the structure can change size, so some algorithms build or filter a new list, and it holds objects, so comparisons use equals.
Required content · LO 4.10.A
Learning objective.
4.10.A. Develop code for standard and original algorithms for a particular context or specification that involve ArrayList objects and determine the result of these algorithms.
Essential knowledge.
4.10.A.1. There are standard ArrayList algorithms that utilize traversals to:
determine a minimum or maximum value
compute a sum or average
determine if at least one element has a particular property
determine if all elements have a particular property
determine the number of elements having a particular property
access all consecutive pairs of elements
determine the presence or absence of duplicate elements
shift or rotate elements left or right
reverse the order of the elements
insert elements
delete elements
The same algorithms with get and size
public static int maxOf(ArrayList<Integer> list) {
int max = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) > max) {
max = list.get(i);
}
}
return max;
}
public static double average(ArrayList<Integer> list) {
int sum = 0;
for (int v : list) {
sum += v;
}
return (double) sum / list.size();
}
public static int countLong(ArrayList<String> words, int n) {
int count = 0;
for (String w : words) {
if (w.length() > n) {
count++;
}
}
return count;
}
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(8);
nums.add(3);
nums.add(10);
ArrayList<String> words = new ArrayList<String>();
words.add("sky");
words.add("forest");
words.add("sea");
System.out.println(maxOf(nums) + " " + average(nums));
System.out.println(countLong(words, 3));
10 7.0
1
Comparing objects: use equals
Elements of a list are objects, so == would compare references. To find out whether a list contains a String, compare with equals.
public static boolean contains(ArrayList<String> list, String target) {
for (String s : list) {
if (s.equals(target)) {
return true;
}
}
return false;
}
ArrayList<String> list = new ArrayList<String>();
list.add("red");
list.add("blue");
System.out.println(contains(list, "blue") + " " + contains(list, "green"));
true false
Algorithms that build a new list
Filtering is easy with a new list: traverse the old one and add what passes. The original is left alone, and no element is skipped.
public static ArrayList<Integer> evensOnly(ArrayList<Integer> list) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int v : list) {
if (v % 2 == 0) {
result.add(v);
}
}
return result;
}
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
ArrayList<Integer> e = evensOnly(a);
System.out.println(e + " " + a);
[2, 4] [1, 2, 3, 4]
Inserting and removing in place
Adding and removing change the order of the list. To move an element, remove it and re-insert it.
public static void moveToFront(ArrayList<String> list, int index) {
String item = list.remove(index);
list.add(0, item);
}
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
moveToFront(list, 2);
System.out.println(list);
[c, a, b]
remove returns the removed element, which is why the one-line String item = list.remove(index) works.
Worked example · find the index of the largest
Return the index of the largest element, or -1 if the list is empty.
public static int indexOfMax(ArrayList<Integer> list) {
if (list.size() == 0) {
return -1;
}
int best = 0;
for (int i = 1; i < list.size(); i++) {
if (list.get(i) > list.get(best)) {
best = i;
}
}
return best;
}
ArrayList<Integer> a = new ArrayList<Integer>();
System.out.println(indexOfMax(a));
a.add(4);
a.add(9);
a.add(9);
a.add(2);
System.out.println(indexOfMax(a));
-1
1
Saving the index of the best element, not its value, lets the method report where it is. The strict > keeps the first of two equal maximums, and the guard keeps get(0) from failing on an empty list.
Worked example · remove duplicates in a row
Remove an element when it equals the one before it, going backward so no element is skipped.
public static void removeRepeats(ArrayList<String> list) {
for (int i = list.size() - 1; i > 0; i--) {
if (list.get(i).equals(list.get(i - 1))) {
list.remove(i);
}
}
}
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("a");
list.add("b");
list.add("b");
list.add("b");
list.add("a");
removeRepeats(list);
System.out.println(list);
[a, b, a]
The loop stops at i > 0 because index 0 has no previous element. Only runs of adjacent equal values are collapsed; the last "a" stays, since it does not touch the first.
The two Strings hold the same characters but are different objects, so == is false. Every algorithm that looks for an object in a list must use equals.
Exam focus
Expect the free-response question on ArrayList data analysis: a method that traverses a list of objects, tests a property, and returns a count, a sum, a new list, or an index. Know the five details: seed from get(0) (or guard an empty list), use equals for objects, size() for the length, a new list for filtering, and a backward loop for removing in place.
Practice
What does moveToFront(list, 1) do to [x, y, z]?
ArrayList<String> list = new ArrayList<String>();
list.add("x");
list.add("y");
list.add("z");
String item = list.remove(1);
list.add(0, item);
System.out.println(list);
Show answer
[y, x, z]. The element at index 1 is removed and re-inserted at the front.
Why does if (list.get(i) == target) risk a bug in a list of Strings?
Show answer
The == operator compares references, so two Strings with the same characters can still be unequal. equals compares the contents.
What does this method return for [2, 5, 8]?
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(5);
list.add(8);
int total = 0;
for (int v : list) {
if (v > 3) {
total += v;
}
}
System.out.println(total);
Show answer
13. The loop adds only the elements greater than 3, which are 5 and 8.
Write the line that returns a new list holding the elements of list that are less than 10 (the traversal is given).
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(12);
list.add(9);
ArrayList<Integer> small = new ArrayList<Integer>();
for (int v : list) {
if (v < 10) {
small.add(v);
}
}
System.out.println(small);
Show answer
The statement is small.add(v); inside the if. The original list is not changed.
Why is the loop in removeRepeats written with i > 0?
Show answer
The loop compares get(i) with get(i - 1). At i = 0 the index -1 would be out of bounds, so the last index checked is 1.
What does indexOfMax return for the list [3, 3], and why?
Show answer
0. The comparison is strict (>), so the second 3 does not replace the best index, and the first largest value is reported.
Some problems involve more than one collection, or more than one String, at a time: do these two lists agree, merge two sorted lists, or compare each character of one word with another. They need a traversal that moves along both structures together. Each step of the loop uses the same index in both, or a separate index for each.
Required content · LO 4.10.A
Learning objective.
4.10.A. Develop code for standard and original algorithms for a particular context or specification that involve ArrayList objects and determine the result of these algorithms.
Essential knowledge.
4.10.A.2. Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.
One index, two structures
When two collections line up element by element, one loop index reaches both. The loop must stay within the shorter one.
public static int matches(ArrayList<String> a, ArrayList<String> b) {
int count = 0;
int n = Math.min(a.size(), b.size());
for (int i = 0; i < n; i++) {
if (a.get(i).equals(b.get(i))) {
count++;
}
}
return count;
}
ArrayList<String> x = new ArrayList<String>();
ArrayList<String> y = new ArrayList<String>();
x.add("a");
x.add("b");
x.add("c");
y.add("a");
y.add("z");
System.out.println(matches(x, y));
1
Math.min keeps the index below both sizes. Using a.size() alone would throw an exception when b is shorter.
Two indexes, one pass each
When the structures are sorted, a merge moves two indexes independently: advance the index of whichever list has the smaller current element.
public static ArrayList<Integer> merge(ArrayList<Integer> a, ArrayList<Integer> b) {
ArrayList<Integer> out = new ArrayList<Integer>();
int i = 0;
int j = 0;
while (i < a.size() && j < b.size()) {
if (a.get(i) <= b.get(j)) {
out.add(a.get(i));
i++;
} else {
out.add(b.get(j));
j++;
}
}
while (i < a.size()) {
out.add(a.get(i));
i++;
}
while (j < b.size()) {
out.add(b.get(j));
j++;
}
return out;
}
ArrayList<Integer> p = new ArrayList<Integer>();
ArrayList<Integer> q = new ArrayList<Integer>();
p.add(1);
p.add(4);
p.add(9);
q.add(2);
q.add(3);
q.add(10);
q.add(11);
System.out.println(merge(p, q));
[1, 2, 3, 4, 9, 10, 11]
The first loop runs until one list is used up, and the two short loops copy whatever remains in the other. This is the merge step that merge sort relies on in Lesson 4.20.
A String and an array together
A String's characters are reached with substring(i, i + 1), so a loop can walk a String and an array in step.
public static int countMatches(String word, String[] letters) {
int count = 0;
for (int i = 0; i < word.length() && i < letters.length; i++) {
if (word.substring(i, i + 1).equals(letters[i])) {
count++;
}
}
return count;
}
Two lists are equal only if they have the same size and every pair of elements is equal.
public static boolean same(ArrayList<Integer> a, ArrayList<Integer> b) {
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
}
ArrayList<Integer> p = new ArrayList<Integer>();
ArrayList<Integer> q = new ArrayList<Integer>();
p.add(7);
q.add(7);
System.out.println(same(p, q));
q.add(8);
System.out.println(same(p, q));
true
false
This is the all pattern from Lesson 4.4: return false at the first failure, and true after everything passed. The size check comes first so the loop never reads past the end of the shorter list.
Worked example · tracing a merge
Trace merge on [1, 4] and [2, 3].
i
j
compare
action
out
0
0
1 <= 2
add 1
[1]
1
0
4 <= 2? no
add 2
[1, 2]
1
1
4 <= 3? no
add 3
[1, 2, 3]
1
2
j reached the end
copy the rest of a
[1, 2, 3, 4]
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(4);
b.add(2);
b.add(3);
System.out.println(merge(a, b));
[1, 2, 3, 4]
Each pass moves exactly one index forward, so the loop runs at most a.size() + b.size() times.
Worked example · two Strings side by side
Count the positions where two words have the same letter.
public static int sameLetters(String a, String b) {
int count = 0;
int n = Math.min(a.length(), b.length());
for (int i = 0; i < n; i++) {
if (a.substring(i, i + 1).equals(b.substring(i, i + 1))) {
count++;
}
}
return count;
}
The words planet and plant agree at positions 0 to 3 (p, l, a, n). At position 4 the letters are e and t, and plant has no position 5, so the loop stops at the shorter length, 5.
Exam focus
Expect a method that takes two lists, arrays, or Strings and loops through them together. Check three details: the loop must stop at the shorter length (Math.min or a compound test), a merge uses two indexes that move separately, and an equality test needs the size check first and equals for objects.
Practice
What does matches return for ["a", "b"] and ["a", "b", "c"]?
ArrayList<String> x = new ArrayList<String>();
ArrayList<String> y = new ArrayList<String>();
x.add("a");
x.add("b");
y.add("a");
y.add("b");
y.add("c");
int c = 0;
for (int i = 0; i < Math.min(x.size(), y.size()); i++) {
if (x.get(i).equals(y.get(i))) {
c++;
}
}
System.out.println(c);
Show answer
2. The loop covers only the first two positions, the shorter length, and both match.
Why is for (int i = 0; i < a.size(); i++) unsafe when it also reads b.get(i)?
Show answer
If b has fewer elements than a, then b.get(i) throws an IndexOutOfBoundsException once i reaches b.size(). The loop must stop at the smaller size.
In a merge, why are there two short loops after the main loop?
Show answer
The main loop ends when either list is used up. One of the lists may still have elements, and since they are sorted and larger than everything copied so far, they are copied to the end of the result.
What does this print?
String a = "bat";
String b = "bad";
int c = 0;
for (int i = 0; i < a.length(); i++) {
if (a.substring(i, i + 1).equals(b.substring(i, i + 1))) {
c++;
}
}
System.out.println(c);
Show answer
2. The first two letters, b and a, match; the last letters t and d do not.
How many comparisons does merge make at most for lists of sizes 3 and 4?
Show answer
At most 7 passes through the loops, since each pass moves one of the two indexes forward and the total number of steps is the sum of the sizes (3 + 4).
In same, why is the size test done before the loop?
Show answer
If the sizes differ, the lists cannot be equal, and a loop over the longer one would read past the end of the shorter one and throw an exception.
A table has rows and columns: a seating chart, a game board, an image of pixels. Java stores one as a 2D array, and the whole idea is that it is an array whose elements are themselves arrays. If you keep that picture in mind, every rule in this lesson follows from what you already know about 1D arrays.
Required content · LO 4.11.A
Learning objective.
4.11.A. Develop code used to represent collections of related data using two-dimensional (2D) array objects.
Essential knowledge.
4.11.A.1. A 2D array is stored as an array of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed. 2D arrays can store either primitive data or object reference data. X EXCLUSION STATEMENT—Nonrectangular 2D array objects are outside the scope of the AP Computer Science A course and exam.
4.11.A.2. When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
4.11.A.3. The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };.
4.11.A.4. The square brackets [row][col] are used to access and modify an element in a 2D array. For the purposes of the exam, when accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.
4.11.A.5. A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index.
4.11.A.6. The number of rows contained in a 2D array can be accessed through the length attribute. The valid row index values for a 2D array are 0 through one less than the number of rows or the length of the array, inclusive. The number of columns contained in a 2D array can be accessed through the length attribute of one of the rows. The valid column index values for a 2D array are 0 through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array named values, the number of rows is values.length and the number of columns is values[0].length. Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException.
An array of arrays
A 2D array is stored as an array of arrays. The size is set when it is created and cannot change. Elements may be primitives or object references. The notation is int[][] grid, and the course convention is that grid[row][col] uses the first index for the row and the second for the column.
Figure 4.2. A 2D array is an array of rows. The first index chooses the row and the second chooses the column; g[r] alone is one whole row.
Creating a 2D array
With new, give the number of rows and the number of columns. Every element starts at the default value for its type. With an initializer list, write one inner list per row.
second is a reference to the actual row, so changing it changes the 2D array. An index outside the valid range throws an ArrayIndexOutOfBoundsException.
int[][] g = new int[2][3];
g[2][0] = 1;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
Worked example · reading a table
A theater stores ticket prices in a 2D array. Rows are sections, columns are seat types.
Always read the first index as the row. The element in row 1, column 2 is the third value of the second row.
Worked example · filling a grid with a pattern
Create a 3 by 4 grid where each element is its row number times its column number.
int[][] t = new int[3][4];
for (int r = 0; r < t.length; r++) {
for (int c = 0; c < t[r].length; c++) {
t[r][c] = r * c;
}
}
System.out.println(t[2][3] + " " + t[1][2] + " " + t[0][3]);
6 2 0
col 0
col 1
col 2
col 3
row 0
0
0
0
0
row 1
0
1
2
3
row 2
0
2
4
6
The outer loop picks a row, the inner loop walks across that row. Lesson 4.13 is entirely about this nested loop.
Worked example · swapping two rows
Because each row is an array reference, swapping two rows is a three-line reference swap.
No element was copied. Only the references stored in the outer array moved, which is why the row is as cheap to swap as a single value.
Exam focus
Expect to create a 2D array with new or an initializer list, to read an element when given the picture of a table, and to answer how many rows and columns it has. Remember: grid.length counts rows and grid[0].length counts columns, the first index is the row, a single index gives a whole row (a 1D array), and the default values are the same as for 1D arrays.
A 1D array needs one loop. A 2D array needs two, one inside the other: the outer loop picks a row and the inner loop walks along it. The order of the two loops decides the order in which the elements are visited, and the exam asks you to trace both.
Required content · LO 4.12.A
Learning objective.
4.12.A. Develop code used to traverse the elements in a 2D array and determine the result of these traversals.
Essential knowledge.
4.12.A.1. Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects. Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, whereas column-major order traversal occurs down each column.
4.12.A.2. The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
Row-major order
Nested iteration statements traverse all, or an ordered sequence of, the elements of a 2D array. Since a 2D array is an array of arrays, the outer loop moves through the rows and the inner loop goes across the columns of the current row. This visits the elements in row-major order: the whole first row, then the whole second row.
int[][] g = { {1, 2, 3}, {4, 5, 6} };
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
System.out.print(g[r][c] + " ");
}
}
1 2 3 4 5 6
The inner bound is g[r].length, the length of the current row, rather than a fixed number.
Column-major order
Swapping the two loops makes the outer loop the column. The traversal then goes down the first column, then the second, and so on. This is column-major order, and it requires the inner bound g.length (rows) and the outer bound g[0].length (columns).
int[][] g = { {1, 2, 3}, {4, 5, 6} };
for (int c = 0; c < g[0].length; c++) {
for (int r = 0; r < g.length; r++) {
System.out.print(g[r][c] + " ");
}
}
1 4 2 5 3 6
Nested enhanced for loops
The outer loop of a nested enhanced for loop traverses the rows, so the outer loop variable must be a 1D array: the type of one row. The inner loop traverses a single row, and its variable has the element type. As always, the variables are copies, so assigning to them does not change the array.
int[][] g = { {1, 2, 3}, {4, 5, 6} };
int total = 0;
for (int[] row : g) {
for (int v : row) {
total += v;
}
}
System.out.println(total);
21
A nested enhanced loop can only do row-major order, and it has no indexes, so it cannot change a primitive element in place.
int[][] g = { {1, 2}, {3, 4} };
for (int[] row : g) {
for (int v : row) {
v = 0;
}
}
System.out.println(g[0][0] + " " + g[1][1]);
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
g[r][c] = 0;
}
}
System.out.println(g[0][0] + " " + g[1][1]);
1 4
0 0
One row, one column, a diagonal
Any ordered sequence of elements counts as a traversal: a single loop can walk one row, one column, or the diagonal.
int[][] g = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int row1 = 0;
for (int c = 0; c < g[1].length; c++) {
row1 += g[1][c];
}
int col2 = 0;
for (int r = 0; r < g.length; r++) {
col2 += g[r][2];
}
int diag = 0;
for (int i = 0; i < g.length; i++) {
diag += g[i][i];
}
System.out.println(row1 + " " + col2 + " " + diag);
15 18 15
Worked example · tracing the traversal order
Which elements are printed, and in what order?
int[][] g = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
for (int r = 0; r < g.length; r++) {
for (int c = r; c < g[r].length; c++) {
System.out.print(g[r][c] + " ");
}
}
r
c values
printed
0
0, 1, 2
1 2 3
1
1, 2
5 6
2
2
9
1 2 3 5 6 9
Starting the inner loop at c = r skips the lower-left part of the grid and visits only the diagonal and everything above it.
Worked example · counting the elements that match
Count the elements of a seating chart (true means taken).
boolean[][] seats = { {true, false, true}, {false, false, true} };
int taken = 0;
for (boolean[] row : seats) {
for (boolean s : row) {
if (s) {
taken++;
}
}
}
System.out.println(taken);
3
The outer variable has type boolean[], one row, and the inner variable has type boolean. If you wrote for (boolean s : seats) the code would not compile.
Worked example · the wrong bound
A programmer swaps the loop bounds in a non-square grid.
int[][] g = new int[2][5];
for (int r = 0; r < g[0].length; r++) {
for (int c = 0; c < g.length; c++) {
g[r][c] = 1;
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
g has 2 rows, but the outer loop runs r up to 4, so g[2][0] fails. The rule: whichever index goes with the row is bounded by g.length, and whichever goes with the column by g[0].length.
Exam focus
Expect nested loops to trace, in row-major and column-major order, and a nested enhanced loop where you must give the type of the outer variable (int[] for an int[][]). Check which index each loop uses, which length bounds it (g.length for rows, g[r].length for columns), and where the inner loop starts. A loop that changes a primitive element needs the indexes.
Practice
What is printed?
int[][] g = { {1, 2}, {3, 4}, {5, 6} };
for (int c = 0; c < g[0].length; c++) {
for (int r = 0; r < g.length; r++) {
System.out.print(g[r][c] + " ");
}
}
Show answer
1 3 5 2 4 6. The outer loop is the column, so each column is read from top to bottom.
What type must the outer loop variable have in a nested enhanced for over String[][] words?
Show answer
String[], because the outer loop gives one row at a time, and each row is a 1D String array.
What is the value of sum after this code?
int[][] g = { {1, 2, 3}, {4, 5, 6} };
int sum = 0;
for (int r = 0; r < g.length; r++) {
sum += g[r][0];
}
System.out.println(sum);
Show answer
5. The loop adds the first element of each row, that is, the whole first column: 1 + 4.
Why does this code leave the grid unchanged?
int[][] g = { {1, 2}, {3, 4} };
for (int[] row : g) {
for (int v : row) {
v = v + 10;
}
}
System.out.println(g[0][0]);
Show answer
The inner variable v is a copy of each element, so adding to it does not change the array. An indexed loop with g[r][c] += 10; would.
Fill in the loop bound: for (int c = 0; c < ______; c++) to go across row r of g.
Show answer
g[r].length, the number of elements in row r.
What does this code print?
int[][] g = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int s = 0;
for (int i = 0; i < g.length; i++) {
s += g[i][g.length - 1 - i];
}
System.out.println(s);
Show answer
15. It adds the other diagonal: g[0][2] + g[1][1] + g[2][0] is 3 + 5 + 7.
The standard algorithms from Lessons 4.5 and 4.10 carry over to a 2D array. The new questions are which elements to include: the whole grid, one row, one column, or some other section. The nested loop from Lesson 4.13 supplies the visiting, and the algorithm is the same accumulator, counter, or comparison that you already know.
The standard 2D algorithms are to determine a minimum or maximum, compute a sum or average, determine if at least one element has a property, determine if all elements have a property, count the elements with a property, and access consecutive pairs, in each case over all the elements or over a designated row, column, or other subsection. There are also algorithms that shift or rotate the elements of a row or column and that reverse the order of a row or column.
Required content · LO 4.13.A
Learning objective.
4.13.A. Develop code for standard and original algorithms for a particular context or specification that involves 2D arrays and determine the result of these algorithms.
Essential knowledge.
4.13.A.1. There are standard algorithms that utilize 2D array traversals to:
determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection
compute a sum or average of all the elements or for a designated row, column, or other subsection
determine if at least one element has a particular property in the entire 2D array or for a designated row, column, or other subsection
determine if all elements of the 2D array or a designated row, column, or other subsection have a particular property
determine the number of elements in the 2D array or in a designated row, column, or other subsection having a particular property
access all consecutive pairs of elements
determine the presence or absence of duplicate elements in the 2D array or in a designated row, column, or other subsection
shift or rotate elements in a row left or right or in a column up or down
reverse the order of the elements in a row or column
Whole grid, one row, one column
public static int sumAll(int[][] g) {
int total = 0;
for (int[] row : g) {
for (int v : row) {
total += v;
}
}
return total;
}
public static int sumRow(int[][] g, int r) {
int total = 0;
for (int c = 0; c < g[r].length; c++) {
total += g[r][c];
}
return total;
}
public static int sumCol(int[][] g, int c) {
int total = 0;
for (int r = 0; r < g.length; r++) {
total += g[r][c];
}
return total;
}
A row loop varies the column index and keeps the row fixed; a column loop varies the row index and keeps the column fixed. A column cannot be passed around the way a row can (g[r] is an array, g[c] would be a row), which is why the column sum needs its own loop.
Maximum, count, and any
public static int maxOf(int[][] g) {
int max = g[0][0];
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
if (g[r][c] > max) {
max = g[r][c];
}
}
}
return max;
}
public static int countNegative(int[][] g) {
int count = 0;
for (int[] row : g) {
for (int v : row) {
if (v < 0) {
count++;
}
}
}
return count;
}
public static boolean rowAllPositive(int[][] g, int r) {
for (int v : g[r]) {
if (v <= 0) {
return false;
}
}
return true;
}
Notice g[r] can be used directly as the array of the enhanced for loop, since a row is a 1D array.
Row-by-row results
Often a program needs one answer per row, such as each row's total. Run the whole inner algorithm inside the outer loop, and reset the accumulator inside the outer loop.
public static int[] rowTotals(int[][] g) {
int[] totals = new int[g.length];
for (int r = 0; r < g.length; r++) {
int sum = 0;
for (int c = 0; c < g[r].length; c++) {
sum += g[r][c];
}
totals[r] = sum;
}
return totals;
}
If int sum = 0; sat before the outer loop, each row's total would include all the rows above it.
Worked example · the accumulator in the wrong place
A programmer declares the accumulator outside the outer loop.
int[][] g = { {1, 2}, {3, 4} };
int[] totals = new int[2];
int sum = 0;
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
sum += g[r][c];
}
totals[r] = sum;
}
System.out.println(totals[0] + " " + totals[1]);
3 10
The second row's total shows 10, not 7, because sum was never reset: it still held the first row's 3. The accumulator is declared inside the outer loop whenever each row needs its own total.
Worked example · the row with the largest sum
Return the index of the row whose elements add up to the most.
public static int bestRow(int[][] g) {
int best = 0;
int bestSum = sumRow(g, 0);
for (int r = 1; r < g.length; r++) {
int s = sumRow(g, r);
if (s > bestSum) {
bestSum = s;
best = r;
}
}
return best;
}
The row sums are 2, 9, and 8, so the answer is row 1. The method reuses sumRow from above, which is how a harder algorithm is built from the standard ones.
Worked example · neighbors in a grid
Count the cells in a row of a grid that are larger than the cell to their left.
public static int risesInRow(int[][] g, int r) {
int count = 0;
for (int c = 1; c < g[r].length; c++) {
if (g[r][c] > g[r][c - 1]) {
count++;
}
}
return count;
}
Starting at column 1 keeps g[r][c - 1] in range. Row 0 rises twice (1 to 3, and 2 to 5); row 1 falls throughout.
Exam focus
Expect a method that takes a 2D array and returns a sum, count, maximum, or a row or column result, and a question about where to put the accumulator. Check which index the inner loop varies (column for a row, row for a column), reset an accumulator for each row inside the outer loop, and make sure any [c - 1] or [r - 1] access starts its loop at 1.
Practice
What does this code print?
int[][] g = { {2, 4}, {6, 8} };
int s = 0;
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
if (r == c) {
s += g[r][c];
}
}
}
System.out.println(s);
Show answer
10. Only the elements where the row and column are equal, g[0][0] and g[1][1], are added: 2 + 8.
Write the loop bound that makes a column sum for column c of g.
Show answer
for (int r = 0; r < g.length; r++), summing g[r][c]. The row index varies and the column is fixed.
Why does the accumulator int sum = 0; belong inside the outer loop in rowTotals?
Show answer
Each row needs its own total starting from 0. Declared outside, the sum would keep growing and include earlier rows.
What is printed?
int[][] g = { {5, 1}, {2, 9}, {7, 3} };
int max = g[0][0];
for (int[] row : g) {
for (int v : row) {
if (v > max) {
max = v;
}
}
}
System.out.println(max);
Show answer
9. The maximum starts as the first element and is replaced whenever a larger value is found.
How many elements does countNegative examine in a 3 by 4 grid?
Show answer
12, because the nested loops visit every element of the 3 rows and 4 columns.
What goes wrong if g[r][c - 1] is read in a loop that starts at c = 0?
Show answer
At c = 0 the index c - 1 is -1, which throws an ArrayIndexOutOfBoundsException. The loop must start at c = 1.
How does a program find a value in a collection? Searching is one of the two jobs (the other is sorting, next lesson) that the course analyzes as named algorithms. The simplest is linear search, and it is the one that always works, whatever order the data is in.
Required content · LO 4.14.A
Learning objective.
4.14.A. Develop code used for linear search algorithms to search for specific information in a collection and determine the results of executing a search.
Essential knowledge.
4.14.A.1. Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
4.14.A.2. When applying linear search algorithms to 2D arrays, each row must be accessed then linear search applied to each row of the 2D array.
The algorithm
A linear search checks each element in order until the desired value is found or all of the elements have been checked. It can begin at the start of the array or list, or at any other position, and it can run forward or backward. A search through an array of primitives compares with ==; a search through objects compares with equals.
public static int linearSearch(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return i;
}
}
return -1;
}
The method returns the index of the first match, and -1 when the target is not there. Because it returns inside the loop, it stops as soon as it succeeds. The return -1 goes after the loop, never inside it; otherwise the method would give up after the first element.
Searching a list or Strings
For an ArrayList, use get, size, and equals.
public static int find(ArrayList<String> list, String target) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(target)) {
return i;
}
}
return -1;
}
To search a 2D array, each row must be accessed, and then a linear search is applied to each row.
public static boolean contains(int[][] g, int target) {
for (int[] row : g) {
for (int v : row) {
if (v == target) {
return true;
}
}
}
return false;
}
public static int[] locate(int[][] g, int target) {
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
if (g[r][c] == target) {
return new int[] {r, c};
}
}
}
return null;
}
Linear search takes more steps for a longer collection. In the best case the target is the first element (1 comparison). In the worst case it is the last element or missing, and every element is compared. For an array of length n, the worst case is n comparisons.
Worked example · counting comparisons
How many elements does a linear search for each target look at in {4, 8, 15, 16, 23, 42}?
Target
Found at index
Comparisons
4
0
1
16
3
4
42
5
6
10
not found
6
The number of comparisons is the index plus 1 for a successful search, and the whole length for an unsuccessful one. The data is sorted here, but linear search does not use that fact, so it never does better than this.
Worked example · searching backward and from a start index
Find the last occurrence of a target.
public static int lastIndex(int[] a, int target) {
for (int i = a.length - 1; i >= 0; i--) {
if (a[i] == target) {
return i;
}
}
return -1;
}
Running the same loop backward finds the last match. A search that starts partway, such as int i = start, finds the first match at or after start, which is how a program finds every occurrence by calling the search again after each hit.
Worked example · a search that counts as it goes
Count how many Strings in a list equal a target, and report whether any do.
public static int countOf(ArrayList<String> list, String target) {
int count = 0;
for (String s : list) {
if (s.equals(target)) {
count++;
}
}
return count;
}
ArrayList<String> w = new ArrayList<String>();
w.add("a");
w.add("b");
w.add("a");
System.out.println(countOf(w, "a") + " " + (countOf(w, "z") > 0));
2 false
A count does not stop early, since it must examine every element. A search that only asks is it there? can stop at the first hit.
Exam focus
Expect to complete or trace a linear search on an array, an ArrayList, or a 2D array, and to say how many elements are examined in the best and worst case. Remember: return the index inside the loop and -1 after it, use equals for objects, and apply the search to each row for a 2D array. Linear search works on unsorted data.
Practice
What does linearSearch(new int[] {6, 2, 6}, 6) return?
int[] a = {6, 2, 6};
int found = -1;
for (int i = 0; i < a.length && found == -1; i++) {
if (a[i] == 6) {
found = i;
}
}
System.out.println(found);
Show answer
0. The search stops at the first match, at index 0, and does not report the second 6.
In the worst case, how many elements does a linear search examine in an array of 500 elements?
Show answer
500: when the target is the last element or is not present, every element is examined.
A programmer writes return -1; inside the loop, in an else after the comparison. What is wrong?
Show answer
The method returns -1 after checking only the first element, if it does not match. The return -1; must come after the loop, once every element has been checked.
What does this code print?
int[][] g = { {5, 6}, {7, 8} };
int count = 0;
for (int[] row : g) {
for (int v : row) {
if (v > 5) {
count++;
}
}
}
System.out.println(count);
Show answer
3. The values 6, 7, and 8 are greater than 5.
Why is list.get(i) == target the wrong test in a search of an ArrayList<String>?
Show answer
The == operator compares references, not contents. list.get(i).equals(target) compares the characters of the Strings.
Does linear search require the data to be sorted?
Show answer
No. It checks the elements one by one and works on data in any order, which is why it is the general-purpose search.
Searching is much faster on sorted data, and many programs sort first. The course covers three named sorting algorithms: selection sort and insertion sort here, and merge sort in Lesson 4.20. Selection sort and insertion sort are iterative, which means they use loops, and both work on arrays or ArrayLists. You are expected to trace them, read their code, and describe what each pass does.
Required content · LO 4.15.A
Learning objective.
4.15.A. Determine the result of executing each step of sorting algorithms to sort the elements of a collection.
Essential knowledge.
4.15.A.1. Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.
4.15.A.2. Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
The idea
Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct position in the sorted portion. That position is also its final position: once an element has been placed, it never moves again.
Figure 4.3. Each pass selects the smallest value in the unsorted part and swaps it to the end of the sorted part (shaded). Sorted values never move again; the two cells swapped in a pass are marked.
The code
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
The outer loop i marks the boundary: everything left of i is sorted and in its final place. The inner loop looks through the rest (i onward) for the index of the smallest value, then one swap places it. The outer loop stops at a.length - 1 because when only one element is left it must already be in place.
Pass 2 swapped the element with itself, which is allowed. The bold part is the sorted portion; after pass k the first k elements are final.
On an ArrayList or Strings
For a list, replace the brackets with get and set. For Strings, compare with compareTo (a negative result means the first String comes first alphabetically).
public static void selectionSortWords(ArrayList<String> w) {
for (int i = 0; i < w.size() - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < w.size(); j++) {
if (w.get(j).compareTo(w.get(minIndex)) < 0) {
minIndex = j;
}
}
String temp = w.get(i);
w.set(i, w.get(minIndex));
w.set(minIndex, temp);
}
}
ArrayList<String> w = new ArrayList<String>();
w.add("pear");
w.add("apple");
w.add("fig");
selectionSortWords(w);
System.out.println(w);
[apple, fig, pear]
How much work?
The inner loop does n - 1 comparisons on the first pass, n - 2 on the second, and so on. The number of comparisons does not depend on the order of the data: a sorted array and a reversed array both take the same number. Only the number of swaps (at most n - 1) can differ.
Worked example · counting comparisons
How many comparisons does selection sort make on an array of 6 elements?
Pass
comparisons
1
5
2
4
3
3
4
2
5
1
The total is 5 + 4 + 3 + 2 + 1 = 15, no matter what the data look like. For n elements it is (n - 1) + (n - 2) + ... + 1.
Worked example · sorting in descending order
Change the algorithm to select the largest element each pass.
public static void selectionSortDesc(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] > a[maxIndex]) {
maxIndex = j;
}
}
int temp = a[i];
a[i] = a[maxIndex];
a[maxIndex] = temp;
}
}
Only the comparison and the variable name changed. Reading the comparison operator and the variable that is tracked tells you the sort order.
Worked example · the array after two passes
Trace {4, 8, 3, 1, 6} and give the array after two passes.
After pass
array
start
4 8 3 1 6
1 (smallest is 1)
1 8 3 4 6
2 (smallest of the rest is 3)
1 3 8 4 6
The answer is 1 3 8 4 6. The unsorted part is not in any particular order, only the sorted part is. Questions often ask for exactly this partial state.
Exam focus
Expect to give the array after a certain number of passes of selection sort, to say how many times a statement executes, or to choose which line makes a descending sort. Know that each pass places one element in its final position, that the outer loop runs length - 1 times, that the number of comparisons does not depend on the initial order, and that the inner loop starts at i + 1.
Practice
What is the array after the first pass of selection sort on {6, 3, 8, 2, 5}?
int[] a = {6, 3, 8, 2, 5};
int m = 0;
for (int j = 1; j < a.length; j++) {
if (a[j] < a[m]) {
m = j;
}
}
int t = a[0];
a[0] = a[m];
a[m] = t;
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4]);
Show answer
2 3 8 6 5. The smallest value 2 (index 3) is swapped with the element at index 0.
How many comparisons does selection sort make on 5 elements?
Show answer
10: 4 + 3 + 2 + 1, regardless of the order of the data.
Why does the outer loop of selection sort stop at a.length - 1?
Show answer
After length - 1 elements are in their final places, the last element is automatically in place, so another pass would do nothing.
Which change makes the sort descending?
Show answer
Selecting the largest element in each pass: tracking the index with a[j] > a[maxIndex] instead of the smallest.
After two passes on {9, 4, 7, 1}, what is the array?
int[] a = {9, 4, 7, 1};
for (int i = 0; i < 2; i++) {
int m = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[m]) {
m = j;
}
}
int t = a[i];
a[i] = a[m];
a[m] = t;
}
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3]);
Show answer
1 4 7 9. Pass 1 swaps 9 and 1 to give 1 4 7 9; pass 2 finds that 4 is already the smallest of the rest, so nothing changes.
Does selection sort move an element that is already in its final position?
Show answer
Not to a different place. When the smallest element of the unsorted part is already at index i, it is swapped with itself, and once placed, an element never moves again.
Selection sort picks an element and puts it in its final place. Insertion sort works the other way around: it takes the next element and slides it into the right spot among the elements already sorted, the way many people sort a hand of playing cards. The elements it places are sorted relative to each other but not necessarily in their final positions, because a later, smaller element may push them along.
Required content · LO 4.15.A
Learning objective.
4.15.A. Determine the result of executing each step of sorting algorithms to sort the elements of a collection.
Essential knowledge.
4.15.A.1. Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.
4.15.A.3. Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.
The idea
Insertion sort inserts an element from the unsorted portion of the list into its correct (but not necessarily final) position in the sorted portion, by shifting the elements of the sorted portion to make room for it.
The code
public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int temp = a[i];
int j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
The outer loop starts at index 1, since a one-element portion is already sorted. In each pass temp holds the element being inserted, the while loop shifts every larger element one place right, and the final line drops temp into the gap. The test j >= 0 comes first so that a[j] is never read at index -1.
After pass 3 the elements 2 5 9 were not in their final spots: inserting 1 pushed all of them one place to the right. That is the difference from selection sort.
Best and worst case
If the array is already sorted, every element finds that nothing needs to move, so the while loop stops at once and insertion sort makes only about n - 1 comparisons. If the array is in reverse order, every element must travel all the way to the front, which takes the most comparisons and shifts. Selection sort does the same number of comparisons either way; insertion sort does not.
public static int countShifts(int[] a) {
int shifts = 0;
for (int i = 1; i < a.length; i++) {
int temp = a[i];
int j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
shifts++;
}
a[j + 1] = temp;
}
return shifts;
}
The same algorithm works on a list, with get and set (or add and remove). Because the shifting is the point, it is common to see it as list.remove(i) followed by list.add(position, value).
public static void insertionSortList(ArrayList<Integer> list) {
for (int i = 1; i < list.size(); i++) {
int temp = list.get(i);
int j = i - 1;
while (j >= 0 && list.get(j) > temp) {
list.set(j + 1, list.get(j));
j--;
}
list.set(j + 1, temp);
}
}
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(1);
list.add(2);
insertionSortList(list);
System.out.println(list);
[1, 2, 3]
Worked example · the array after two passes
Trace {4, 8, 3, 1, 6} and give the array after two passes of insertion sort, then compare with selection sort.
After pass
array
start
4 8 3 1 6
1 (insert 8)
4 8 3 1 6
2 (insert 3, shifts 8 and 4)
3 4 8 1 6
The answer is 3 4 8 1 6. After two passes of selection sort the same array is 1 3 8 4 6 (Lesson 4.16). Both leave part of the array sorted, but different parts: selection sort's sorted portion holds the smallest values, while insertion sort's holds the first values, sorted among themselves.
Worked example · identifying the sort from a partial result
After some passes, {7, 2, 9, 4, 1} becomes {2, 7, 9, 4, 1}. Which sort could have done this in one pass?
An insertion sort pass inserted 2 before 7. One pass of selection sort would have swapped the smallest value, 1, into index 0, giving 1 2 9 4 7. The first two elements being in order while the rest is untouched points to insertion sort.
Worked example · the effect of swapping the while conditions
What happens if the while test is written a[j] > temp && j >= 0?
int[] a = {3, 1};
int temp = a[1];
int j = 0;
while (a[j] > temp && j >= 0) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
After shifting 3, j becomes -1, and the test reads a[-1] before it checks j >= 0. The short-circuit rule (Lesson 2.5) only protects an index if the range check comes first.
Exam focus
Expect to give the array after a number of passes, to tell selection from insertion sort by a partial result, and to compare the amount of work for sorted and reversed data. Remember: insertion sort starts at index 1, shifts larger elements right and then places the element, is fastest on sorted data, and checks j >= 0 before a[j]. After a pass, the sorted portion is sorted but not necessarily final.
Practice
What is the array after two passes of insertion sort on {5, 3, 8, 1}?
int[] a = {5, 3, 8, 1};
for (int i = 1; i <= 2; i++) {
int temp = a[i];
int j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3]);
Show answer
3 5 8 1. Pass 1 inserts 3 before 5, and pass 2 finds that 8 is already larger than 5, so nothing moves.
How many shifts does insertion sort make on an array that is already sorted?
Show answer
None. Each element is at least as large as the one before it, so the while loop stops immediately.
Which sort does the same number of comparisons whatever order the data is in?
Show answer
Selection sort. Insertion sort does fewer comparisons on sorted data and the most on reversed data.
Why must the test be j >= 0 && a[j] > temp in that order?
Show answer
If j is -1, evaluating a[j] first would throw an ArrayIndexOutOfBoundsException. With j >= 0 first, the && stops before reading a[j].
After one pass of a sort on {6, 2, 9, 4, 1} the array is {2, 6, 9, 4, 1}. Could it be selection sort?
Show answer
No. One pass of selection sort would swap the smallest value in the whole array, 1, into index 0, giving 1 2 9 4 6. The result 2 6 9 4 1 is what one pass of insertion sort gives, because it only inserted the second element among the first two.
What does the last line of the outer loop, a[j + 1] = temp;, do?
Show answer
It places the element being inserted into the gap that the shifting opened up.
Every loop you have written so far repeats by going back to the top. There is a second way for a program to repeat: a method can call itself. This is recursion, and the exam asks you to read it and trace it. The course states plainly that writing recursive code is outside its scope, so this lesson is about understanding recursive methods that are shown to you, tracing what they return, and recognizing their parts.
Required content · LO 4.16.A
Learning objective.
4.16.A. Determine the result of calling recursive methods.
Essential knowledge.
4.16.A.1. A recursive method is a method that calls itself. Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition.
4.16.A.2. Each recursive call has its own set of local variables, including the parameters. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
4.16.A.3. Any recursive solution can be replicated through the use of an iterative approach and vice versa. X EXCLUSION STATEMENT—Writing recursive code is outside the scope of the AP Computer Science A course and exam.
The two parts
A recursive method is a method that calls itself. It must have at least one base case, a situation where it returns an answer without calling itself, which halts the recursion, and at least one recursive call, where it calls itself on a smaller or simpler version of the problem. Recursion is another form of repetition.
public static int sumTo(int n) {
if (n == 1) {
return 1;
}
return n + sumTo(n - 1);
}
System.out.println(sumTo(4));
10
The base case is n == 1. The recursive call sumTo(n - 1) has a smaller argument, so each call moves closer to the base case. A recursive method whose calls never reach the base case runs until memory for calls is exhausted, which throws a StackOverflowError.
public static int broken(int n) {
return n + broken(n - 1);
}
System.out.println(broken(3));
Exception in thread "main" java.lang.StackOverflowError
Each call has its own variables
Each recursive call has its own set of local variables, including the parameters. The value of a parameter records the progress of the process, much as a loop variable records the progress of a loop.
Figure 4.4. Each recursive call is added on top with its own value of n. The base case sumTo(1) answers first, and every waiting call then finishes in turn.
To trace sumTo(4), list the calls as they are made and the values as they come back:
Call
Needs
Returns
sumTo(4)
4 + sumTo(3)
4 + 6 = 10
sumTo(3)
3 + sumTo(2)
3 + 3 = 6
sumTo(2)
2 + sumTo(1)
2 + 1 = 3
sumTo(1)
base case
1
The calls go down to the base case, and then the results come back up, each call finishing only after the call it made has returned.
Work before and after the call
Where a statement sits relative to the recursive call changes the output.
In countdown the printing happens on the way down. In countup the print waits until the deeper call returns, so the output appears on the way up, in the opposite order.
Recursion and loops
Any recursive solution can be replicated with iteration, and any iterative solution with recursion.
public static int sumToLoop(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
System.out.println(sumToLoop(4));
10
The loop and the recursive method give the same value; the loop variable i plays the part that the parameter n played.
Worked example · tracing a recursive method
What does mystery(3) return?
public static int mystery(int n) {
if (n <= 1) {
return 1;
}
return n * mystery(n - 1);
}
Working back up: mystery(2) is 2 * 1 = 2, then mystery(3) is 3 * 2 = 6. The method computes the factorial, and mystery(5) is 5 * 4 * 3 * 2 * 1 = 120.
Worked example · a recursive call on a String
What does this method do to "abc"?
public static String flip(String s) {
if (s.length() <= 1) {
return s;
}
return flip(s.substring(1)) + s.substring(0, 1);
}
System.out.println(flip("abc"));
cba
Call
Needs
Returns
flip("abc")
flip("bc") + "a"
"cb" + "a"
flip("bc")
flip("c") + "b"
"c" + "b"
flip("c")
base case
"c"
The parameter s gets one character shorter each call, and the first character is placed after the result of the deeper call, which reverses the String.
Worked example · finding the base case and the progress
Name the base case, the recursive call, and how the parameter shows progress.
public static int digits(int n) {
if (n < 10) {
return 1;
}
return 1 + digits(n / 10);
}
System.out.println(digits(4096));
4
The base case is n < 10, a one-digit number, which returns 1. The recursive call is digits(n / 10), and integer division by 10 drops the last digit, so n shrinks: 4096, 409, 40, 4. That is four calls, hence the answer 4.
Exam focus
Expect to be given a recursive method and asked what it returns or prints for a certain argument, to identify the base case or the recursive call, or to say what happens if the base case is missing. You will not be asked to write one. Trace by listing the calls going down and the returns coming back up, and watch where a print sits relative to the recursive call.
Practice
What does sumTo(5) return?
public static int sumTo(int n) {
if (n == 1) {
return 1;
}
return n + sumTo(n - 1);
}
System.out.println(sumTo(5));
Show answer
15, that is 5 + 4 + 3 + 2 + 1.
What is the base case of digits(int n) above, and why is it needed?
Show answer
The base case is n < 10. It stops the recursion; without it the method would keep calling itself and throw a StackOverflowError.
What is printed?
public static void show(int n) {
if (n > 0) {
show(n - 1);
System.out.print(n + " ");
}
}
show(3);
Show answer
1 2 3. The print comes after the recursive call, so the deepest call prints first.
What does flip("dog") return?
public static String flip(String s) {
if (s.length() <= 1) {
return s;
}
return flip(s.substring(1)) + s.substring(0, 1);
}
System.out.println(flip("dog"));
Show answer
"god": flip("og") + "d" is ("g" + "o") + "d".
Why does each recursive call have its own value of the parameter n?
Show answer
Every call is a separate execution of the method with its own local variables, so the call sumTo(3) and the call sumTo(2) each keep their own n.
A recursive method calls itself with the same argument it received. What happens?
Show answer
The argument never moves toward the base case, so the calls never stop and the program throws a StackOverflowError.
Recursion can do the job of a loop on a String, an array, or an ArrayList: handle one element, then call itself on the rest. It can also do something loops do not do naturally, cut the problem in half each time, which is the idea behind binary search. As in Lesson 4.18, your job is to read and trace recursive methods, not to write them.
Required content · LO 4.17.A, LO 4.17.B, LO 4.17.C
Learning objectives.
4.17.A. Determine the result of executing recursive algorithms that use strings or collections.
4.17.B. Determine the result of each iteration of a binary search algorithm used to search for information in a collection.
4.17.C. Determine the result of each iteration of the merge sort algorithm when used to sort a collection.
Essential knowledge.
4.17.A.1. Recursion can be used to traverse String objects, arrays, and ArrayList objects.
4.17.B.1. Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each recursive call until the desired value is found or all elements have been eliminated.
4.17.B.2. Binary search is typically more efficient than linear search. Outside the course: Search algorithms other than linear and binary search are outside the scope of the AP Computer Science A course and exam.
4.17.B.3. The binary search algorithm can be written either iteratively or recursively.
Recursive traversal
To traverse a String recursively, handle the first character and recurse on the rest. To traverse an array, pass the index along as a parameter. The index parameter takes the place of a loop variable.
public static int countA(String s) {
if (s.length() == 0) {
return 0;
}
if (s.substring(0, 1).equals("a")) {
return 1 + countA(s.substring(1));
}
return countA(s.substring(1));
}
public static int sumFrom(int[] a, int i) {
if (i == a.length) {
return 0;
}
return a[i] + sumFrom(a, i + 1);
}
int[] data = {4, 7, 1};
System.out.println(countA("banana"));
System.out.println(sumFrom(data, 0));
3
12
The base case is the empty String, or an index equal to the length: nothing is left to examine. The first call to sumFrom passes 0, and each call moves the index forward by 1.
Binary search
Linear search checks element after element. If the data is sorted, a faster method exists: binary search starts at the middle of the sorted array or list and eliminates half of it with each step, until the value is found or no elements remain. The data must be in sorted order for it to work, and it is typically more efficient than linear search.
Figure 4.5. Binary search looks at the middle cell (highlighted), then discards half of the remaining range (gray). Searching for 23 takes two looks, where a linear search would take six.
Here is the algorithm written recursively. The parameters low and high mark the part of the array that is still possible.
public static int binarySearch(int[] a, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (a[mid] == target) {
return mid;
}
if (a[mid] < target) {
return binarySearch(a, target, mid + 1, high);
}
return binarySearch(a, target, low, mid - 1);
}
Each step discards half of the remaining elements. An array of 1,000 elements takes at most 10 comparisons, because 1,000 halves to 1 in 10 steps. An array of about a million takes at most 20. A linear search of a million elements could take a million.
Worked example · tracing a binary search
Search for 23 in {2, 5, 8, 12, 16, 23, 38} (indexes 0 to 6).
Step
low
high
mid
a[mid]
Decision
1
0
6
3
12
12 < 23, search right: low = 4
2
4
6
5
23
found at index 5
Two comparisons found the value; a linear search would have used six. For the missing target 7, the ranges narrow as 0 to 6, then 0 to 2, then 0 to 0, then 1 to 0, which is empty, and the answer is -1.
Worked example · binary search on a list of Strings
Strings are compared with compareTo, and the list must be sorted.
public static int searchWords(ArrayList<String> w, String target) {
int low = 0;
int high = w.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
int cmp = w.get(mid).compareTo(target);
if (cmp == 0) {
return mid;
}
if (cmp < 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
ArrayList<String> w = new ArrayList<String>();
w.add("ant");
w.add("bee");
w.add("cat");
w.add("dog");
System.out.println(searchWords(w, "cat") + " " + searchWords(w, "eel"));
2 -1
A negative compareTo result means the middle word comes before the target alphabetically, so the target must be in the upper half.
Worked example · the unsorted trap
Binary search on data that is not sorted can miss a value that is present.
The value 1 is at index 4, but the first middle element is 7, which is larger than 1, so the search discards the right half and never sees it. The algorithm's reasoning ("everything to the right is larger") is true only for sorted data.
Exam focus
Expect to trace a binary search by listing low, mid, and high, to say how many elements are examined, to identify which half is eliminated, and to state the requirement that the data be sorted. Know that binary search is typically more efficient than linear search, that it can be written with recursion or a loop, and that a recursive traversal of a String or array has a base case when nothing is left.
Practice
What does sumFrom(a, 0) return for {3, 5}?
public static int sumFrom(int[] a, int i) {
if (i == a.length) {
return 0;
}
return a[i] + sumFrom(a, i + 1);
}
System.out.println(sumFrom(new int[] {3, 5}, 0));
Show answer
8. The calls add 3 + 5 + 0, where the 0 comes from the base case i == a.length.
What precondition must the data meet for binary search?
Show answer
The array or list must be in sorted order.
How many elements does a binary search examine, at most, in a sorted array of 100 elements (to the nearest whole number of halvings)?
Show answer
At most 7, since 100 halves to 1 in 7 steps (100, 50, 25, 12, 6, 3, 1).
In binarySearch, what does the base case low > high mean?
Show answer
No elements remain to be examined, so the target is not in the array and the method returns -1.
Which element does the first step of a binary search on {2, 5, 8, 12, 16} examine?
int[] a = {2, 5, 8, 12, 16};
int mid = (0 + a.length - 1) / 2;
System.out.println(a[mid]);
Show answer
The middle element, 8, at index 2.
After the first step of searching for 16 in that array, which half remains?
Show answer
The upper half: 8 is less than 16, so the search continues with indexes 3 to 4 (low = mid + 1).
Selection sort and insertion sort use loops, and for large data they are slow. Merge sort uses recursion to do something smarter: split the array in half, sort each half the same way, then merge two sorted halves into one. It is the third and last sorting algorithm in the course. As with the other recursive lessons, you are asked to trace it and explain it, and the code is given to you.
Required content · LO 4.17.A, LO 4.17.B, LO 4.17.C
Learning objectives.
4.17.A. Determine the result of executing recursive algorithms that use strings or collections.
4.17.B. Determine the result of each iteration of a binary search algorithm used to search for information in a collection.
4.17.C. Determine the result of each iteration of the merge sort algorithm when used to sort a collection.
Essential knowledge.
4.17.C.1. Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList. Outside the course: Sorting algorithms other than selection, insertion, and merge sort are outside the scope of the AP Computer Science A course and exam.
4.17.C.2. Merge sort repeatedly divides an array into smaller subarrays until each subarray is one element and then recursively merges the sorted subarrays back together in sorted order to form the final sorted array.
The idea
Merge sort repeatedly divides an array into smaller subarrays until each subarray has one element, and then recursively merges the sorted subarrays back together, in sorted order, to form the final sorted array. A one-element array is already sorted, which is the base case.
Figure 4.6. Merge sort splits the array down to single elements, which are already sorted, then merges neighboring sorted pieces back up into one sorted array.
The merge step
Merging two sorted halves is the same two-index merge from Lesson 4.11: compare the front elements and take the smaller.
The code
public static void mergeSort(int[] a) {
sort(a, 0, a.length - 1);
}
private static void sort(int[] a, int low, int high) {
if (low >= high) {
return;
}
int mid = (low + high) / 2;
sort(a, low, mid);
sort(a, mid + 1, high);
merge(a, low, mid, high);
}
private static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
if (a[i] <= a[j]) {
temp[k] = a[i];
i++;
} else {
temp[k] = a[j];
j++;
}
k++;
}
while (i <= mid) {
temp[k] = a[i];
i++;
k++;
}
while (j <= high) {
temp[k] = a[j];
j++;
k++;
}
for (int m = 0; m < temp.length; m++) {
a[low + m] = temp[m];
}
}
The method sort has a base case (low >= high: zero or one element), two recursive calls, one for each half, and then the merge. The merge uses a temporary array and copies the result back, so merge sort needs extra memory proportional to the array size, which selection and insertion sort do not.
Tracing the divide and merge
For {5, 2, 8, 1} the array is split until single elements remain, and then merged back:
Stage
Subarrays
divide
[5, 2, 8, 1]
divide
[5, 2] and [8, 1]
divide
[5][2][8][1]
merge
[2, 5] and [1, 8]
merge
[1, 2, 5, 8]
The order of the work matters: the left half is sorted completely, then the right half, and only then are they merged.
How much faster?
Each level of splitting halves the size, so an array of n elements is split about log base 2 of n times, and merging each level touches all n elements. For 1,024 elements that is about 10 levels of 1,024 steps, roughly 10,000 steps, while selection sort makes about half a million comparisons. Merge sort is much faster for large arrays, and its work does not depend on the starting order.
Worked example · counting the levels
How many times can an array of 16 elements be halved before the pieces have 1 element?
Level
Number of subarrays
Size of each
0
1
16
1
2
8
2
4
4
3
8
2
4
16
1
There are 4 levels of dividing. Merging goes back up the same 4 levels, and each level of merging handles all 16 elements once, for a total of about 4 times 16 = 64 steps.
Worked example · one merge
Merge the sorted halves [3, 9] and [1, 7, 10].
i points to
j points to
take
result
3
1
1
[1]
3
7
3
[1, 3]
9
7
7
[1, 3, 7]
9
10
9
[1, 3, 7, 9]
(left done)
10
10
[1, 3, 7, 9, 10]
Once the left half is used up, the rest of the right half is copied. The merge works only because each half is already sorted, which is why the recursive calls come first.
Worked example · choosing the right sort
For each situation, which sort fits best?
Situation
Best choice
Why
8 elements, almost sorted
insertion sort
few shifts on nearly sorted data
100,000 elements, random order
merge sort
far fewer steps than the two loop sorts
memory for a copy is not available
selection or insertion sort
they sort in place with no temporary array
must be told the exact number of comparisons in advance
selection sort
its count does not depend on the data
There is no single best sort. The course expects you to match the algorithm to the situation using these properties.
Exam focus
Expect to describe merge sort as divide, sort each half recursively, then merge; to trace the subarrays after a given number of divisions or merges; and to compare it with selection and insertion sort (faster for large data, needs extra memory, base case is one element). You will not write the code, but you should read the structure: base case, two recursive calls, then the merge.
Practice
What is the base case of merge sort?
Show answer
A subarray with zero or one element, which is already sorted, so no more splitting is needed.
What are the three steps of merge sort on an array?
Show answer
Divide the array into two halves, recursively sort each half, then merge the two sorted halves into one sorted array.
[2, 4, 5, 6, 9]: at each step the smaller front element is taken.
How many levels of splitting does an array of 8 elements need to reach single elements?
Show answer
3 levels: 8 splits to 4, then 2, then 1.
Name one advantage and one disadvantage of merge sort compared with insertion sort.
Show answer
Advantage: it is much faster on large arrays, and its work does not depend on the starting order. Disadvantage: it needs a temporary array, so it uses extra memory, and it is more complex.
Why must both halves be sorted before the merge step?
Show answer
The merge only compares the front elements of each half and takes the smaller. That gives a correct sorted result only if each half is already in order.
Unit 4 review · 10 multiple-choice
Unit 4 review: Data Collections
Ten exam-style questions on the unit that carries the most weight on the exam (the ethics of collecting data, arrays and their traversals, file parsing, wrapper classes,
ArrayList, 2D grids, searching and sorting, and recursion) with every stated
output taken from a real run of the stimulus.
Multiple choice
A district's attendance app records who was present each day. For every student it
stores the name, the student ID, the home address, a photograph, and the GPS position of
the phone at the moment the student signs in. The sign-in itself is what marks a student
present; the GPS position has never been used for anything else. The team wants to reduce
the harm a future data breach could do, without changing what the app is for.
Which change does the most to reduce that harm?
Shortening how long data is kept genuinely helps, and a retention limit is
worth having. But the app still gathers a year of location history on every student, so a
breach next week exposes everything collected since last year.
Access control protects data from people who should not see it; it does
nothing about a stolen database, a misconfigured backup, or a subpoena. Adding a password
leaves the same pile of sensitive data sitting there.
Correct. This is data minimization: collect only what the stated purpose
requires. Presence is already established by the sign-in, so the location adds nothing to
the purpose while adding a daily movement trail for every student, and data that was
never collected cannot leak, be subpoenaed, or be repurposed later.
Removing names sounds like anonymizing, but the record still carries a home
address and a photograph, either of which identifies the student immediately. Swapping an
identifier for another identifier is not the same as collecting less.
int[] scores = {4, 7, 2, 9};
for (int s : scores) {
s = s * 2;
}
scores[scores.length - 1] = 0;
for (int v : scores) {
System.out.print(v + " ");
}
What is printed as a result of executing the code segment?
This assumes the first loop doubled the array and the assignment then
changed the last element. Only the second half is true: an enhanced for loop hands you a
copy of each element, so writing to s never reaches the array.
This doubles the array and then loses the last assignment, which is
backwards on both counts. The enhanced loop changes nothing, and the indexed write does
take effect: scores.length - 1 is 3, a legal index, while
scores[scores.length] is the one that would throw.
This has the enhanced loop right but misses the assignment.
scores[scores.length - 1] = 0; is an ordinary indexed write to element 3, and
an indexed write is exactly what the enhanced loop cannot do.
Correct. The first loop is decided on its very first pass:
s = s * 2; writes 8 into a copy that is thrown away when the pass ends, and
four passes later the array still holds 4, 7, 2, 9. The indexed assignment does change
the array, and scores.length - 1 is 3, the last legal index, so the final
element becomes 0.
public static int indexOfMax(int[] values) {
int best = values[0];
int bestIndex = 0;
for (int i = 1; i < values.length; i++) {
if (values[i] >= best) { // line 5
best = values[i];
bestIndex = i;
}
}
return bestIndex;
}
The method is intended to return the smallest index at which the largest
value occurs, but on {12, 47, 31, 47, 9} it returns 3. Which of the following
replacements for line 5 makes the method work as intended for all arrays of length at least
one?
This spells the champion differently but keeps the >=, so a
later equal value still displaces the earlier one. Run on the same array it returns 3
again: the second 47, not the first.
Reversing the comparison turns the method into a minimum finder. On the
same array it returns 4, the index of 9, because the only element that ever beats the
running value under this test is a smaller one.
Correct. Index 3 is where the answer is decided: values[3] is
47 and best is already 47, so >= is true and the index moves,
while a strict > is false and the first winner keeps the title. The method
then returns 1. Match the operator to the sentence: > keeps the first
maximum, >= keeps the last.
Comparing against values[0] forever compares against the first
element instead of the running maximum, so every element larger than 12 overwrites
bestIndex and the method returns 3, the last such index.
String[] lines = {"Elm St,18", "", "Oak Ave,22", "Pine Rd,31"};
int count = 0;
int total = 0;
for (int i = 0; i < lines.length; i++) {
int comma = lines[i].indexOf(",");
if (comma >= 0) {
total += Integer.parseInt(lines[i].substring(comma + 1));
count++;
}
}
System.out.println(count + " " + total + " " + total / count);
What is printed as a result of executing the code segment?
This counts the blank line as a record. On the empty string
indexOf(",") returns −1, the guard comma >= 0 is false, and
neither total nor count is touched, which is exactly the job
that one test is doing.
The first two numbers are right, but the third is not a
double. Both total and count are
int, so total / count is integer division, decided entirely by
the operand types and not by what is printed.
Correct. The second pass is where it is settled: the blank line is skipped,
so three records contribute 18 + 22 + 31 = 71, and 71 / 3 is integer
division, which truncates toward zero to 23 rather than rounding. Casting one operand, (double) total / count, is what would give 23.666666666666668.
24 is what you get by rounding 23.666… to the nearest whole number. Integer
division never rounds; it discards the fractional part. Rounding half up takes the
(int) (x + 0.5) idiom, and nothing here does that.
What is printed as a result of executing the code segment?
Correct. Follow the shifts: remove(1) deletes the element at
index 1 and returns 34, leaving [12, 56, 78]; add(0, 90) pushes all three
one place right, giving [90, 12, 56, 78]; and the decisive step is
set(2, 11), which overwrites whatever is at index 2 after those
shifts, 56, not 78.
This reads nums.remove(1) as removing the value 1. On an
ArrayList<Integer> an int argument selects the
remove(int index) method, so it removes the element at index 1; you would
have to write nums.remove(Integer.valueOf(1)) to remove by value.
This treats add(0, 90) as an append. The two-argument
add inserts at the given index and shifts every later element right, so 90
lands at the front; add(90) with one argument is the one that appends.
This has the removal and the insertion right but treats set as
though it only read the list. set(2, 11) replaces the element at index 2 and
returns the old value, so the list really does change, though, unlike
add and remove, it never changes size().
// nums holds [9, 4, 3, 12, 2, 6]
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) < 5) {
nums.remove(i);
}
}
System.out.println(nums);
The segment is intended to remove every element less than 5. What is printed as
a result of executing it?
This is what the author intended, and what a backward loop
(for (int i = nums.size() - 1; i >= 0; i--)) actually produces on this
data. The forward loop does not manage it.
Correct. The pass at i = 1 decides it: removing the 4 slides
the 3 down into index 1, but the loop has already finished with index 1 and moves on to
index 2, so the 3 is never examined. The 2 at the end is caught only because it happens
to have no removed neighbor before it: adjacent small values are what expose this
bug.
This removes only the 4, as if the loop stopped after its first removal.
The 2 is also less than 5 and the loop does reach it, so it is removed too. Note that
nums.get(i) is unboxed to an int before the comparison, so
< compares numbers, not references.
That exception belongs to the enhanced for loop, which refuses to let you
add to or remove from the collection it is walking. This is an indexed loop, so Java
raises no objection: it simply produces the wrong answer, quietly.
// Each Reading has getStation() and getLevel().
// The readings were built from lines of a data file, so their
// station names are NOT string literals.
public double averageFor(String station) {
double total = 0.0;
int count = 0;
for (Reading r : readings) {
if (r.getStation() == station) { // line 9
total += r.getLevel();
count++;
}
}
if (count == 0) {
return -1.0;
}
return total / count;
}
The log holds Elm St readings of 18.0, 25.0 and 20.0, one Oak Ave reading and one
Elm St North reading, yet averageFor("Elm St") returns −1.0. Which replacement
for line 9 makes the method return 21.0 here and work for every station name?
Writing the same test backwards changes nothing: == on two
String references asks whether they are the same object, and a name built at
run time by substring is a different object from the literal in the call, so
the count stays 0 and the method still returns −1.0.
compareTo returns 0 for equal strings, so only == 0 is an
equality test. Asking for >= 0 accepts every station at or after this one
alphabetically, which here counts all five readings and returns 23.2.
This matches any name that contains the argument, so Elm St North
is counted as an Elm St reading and the method returns 23.5. Substring matching is a
different question from equality, and the exam plants a name like Elm St North precisely
to catch it.
Correct. equals compares the characters rather than the
references, so the three Elm St readings match whatever built their names, and
(18.0 + 25.0 + 20.0) / 3 is 21.0. The empty-case guard still works: a station with no
readings leaves count at 0 and returns −1.0 instead of dividing by zero.
int[][] grid = {{3, 8, 2, 5},
{4, 6, 9, 1},
{7, 2, 5, 3}};
for (int c = 0; c < grid[0].length; c++) {
for (int r = 0; r < grid.length; r++) {
System.out.print(grid[r][c] + " ");
}
}
What is printed as a result of executing the code segment?
That is row-major order, which is what you get when r is on the
outside. Here c is on the outside, so a whole column is finished before the
next column begins.
Correct. The outer loop fixes a column and the inner loop walks the rows of
it, so the first three values printed are column 0 top to bottom (3, 4, 7), and the
fourth value, 8, is where the order visibly differs from row-major. All twelve cells are
still visited, and the last one is still grid[2][3].
Six values would mean the outer loop ran only twice. It runs
grid[0].length times, which is 4: the number of columns, because
grid[0] is one row and its length is how many entries that row has.
Nothing is out of bounds. The bounds are correctly paired with the
subscripts they control: c is tested against
grid[0].length and used as the second subscript, and r is
tested against grid.length and used as the first.
public static int[] columnTotals(int[][] grid) {
int[] totals = new int[grid.length]; // line 2
for (int c = 0; c < grid[0].length; c++) {
int total = 0;
for (int r = 0; r < grid.length; r++) {
total += grid[r][c];
}
totals[c] = total;
}
return totals;
}
Called on the 3-by-4 grid {{3, 8, 2, 5}, {4, 6, 9, 1}, {7, 2, 5, 3}},
the method throws an exception. Which replacement for line 2 makes it return the column
totals for every rectangular grid?
Correct. The subscript that indexes totals is c,
and c runs up to grid[0].length - 1, so the array needs one slot
per column. grid.length is the number of rows, 3 here, which is
why totals[3] throws Index 3 out of bounds for length 3. With
the fix the method returns {14, 16, 16, 9}.
This is big enough never to throw, which is exactly why it hides the error:
on the 3-by-4 grid it returns a twelve-element array,
{14, 16, 16, 9, 0, 0, 0, 0, 0, 0, 0, 0}, with eight zero totals for columns
that do not exist.
Hard-coding 4 does return {14, 16, 16, 9} for this grid and
then throws Index 4 out of bounds for length 4 the first time the method
meets a grid with five columns. A length taken from the data is what makes the method
general.
Returning a grid where a one-dimensional array was promised does not even
compile: javac reports
incompatible types: int cannot be converted to int[] at the assignment and
int[][] cannot be converted to int[] at the return.
public static int search(int[] values, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (values[mid] == target) {
return mid;
}
if (values[mid] < target) {
return search(values, target, mid + 1, high);
}
return search(values, target, low, mid - 1);
}
How many calls to search are made in total, including the original
call from println?
Three is the number of calls that actually examine a midpoint: 23 at index
4, then 9 at index 1, then 5 at index 0. Each one is too big, too big, then too small, so
a fourth call is made before the method can answer.
Correct. The fourth call is the one students forget. After the third call
finds 5 < 7 it recurses with low = 1, high = 0; that call examines no
element at all, hits the base case low > high, and returns −1. When a
target is absent, the empty-range call is what delivers the answer, so it counts.
Five calls would need one more halving. For the target 7 the live range goes
9, 4, 1, 0 and the search is over after four calls. A target larger than everything in the
array, such as 51, does take five calls here: it keeps moving right through the midpoints
at indexes 4, 6, 7 and 8 and then reaches an empty range.
Nine is the length of the array, and the number of comparisons a
linear search would need to report that 7 is absent. Halving the live range on
every call is the whole reason binary search is worth keeping the data sorted for.
FRQ 1 · Methods and Control Structures · 22 minutes · 7 points
Write the charge and totalCharge methods of the ParkingGarage class.
Directions
Write your response in Java. Assume that the classes shown below compile exactly as given and
that every precondition stated in the question is met: you do not have to check them. Write
only the bodies of the two methods you are asked for: do not rewrite the constructor, do not
change the given headers, and do not write any code outside the two methods. You may call any
method that the class already provides, including one you are writing in another part. Your
response is scored on Java that would compile and on whether it produces exactly the values in
the examples table, so a method that prints instead of returning, or that has a side effect the
question never asked for, loses points even when the arithmetic is right.
A city parking garage charges by the hour, but gives every driver a short free window at the start
of a visit so that people who only drop something off are not billed. Once the free window is used
up, the garage charges its hourly rate for every started hour past that window: one
minute over the free window costs a full hour, sixty-one minutes over costs two hours, and so on.
No matter how long a car stays, a single visit is never billed more than the daily maximum of
24.00 dollars.
At the end of each day the attendant hands in a log: the lengths of the day's visits in minutes,
written as one string with single commas between the numbers and no spaces, for example
20,75,130. A day with no visits is recorded as the empty string. The class below is
used to price a single visit and to price a whole day's log.
public class ParkingGarage {
/** The dollars charged for each started hour past the free window; always positive. */
private double hourlyRate;
/** The number of minutes at the start of a visit that cost nothing; never negative. */
private int freeMinutes;
/** Constructs a garage with the given hourly rate and free window. */
public ParkingGarage(double hourlyRate, int freeMinutes) {
this.hourlyRate = hourlyRate;
this.freeMinutes = freeMinutes;
}
/** Returns the charge, in dollars, for a single visit lasting minutes minutes,
* as described in part (a).
* Precondition: minutes >= 0
*/
public double charge(int minutes) {
/* to be implemented in part (a) */
}
/** Returns the total charge, in dollars, for every visit recorded in log,
* as described in part (b).
* Precondition: log is not null. log is either the empty string or one or more
* non-negative integers separated by single commas, with no spaces
* and no comma at either end.
*/
public double totalCharge(String log) {
/* to be implemented in part (b) */
}
}
(a) Write the method charge. A visit of freeMinutes
minutes or fewer is free and returns 0.0. Otherwise the garage counts the minutes past
the free window and rounds them up to a whole number of started hours, so that any part of
an hour is billed as a full hour, and multiplies that count by hourlyRate. If the
result is greater than 24.0, the method returns 24.0 instead.
Precondition:minutes >= 0. Postcondition: the returned value is
at least 0.0 and at most 24.0, and neither instance variable has changed.
public double charge(int minutes)
(b) Write the method totalCharge. The method walks the string
log from left to right, using indexOf to find the next comma and
substring to cut off the piece in front of it, converts each piece to an
int with Integer.parseInt, and adds up the charge for each visit. The
empty log returns 0.0. A log with no comma in it holds exactly one visit.
Precondition:log is not null and has the form described above.
Postcondition: the returned value is the sum of charge applied to every visit
length in log, and neither instance variable has changed.
In writing totalCharge you may call charge; assume that
charge works as specified regardless of what you wrote for part (a).
public double totalCharge(String log)
The table below assumes the garage was built with
ParkingGarage g = new ParkingGarage(2.50, 15);. The middle column is what Java actually
prints for the returned double, so a charge of two dollars fifty cents appears as
2.5.
Call
Returns
Why
g.charge(15)
0.0
15 is not past the 15-minute free window, so the visit is free.
g.charge(16)
2.5
1 minute past the window starts an hour, so one hour is billed.
g.charge(75)
2.5
60 minutes past the window is exactly one hour, no second hour starts.
g.charge(76)
5.0
61 minutes past the window starts a second hour.
g.charge(135)
5.0
120 minutes past the window is exactly two hours.
g.charge(2000)
24.0
34 started hours would be 85.0 dollars, so the daily maximum applies.
g.totalCharge("20,75,130")
10.0
2.5 + 2.5 + 5.0: the last piece has no comma after it and must still be counted.
g.totalCharge("130")
5.0
A log with no comma holds exactly one visit.
g.totalCharge("")
0.0
An empty log means no visits, so the loop never runs.
Your code
What a reader looks for on this question
A reader applies nine checks to your code. This question is scored out of 7, so the checks are grouped into the 7 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 (a) returns 0.0 when minutes is at most freeMinutes: the test is <=, not <, so a visit of exactly freeMinutes is still free.
+1 (a) computes the minutes past the free window as minutes - freeMinutes and converts them to a whole number of started hours, adding one more hour whenever the remainder after dividing by 60 is positive.
+1 (a) multiplies the hour count by hourlyRate, caps the result at 24.0 when it is larger, and returns a double.
+1 (b) declares and initializes a running total of 0.0 and a local copy of log before the loop, and returns 0.0 for the empty log without entering the loop.
+1 (b) finds each separator with indexOf and cuts exactly one visit length per pass with substring, consuming the whole string (including the final piece, which has no comma after it), and terminating.
+1 (b) converts each piece with Integer.parseInt, adds the charge for that visit into the accumulator on every pass, and returns the accumulated sum after the loop rather than inside it.
+1 uses the given class as specified: both headers match the skeleton exactly, the private fields hourlyRate and freeMinutes are read directly because the code is inside their own class, and the String methods are called with correct arguments (substring(0, comma) and substring(comma + 1)). Same point, also required: writes Java that would compile: every local variable is declared with a type, int and double are not confused in the return statements, braces and semicolons are balanced, and no variable is used outside the block in which it is declared. Same point, also required: no side effects beyond the specification and no unnecessary code: part (b) calls charge instead of re-deriving the hour arithmetic, neither method assigns to hourlyRate or freeMinutes, neither prints anything, log itself is never treated as something to modify, and the string is walked once.
Show a full-credit (7/7) solution
Part (a)
public double charge(int minutes) {
if (minutes <= freeMinutes) {
return 0.0;
}
int extra = minutes - freeMinutes;
int hours = extra / 60;
if (extra % 60 > 0) {
hours++;
}
double amount = hours * hourlyRate;
if (amount > 24.0) {
amount = 24.0;
}
return amount;
}
Part (b)
public double totalCharge(String log) {
double total = 0.0;
String rest = log;
while (rest.length() > 0) {
String piece = rest;
int comma = rest.indexOf(",");
if (comma >= 0) {
piece = rest.substring(0, comma);
rest = rest.substring(comma + 1);
} else {
rest = "";
}
total = total + charge(Integer.parseInt(piece));
}
return total;
}
Where the 7 points are earned
Point 1.The free window. The first if returns
0.0 for every visit of freeMinutes minutes or fewer. The comparison
has to be <=. Writing < makes charge(15) return
2.5 instead of 0.0 and costs this point, and it is the single most
common slip on this question because the free window sounds like "under fifteen minutes" in
English when the specification says "at most fifteen".
Point 2.Started hours.extra is the number of billable
minutes, and extra / 60 is integer division, so it throws away the leftover
minutes. The test extra % 60 > 0 puts the leftover back as one more full hour.
That is what makes charge(16) cost a whole hour while charge(75),
whose remainder is exactly zero, does not start a second one.
Point 3.Rate and cap.hours * hourlyRate mixes an
int with a double, so Java promotes the product to double, no cast is needed. The second if replaces anything above the daily maximum with
24.0, which is why 2000 minutes returns 24.0 rather than
85.0.
Point 4.Set-up and the empty log.total starts at
0.0 and rest starts as the whole log. When log is
"" the while condition is false immediately, the body never runs, and
the method returns the initial 0.0. Initializing inside the loop, or returning
from inside it, breaks this case.
Point 5.Cutting the pieces. Each pass asks indexOf for
the next comma. If there is one, the piece in front of it is taken and rest is
reassigned to everything after it; if there is none, the whole of rest is the last
visit and rest becomes "" so the loop stops. Forgetting that last
branch is how students lose the final visit and report 5.0 for
"20,75,130"; forgetting to shrink rest at all is how they write an
infinite loop.
Point 6.Accumulate and return.Integer.parseInt(piece)
turns the text into an int, charge prices it, and the result is added
into total on every pass. The return sits after the loop, so all three
visits in "20,75,130" are summed to 10.0. A return inside
the loop would report only the first visit.
Point 7.Using the class as given. Both headers are copied from the skeleton
unchanged, the private fields are used directly because this code lives inside
ParkingGarage, and the String methods are called the way the Java
Quick Reference defines them: substring(from, to) stops just before
to, and substring(from) runs to the end. Code that compiles. Every local (extra,
hours, amount, total, rest,
piece, comma) is declared with a type, both methods return a
double on every path, and piece is declared before the
if so that it is still in scope when it is used afterwards. No side effects, no repetition. Part (b) calls
charge instead of copying the hour-and-cap arithmetic into a second place, neither
method assigns to hourlyRate or freeMinutes, neither prints anything,
and the log is traversed exactly once with no extra variables left unused.
Common ways to lose points on this question:
Using < instead of <= for the free window, so an exactly
fifteen-minute visit is billed.
Writing extra / 60 alone and never adding the partial hour, which makes
charge(16) return 0.0.
Dividing after converting to double (extra / 60.0) and then
multiplying, which bills fractions of an hour instead of started hours.
Comparing against the cap with >= and returning early, or capping the hour
count rather than the dollar amount.
Re-deriving the fee inside totalCharge instead of calling charge:
this is the design point, and it is lost even if both methods return the right numbers.
Printing the total instead of returning it, or changing hourlyRate while
computing.
FRQ 2 · Methods and Control Structures · 22 minutes · 7 points
Write the score and rating methods of the PasswordStrength class.
Directions
Write your response in Java. Assume that the class shown below compiles exactly as given and that
every stated precondition is met: you do not have to check for a null string. Write only the
bodies of the two methods you are asked for: do not rewrite the constructor, do not change the
given headers, and do not write any code outside the two methods. You may call a method you are
writing in another part of this question. Your response is scored on Java that would compile and
on whether it produces exactly the values in the examples table. Remember that this course's Java
subset has no charAt: take a single character as the one-character string
s.substring(i, i + 1) and compare it with compareTo or
equals.
A website rates the passwords people choose and shows them a one-word verdict as they type. The
rating is built from a numeric score out of 4. A password earns one point for containing at least
one digit, one point for containing at least one uppercase letter, one point for containing at least
one lowercase letter, and one point for being long enough. Each of those four things is worth
at most one point no matter how many characters satisfy it: a password of twelve
digits still earns exactly one point for digits.
"Long enough" is decided by the site, not by the class, so the minimum length is stored in the object
when it is constructed. The score is then turned into the word the user sees. The class below does
both jobs.
public class PasswordStrength {
/** The smallest length that earns the length point; always positive. */
private int minLength;
/** Constructs a password checker with the given minimum length. */
public PasswordStrength(int minLength) {
this.minLength = minLength;
}
/** Returns the strength score of pw, a value from 0 through 4,
* as described in part (a).
* Precondition: pw is not null.
*/
public int score(String pw) {
/* to be implemented in part (a) */
}
/** Returns the one-word rating of pw, as described in part (b).
* Precondition: pw is not null.
*/
public String rating(String pw) {
/* to be implemented in part (b) */
}
}
(a) Write the method score. Walk pw one character at a
time, taking each character as the one-character string pw.substring(i, i + 1). A
one-character string ch is a digit when ch.compareTo("0") >= 0 and
ch.compareTo("9") <= 0; uppercase letters and lowercase letters are tested the same
way, against "A" and "Z" and against "a" and
"z". Award one point if at least one digit appears anywhere in pw, one
point if at least one uppercase letter appears, one point if at least one lowercase letter appears,
and one point if the length of pw is at least minLength. Return the total.
Precondition:pw is not null; pw may be the empty string.
Postcondition: the returned value is an int from 0 through 4 inclusive, and
minLength has not changed.
public int score(String pw)
(b) Write the method rating. It returns "weak" when the
score is 0 or 1, "fair" when the score is 2 or 3, and "strong" when the
score is 4. Precondition:pw is not null. Postcondition: the returned
value is exactly one of the three words above, in lowercase, and minLength has not
changed. In writing rating you may call score; assume that
score works as specified regardless of what you wrote for part (a).
public String rating(String pw)
The table below assumes the checker was built with
PasswordStrength p = new PasswordStrength(8);.
Call
score returns
rating returns
Why
"abc"
1
weak
Lowercase only, and 3 is shorter than 8.
"abcdefgh"
2
fair
Lowercase plus the length point; no digit and no uppercase.
"Abcdefgh"
3
fair
Uppercase, lowercase and length; still no digit.
"Abcdef12"
4
strong
All three categories appear and the length is 8.
"AB12"
2
fair
Digit and uppercase only: two digits and two capitals are still one point each.
""
0
weak
The loop never runs and 0 is shorter than 8.
Your code
What a reader looks for on this question
A reader applies nine checks to your code. This question is scored out of 7, so the checks are grouped into the 7 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 (a) declares and initializes one boolean flag (or equivalent) for each of the three character categories before the loop starts, so that a category found early is remembered to the end.
+1 (a) loops over every index of pw from 0 through pw.length() - 1, missing neither the first nor the last character and running off neither end, and extracts one character with pw.substring(i, i + 1).
+1 (a) tests the three categories correctly on that one-character string, using compareTo range comparisons against "0"/"9", "A"/"Z" and "a"/"z" rather than == on strings.
+1 (a) counts each category at most once, however many characters match it, so "AB12" scores 2 and not 4.
+1 (a) adds the fourth point exactly when pw.length() >= minLength, comparing against the instance variable and not a hard-coded number, and handles the empty string by scoring 0 rather than failing.
+1 (a) returns the accumulated total, an int from 0 through 4, after the loop rather than inside it.
+1 uses the given class as specified: both headers match the skeleton exactly, minLength is read directly because the code is inside its own class, and String methods are called with correct arguments: substring(i, i + 1), length() with parentheses, compareTo used for its sign rather than compared to a letter. Same point, also required: writes Java that would compile: every local variable is declared with a type, rating returns a String on every possible path, score returns an int, braces and semicolons are balanced, and no variable is used outside the block where it is declared. Same point, also required: no side effects beyond the specification and no unnecessary code: rating calls score once instead of repeating the character scan, neither method assigns to minLength, neither prints when it is asked to return, pw is never reassigned, and the password is walked only once.
Show a full-credit (7/7) solution
Part (a)
public int score(String pw) {
boolean hasDigit = false;
boolean hasUpper = false;
boolean hasLower = false;
for (int i = 0; i < pw.length(); i++) {
String ch = pw.substring(i, i + 1);
if (ch.compareTo("0") >= 0 && ch.compareTo("9") <= 0) {
hasDigit = true;
}
if (ch.compareTo("A") >= 0 && ch.compareTo("Z") <= 0) {
hasUpper = true;
}
if (ch.compareTo("a") >= 0 && ch.compareTo("z") <= 0) {
hasLower = true;
}
}
int points = 0;
if (hasDigit) {
points++;
}
if (hasUpper) {
points++;
}
if (hasLower) {
points++;
}
if (pw.length() >= minLength) {
points++;
}
return points;
}
Part (b)
public String rating(String pw) {
int s = score(pw);
if (s <= 1) {
return "weak";
}
if (s <= 3) {
return "fair";
}
return "strong";
}
Where the 7 points are earned
Point 1.The flags. Three boolean variables are declared
and set to falsebefore the loop. That placement is the whole idea of the
method: the loop can only ever flip a flag from false to true, so whatever it finds at index 0
is still remembered at the last index. Declaring the flags inside the loop resets them on every
pass and leaves the method reporting only what the final character happened to be.
Point 2.The traversal. The loop runs i from 0 while
i < pw.length(), which visits every index once and stops before the string ends.
pw.substring(i, i + 1) is the AP-subset way to pull out a single character: the
second argument is the index just past the piece you want, so this returns exactly one
character. Using <= in the loop condition throws
StringIndexOutOfBoundsException.
Point 3.The category tests.compareTo returns a negative
number, zero, or a positive number according to alphabetical order, so
ch.compareTo("0") >= 0 && ch.compareTo("9") <= 0 says "this character
sits between 0 and 9 inclusive". The same pattern tests the two letter ranges. The three tests
are separate if statements, not else if, which is harmless here
because no character can be in two ranges at once, but writing them as independent tests is
the habit that keeps this kind of method correct.
Point 4.At most one point per category. Because the loop only sets
flags and the points are counted afterward, a password of four digits sets
hasDigit four times and still scores one point for digits. This is exactly the
case the examples table checks with "AB12", which has two capitals and two digits
and scores 2. A counter that increments inside the loop would report 4 there and lose this
point.
Point 5.The length point and the empty string. The last
if compares pw.length() with the instance variable
minLength, not with a literal 8, so the same class works for a site that wants
twelve. For "" the loop body never executes, all three flags stay false, the
length test fails, and the method returns 0, no special case is needed.
Point 6.The return.points is accumulated after the loop
and returned once, so the value is an int from 0 through 4. Part (b) then maps that
number onto the three words with two tests and a fall-through return, which covers 0 through 4
with no gap and no overlap and guarantees a String on every path.
Point 7.Using the class as given. Both headers are copied from the skeleton
unchanged. minLength is read directly because this code lives inside
PasswordStrength; from outside the class it would have to go through an accessor.
length() is a method on a String and needs its parentheses: the
parenthesis-free length belongs to arrays. Code that compiles.hasDigit, hasUpper,
hasLower, ch, points and s are all declared
with a type; ch is declared inside the loop where it is used and nowhere else;
score returns an int and rating a String;
and the string comparisons use compareTo rather than <, which does
not compile on objects. No side effects, no repetition.rating calls
score once and stores the result instead of calling it three times or copying the
scan; neither method assigns to minLength or to pw; neither prints
when it was asked to return; and no variable is declared that is never used.
Common ways to lose points on this question:
Incrementing a counter inside the loop instead of setting a flag, so a password with several
digits scores more than one point for digits.
Declaring the flags inside the loop, which resets them every pass and leaves the score
describing only the last character.
Using == or < on the one-character strings; ==
compares references and < does not compile on a String.
Writing i <= pw.length(), or substring(i, i + 2), and running off
the end of the string.
Comparing the length against a literal 8 instead of minLength, which passes the
examples table but fails any other checker object.
Rewriting the whole character scan inside rating rather than calling
score: this is the design point, and it is lost even when both methods return the
right words.
Returning "Weak" or "STRONG"; the specification names the words in
lowercase and a grader compares them with equals.
FRQ 3 · Class Design · 22 minutes · 7 points
A coffee shop punch card
This is a Question 2 task: you are handed a description of an object and you write the
whole class (the instance variables, the constructor, and every method) from nothing.
Nobody gives you a skeleton to fill in, so the first thing a reader checks is whether the
class you wrote would compile on its own.
A campus coffee shop gives every regular a paper punch card. The card belongs to one named
owner. Each drink the owner buys adds one punch to the card. When the fifth punch is added
the shop tears the card down: those five punches become one free drink, and the punch count
goes back to zero, so the sixth purchase is punch number one on a fresh card. Free drinks
pile up on the card until the owner spends them, and a free drink can only be spent if there
is one there to spend.
Write the complete class CoffeeCard to model one punch card.
Instance variables. Your class needs exactly three pieces of state, and
all three must be private: the owner's name as a String, the
number of punches currently on the card as an int, and the number of unspent
free drinks as an int. Choose the names yourself: a reader scores the
encapsulation, not your spelling.
Constructor and methods. Your class must declare exactly these members,
with these headers. The behavior of each one is described below.
public CoffeeCard(String owner)
public void buy()
public int getFreeDrinks()
public boolean redeem()
public String getStatus()
CoffeeCard(String owner): creates a brand-new card for the given owner, with
zero punches and zero free drinks. Precondition:owner is not
null.
buy(): records one purchase. It adds one punch to the card. If that punch is
the fifth one, it instead converts the five punches into one more free drink and sets the
punch count back to 0. It returns nothing.
getFreeDrinks(): returns the number of unspent free drinks on the card. It
must not change the card.
redeem(): spends one free drink. If the card has at least one unspent free
drink, redeem removes one from the card and returns true. If the
card has no free drinks, it changes nothing at all and returns false. The punch
count is never touched by redeem.
getStatus(): returns the owner's name, a space, the punch count, a slash, the
digit 5, a comma, a space, the free-drink count, a space, and the word free.
For a card belonging to Maya with one punch and one free drink that string is exactly
Maya 1/5, 1 free.
The table traces one card from the moment it is created through six calls to
buy and two calls to redeem. Every value in it comes from running
the class. The punch count is the number before the slash.
Call
Returns
getFreeDrinks()
getStatus()
CoffeeCard card = new CoffeeCard("Maya");
:
0
Maya 0/5, 0 free
card.buy(); (1st)
no value (void)
0
Maya 1/5, 0 free
card.buy(); (2nd)
no value (void)
0
Maya 2/5, 0 free
card.buy(); (3rd)
no value (void)
0
Maya 3/5, 0 free
card.buy(); (4th)
no value (void)
0
Maya 4/5, 0 free
card.buy(); (5th)
no value (void)
1
Maya 0/5, 1 free
card.buy(); (6th)
no value (void)
1
Maya 1/5, 1 free
card.redeem();
true
0
Maya 1/5, 0 free
card.redeem(); (again)
false
0
Maya 1/5, 0 free
Directions
Write the complete CoffeeCard class, including the class header, the private
instance variables, the constructor, and all four methods, so that it behaves exactly as
described above and produces every value in the examples table. Your response is scored on
Java that would compile: declare a type for every variable, match the given headers exactly,
and balance your braces. Write the class so that it stands alone, no main
method, no import, no printing inside any method, and nothing outside the
class. You have 22 minutes; a Question 2 response is worth 7 points, and correctness is
worth more than elegance, so write the straightforward version first and only tidy it if
time is left.
Your code
Scoring notes, 7 points
A reader applies nine checks to your code. This question is scored out of 7, so the checks are grouped into the 7 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 declares public class CoffeeCard and everything the question asks for lives inside that one class body, no main method, no second class, no code outside the braces.
+1 declares all three instance variables and declares them private: a String for the owner and two int counters for punches and free drinks.
+1 constructor public CoffeeCard(String owner) stores the parameter in the owner field and sets both counters to 0 (writing them explicitly or letting them default is both fine, but the field must be assigned the parameter, not itself).
+1 public void buy() adds exactly one punch on every call, and on the fifth punch adds one to the free-drink count and resets the punch count to 0: the test is == 5 (or >= 5), never > 5, and the reset happens in the same call.
+1 public int getFreeDrinks() returns the free-drink counter itself and modifies nothing. Same point, also required:public boolean redeem() guards on the free-drink count being greater than 0, decreases it by one and returns true inside the guard, and returns false without changing any field otherwise: both paths return.
+1 public String getStatus() builds and returns owner, space, punch count, /5, comma, space, free count, space, free, in that order with those exact separators.
+1 every header matches the required return type and parameter list exactly (void for buy, int for getFreeDrinks, boolean for redeem, String for getStatus), and every non-void method returns a value of that type on every path. Same point, also required: design and encapsulation: the fields stay private and are never exposed, no accessor changes state, no method prints instead of returning, redeem leaves the punch count alone, and no variable is declared that is never used.
Show a full-credit (7/7) solution
Here is a response that earns all seven points. It was compiled with javac and
run against the call sequence in the examples table.
public class CoffeeCard {
private String owner;
private int punches;
private int freeDrinks;
public CoffeeCard(String owner) {
this.owner = owner;
punches = 0;
freeDrinks = 0;
}
public void buy() {
punches++;
if (punches == 5) {
freeDrinks++;
punches = 0;
}
}
public int getFreeDrinks() {
return freeDrinks;
}
public boolean redeem() {
if (freeDrinks > 0) {
freeDrinks--;
return true;
}
return false;
}
public String getStatus() {
return owner + " " + punches + "/5, " + freeDrinks + " free";
}
}
Printing card.getStatus() after the card is created, after each of six calls to buy, and
around two calls to redeem gives exactly this:
Point 1.Class header:public class CoffeeCard { opens the file and the closing brace ends it. There is no main, no import and no second class, so the file compiles on its own, which is the only way the other six points can be awarded at all.
Point 2.Private instance variables: three fields, one per piece of state the description names, each marked private. The counters are int because they count whole punches and whole drinks; the owner is a String.
Point 3.Constructor: the header matches public CoffeeCard(String owner). Because the parameter and the field share the name owner, the assignment must be this.owner = owner;: owner = owner; compiles and silently does nothing. Both counters are set to 0, so a new card starts empty.
Point 4.Buy: one punch is added on every call, then the fifth punch is converted. Testing punches == 5 after the increment is what makes the card reset on the fifth call rather than the sixth, and setting punches = 0 inside the same if is what makes the sixth call read 1/5.
Point 5.GetFreeDrinks: a one-line accessor that returns the counter and touches nothing. An accessor that also changed state would cost this point and the design point together. Redeem: the guard freeDrinks > 0 separates the two cases the specification names. Inside the guard the count drops by one and the method returns true; outside it the method returns false having changed nothing, which is why the second redeem in the table prints false and leaves the card reading 1/5, 0 free.
Point 6.GetStatus: one concatenation, in the exact order the specification gives, with the literal "/5, " and " free" carrying the punctuation. The int fields convert to text automatically when they are added to a String.
Point 7.Return types and headers:buy is void and returns nothing, getFreeDrinks returns an int, redeem returns a boolean on both paths, and getStatus returns a String. Every header is spelled exactly as the question gave it, so a client written against the specification links against this class. Program design and encapsulation: nothing is public except the five members the question asked for, no method prints, redeem does not disturb the punch count, and there are no leftover local variables or a second pass over anything.
Common ways to lose points on this question:
Testing punches > 5 instead of punches == 5. The card then rewards the owner on the sixth punch, and every row of the examples table from the fifth buy onward is wrong.
Incrementing after the test, if (punches == 4) { ... } punches++;, which is a real off-by-one, not a style choice. Do the increment first, then ask whether the card is full.
Writing owner = owner; in the constructor. It compiles, the field stays null, and getStatus returns null 0/5, 0 free.
Making redeem return void, or printing "no free drinks" instead of returning false. The header is public boolean redeem(); a method asked to return must never print.
Declaring the fields public, or adding a setter nobody asked for. Either one costs the design point, and public fields also undercut the encapsulation the whole question is testing.
Adding a main method to test the class and leaving it in. The response is supposed to be a class, not a program, and stray code outside the class body will not compile.
FRQ 4 · Class Design · 22 minutes · 7 points
A water tank with a limited capacity
This is another Question 2 task: you are handed a description and you write the whole class.
The twist in this one is a limit. The object has a maximum it must never exceed, and two of
its methods have to decide what actually happened before they report it.
A rain barrel stores water for a garden. The barrel has a fixed capacity in liters that is set
when it is built, and it always starts empty. Pouring water in adds as much as fits: if the
barrel would overflow, the extra water is simply lost and the barrel ends up exactly full.
Taking water out works only if the barrel holds enough, and a request for more than the
barrel holds takes nothing at all.
Write the complete class WaterTank to model one barrel.
Instance variables. Your class needs exactly two pieces of state, and both
must be private: the capacity in liters and the current level in liters, each an
int. Choose the names yourself: a reader scores the encapsulation, not your
spelling.
Constructor and methods. Your class must declare exactly these members, with
these headers.
public WaterTank(int capacity)
public int fill(int liters)
public boolean use(int liters)
public int getLevel()
public int percentFull()
WaterTank(int capacity): creates an empty tank with the given capacity.
Precondition:capacity is at least 1.
fill(int liters): pours water in. It adds as many of the liters as
fit under the capacity, and returns the number of liters that were actually added, which is
less than liters when the tank overflows. Precondition:liters is at least 0.
use(int liters): takes water out. If the tank holds at least liters
liters, it removes them and returns true. Otherwise it changes nothing and
returns false. Precondition:liters is at least 0.
getLevel(): returns the current level in liters. It must not change the
tank.
percentFull(): returns the level as a whole-number percentage of the capacity,
rounded down. A tank of capacity 30 holding 20 liters is 66 percent full.
Every value in the table below was produced by running the class on one tank, from the call
that creates it through the calls that follow, in order.
Call
Returns
getLevel()
percentFull()
WaterTank t = new WaterTank(30);
:
0
0
t.fill(20);
20
20
66
t.fill(20);
10
30
100
t.use(12);
true
18
60
t.use(25);
false
18
60
t.use(5);
true
13
43
t.fill(0);
0
13
43
Directions
Write the complete WaterTank class, including the class header, the private
instance variables, the constructor, and all four methods, so that it behaves exactly as
described and produces every value in the examples table. Your response is scored on Java
that would compile: declare a type for every variable, match the given headers exactly, and
balance your braces. Write the class so that it stands alone, no main method,
no import, no printing inside any method, and nothing outside the class. You
have 22 minutes for 7 points.
Your code
Scoring notes, 7 points
A reader applies nine checks to your code. This question is scored out of 7, so the checks are grouped into the 7 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 declares public class WaterTank and everything the question asks for lives inside that one class body, no main method, no second class, no code outside the braces.
+1 declares both instance variables as private int: one for the capacity and one for the level.
+1 constructor public WaterTank(int capacity) stores the parameter in the capacity field (not into itself) and starts the level at 0.
+1 public int fill(int liters) adds only what fits, so the level never exceeds the capacity, and returns the number of liters actually added (the amount that fit, not the amount requested).
+1 public boolean use(int liters) tests the level against liters (>=, so taking exactly all of it is allowed), subtracts and returns true inside the test, and returns false without changing any field otherwise: both paths return.
+1 public int getLevel() returns the level itself and modifies nothing. Same point, also required:public int percentFull() returns level * 100 / capacity (or an equivalent), multiplying before the integer division so the result is rounded down correctly and not always 0.
+1 every header matches the required return type and parameter list exactly (int for fill, boolean for use, int for getLevel and percentFull), and every non-void method returns a value of that type on every path. Same point, also required: design and encapsulation: the fields stay private and are never exposed, no accessor changes state, no method prints instead of returning, use changes nothing when it returns false, and no variable is declared that is never used.
Show a full-credit (7/7) solution
Here is a response that earns all seven points. It was compiled with javac and
run against the call sequence in the examples table.
public class WaterTank {
private int capacity;
private int level;
public WaterTank(int capacity) {
this.capacity = capacity;
level = 0;
}
public int fill(int liters) {
int room = capacity - level;
int added = liters;
if (added > room) {
added = room;
}
level += added;
return added;
}
public boolean use(int liters) {
if (level >= liters) {
level -= liters;
return true;
}
return false;
}
public int getLevel() {
return level;
}
public int percentFull() {
return level * 100 / capacity;
}
}
Printing the return value, the level and the percentage after each call in the table gives
exactly this:
Point 1.Class header:public class WaterTank { opens the file and the closing brace ends it. There is no main, no import and no second class, so the file compiles on its own, which is the only way the other six points can be awarded at all.
Point 2.Private instance variables: two private int fields, one per piece of state the description names. Both are whole liters, so int is the right type.
Point 3.Constructor: the parameter and the field share the name capacity, so the assignment must be this.capacity = capacity;: writing capacity = capacity; compiles and silently does nothing, which would leave the capacity at 0. The level is set to 0 so a new tank starts empty.
Point 4.Fill:room is how much space is left. If the request is larger than room, the amount added is cut down to room; the level goes up by the amount added, and that same number is returned. In the table the second fill(20) asks for 20 but only 10 fit, so it returns 10 and the tank is exactly full.
Point 5.Use: the guard level >= liters separates the two cases. Inside the guard the level drops and the method returns true; outside it the method returns false having changed nothing, which is why use(25) in the table leaves the level at 18.
Point 6.GetLevel: a one-line accessor that returns the field and touches nothing. PercentFull:level * 100 / capacity multiplies first. Writing level / capacity * 100 would divide two ints first and give 0 for every level below the capacity. With 20 of 30 the product is 2000, and 2000 / 30 is 66 after the division drops the remainder, which is the round-down the question asked for.
Point 7.Return types and headers:fill returns an int on its only path, use returns a boolean on both paths, and the two accessors return an int. Every header is spelled exactly as the question gave it. Program design and encapsulation: nothing is public except the five members the question asked for, no method prints, use changes nothing when it fails, and there are no leftover local variables.
Common ways to lose points on this question:
Adding all the requested liters and then correcting the level afterward, or returning liters instead of the amount that actually fit. The return value is the amount added, and the second row of the table is the test.
Testing level > liters in use. Taking exactly all the water then fails, and the question allows it.
Writing level / capacity * 100. Integer division makes the first quotient 0 until the tank is full, so every row but the full one reports 0 percent.
Writing capacity = capacity; in the constructor. It compiles, the field stays 0, and percentFull then divides by zero and throws an ArithmeticException.
Printing "not enough water" inside use instead of returning false. A method asked to return a value must never print instead.
Declaring the fields public, or adding a setter nobody asked for. Either one costs the design point.
FRQ 5 · Data Analysis with ArrayList · 22 minutes · 5 points
Averaging and pruning an air-quality log
Directions
Write your answer to each part in the space below. Your response is scored on Java that
would compile: every method header must match the header given in the question exactly,
every variable must be declared, and every object you create must use a constructor that
exists. Use the given classes as specified: read a Reading through its
accessor methods rather than reaching into its private fields, and use the
ArrayList methods size, get and remove
rather than writing your own. Do not write anything the question does not ask for: a method
that is told to return a value must return it, not print it, and it must not change data the
question does not tell it to change. You have about 22 minutes.
A regional agency records fine-particulate readings from several monitoring stations. Each
reading knows which station recorded it, which day of the study it belongs to, and the PM2.5
concentration measured, in micrograms per cubic meter. Readings arrive in the order they are
taken, and the agency keeps them in that order.
The Reading class below is given to you. You will not write any part of it; you
will only call its accessor methods.
public class Reading
{
/** The name of the station that recorded this reading; never null. */
private String station;
/** The day of the study on which this reading was taken; 1 is the first day. */
private int day;
/** The PM2.5 concentration of this reading, in micrograms per cubic meter. */
private double pm25;
public Reading(String s, int d, double p)
{
station = s;
day = d;
pm25 = p;
}
/** @return the name of the station that recorded this reading */
public String getStation()
{
return station;
}
/** @return the day of the study on which this reading was taken */
public int getDay()
{
return day;
}
/** @return the PM2.5 concentration of this reading */
public double getPm25()
{
return pm25;
}
}
The class AirQualityLog stores the readings collected so far. You will write two
of its methods. The declarations of the two methods, with their preconditions and
postconditions, are shown below.
public class AirQualityLog
{
/** The readings in this log, in the order they were recorded.
* Guaranteed not to be null, but it may be empty.
*/
private ArrayList<Reading> readings;
/** Returns the mean of the pm25 values of all readings in this log that were
* recorded at station, or -1.0 if this log contains no reading from station.
* Precondition: station is not null.
* Postcondition: readings is unchanged.
*/
public double averageFor(String station)
{ /* to be implemented in part (a) */ }
/** Removes from this log every reading whose pm25 value is strictly less than
* limit, and returns the number of readings removed.
* Postcondition: the readings that were not removed appear in readings in the
* same relative order in which they appeared before the call.
*/
public int removeBelow(double limit)
{ /* to be implemented in part (b) */ }
// There may be instance variables, constructors, and methods that are not shown.
}
Part (a). Write the method averageFor. The method returns the
mean of the pm25 values of every reading in readings whose station
name is equal to station. If no reading in the log came from that station, and
in particular if readings is empty, the method returns -1.0. The
log itself must not change. Write the complete method, beginning with the header
public double averageFor(String station).
Part (b). Write the method removeBelow. The method removes from
readings every reading whose pm25 value is strictly less than
limit and returns how many readings it removed. Readings whose value is exactly
limit stay. Every reading that is not removed must still be in
readings afterwards, in its original relative order. Write the complete method,
beginning with the header public int removeBelow(double limit).
In the examples below, log is an AirQualityLog whose
readings list holds these six readings, in this order:
North/day 1/12.0, South/day 1/22.0,
North/day 2/25.0, East/day 2/9.0,
North/day 3/18.5, South/day 3/14.0. Each row starts from
that original list.
Call
Value returned
Contents of readings afterwards
log.averageFor("North")
18.5
unchanged (all six readings)
log.averageFor("South")
18.0
unchanged (all six readings)
log.averageFor("East")
9.0
unchanged (all six readings)
log.averageFor("West")
-1.0
unchanged (all six readings)
log.removeBelow(15.0)
3
South/1/22.0, North/2/25.0, North/3/18.5
log.removeBelow(5.0)
0
unchanged (all six readings)
log.removeBelow(30.0)
6
empty
Your code
Scoring notes, where the 5 points are
A reader applies nine checks to your code. This question is scored out of 5, so the checks are grouped into the 5 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 Traversal. Loops over the elements of readings in both parts with bounds that miss no first or last element and run off no end: an index from 0 while i < readings.size() in part (a), and in part (b) a loop that visits every index of the list even while it is shrinking.
+1 Accessing elements with get. Obtains each element as readings.get(i) and reads its data through the given accessors getStation() and getPm25(), never by naming a field of Reading. Same point, also required:Uses the given classes as specified. Uses the ArrayList API correctly (size(), get(int), remove(int) on an ArrayList of Reading), and calls the supplied Reading methods instead of re-implementing or bypassing them.
+1 Comparison logic. Compares station names with equals and not with == in part (a), and in part (b) tests getPm25() < limit strictly, so a reading exactly equal to limit survives.
+1 Accumulation. Declares and initializes a running sum and a match counter before the loop in part (a), and adds getPm25() to the sum and increments the counter on exactly the matching readings, not on every reading. Same point, also required:Correct removal without skipping. In part (b), removes with readings.remove(i) in a way that still examines every reading: a loop running backward from readings.size() - 1 down to 0, or a forward loop that does not increment the index after a successful removal, and increments a removal counter on each removal.
+1 Return. Part (a) returns -1.0 when the counter is 0 and otherwise returns sum / count after the loop finishes, with the division done in double; part (b) returns the removal count after the loop, not from inside it. Same point, also required:Java that would compile. Both headers match public double averageFor(String station) and public int removeBelow(double limit) exactly, every local variable is declared with a type, the element pulled out of the list is typed Reading, and braces, parentheses and semicolons balance. Same point, also required:Design and encapsulation. No side effects beyond the specification and no unnecessary code: averageFor leaves readings untouched, removeBelow changes it only by removing and preserves the survivors' relative order, neither method prints when it is asked to return, and neither traverses the list a second time to do work one pass already did.
Show a full-credit (5/5) solution
Part (a).
public double averageFor(String station)
{
double sum = 0.0;
int count = 0;
for (int i = 0; i < readings.size(); i++)
{
Reading r = readings.get(i);
if (r.getStation().equals(station))
{
sum += r.getPm25();
count++;
}
}
if (count == 0)
{
return -1.0;
}
return sum / count;
}
Part (b).
public int removeBelow(double limit)
{
int removed = 0;
for (int i = readings.size() - 1; i >= 0; i--)
{
if (readings.get(i).getPm25() < limit)
{
readings.remove(i);
removed++;
}
}
return removed;
}
Part (a) is the standard conditional-average shape: two accumulators declared before the
loop, one traversal, a guard for the empty case, and a division that happens once, at the
end. Because sum is a double, sum / count is
double division even though count is an int, so no cast is
needed. The count == 0 test has to come before the division, not after it:
dividing by zero in double arithmetic does not throw, it quietly produces
NaN, and a method that returns NaN where the specification says
-1.0 loses the point silently.
Part (b) walks the list backward. That is the whole trick, and it works for one reason:
removing the element at index i shifts only the elements after
i, and when you are moving toward 0 you have already finished with all of
them. A forward loop shifts the unexamined elements down into positions you have already
passed. A driver that builds the six-reading example, calls each method on a fresh copy of
it and prints each surviving reading as station/day/value produces exactly the table
values:
Point 1.Traversal:for (int i = 0; i < readings.size(); i++) in part (a) visits indexes 0 through 5 of a six-element list, and for (int i = readings.size() - 1; i >= 0; i--) in part (b) visits 5 down to 0. Neither loop touches an index that does not exist.
Point 2.Accessing elements with get: part (a) pulls the element out once into Reading r and then asks it two questions; part (b) chains readings.get(i).getPm25(). Neither reaches for station or pm25 directly, which would not compile from outside Reading. Uses the given classes as specified: only size(), get(int) and remove(int) are used on the list, all three on an ArrayList of Reading, and the two Reading accessors do all the data reading.
Point 3.Comparison logic:r.getStation().equals(station) compares the characters of the two names. In part (b), < limit is strict, so the 22.0 and 25.0 readings survive removeBelow(15.0) and so would a reading of exactly 15.0.
Point 4.Accumulation:sum and count are declared and initialized before the loop, so they survive every pass, and both are updated inside the if, so only North readings contribute to the 12.0 + 25.0 + 18.5 = 55.5 that becomes 18.5. Correct removal without skipping: the backward loop plus readings.remove(i) removes the 14.0, the 9.0 and the 12.0 readings in that order and leaves the three survivors in their original relative order, and removed++ counts each one, giving 3.
Point 5.Return: part (a) returns -1.0 from inside the count == 0 guard and sum / count only after the loop has seen every reading; part (b) returns removed after the loop, so it reports the total rather than 1 on the first removal. Java that would compile: both headers are copied from the question, double sum, int count, Reading r, int removed and both loop variables are declared, and every path out of each method returns a value of the declared type. Design and encapsulation:averageFor never calls a mutator, so readings is unchanged as the postcondition requires; removeBelow does its counting in the same pass that does its removing rather than counting first and removing second; and neither method prints anything.
Common ways to lose points. The forward-removal skip is the single most
common error on this question type. Written as
for (int i = 0; i < readings.size(); i++) with a
readings.remove(i) inside, the loop misses any reading that lands in slot
i because its predecessor was just deleted. On this list the bug hides at
limit 15.0 (the qualifying readings happen not to be adjacent, so the buggy
version also returns 3), but at limit 20.0 the correct method returns 4 and
leaves South/1/22.0 and North/2/25.0, while the forward version returns 3 and leaves
South/1/22.0, North/2/25.0 and North/3/18.5: the 18.5 reading slid into the index the
loop had already moved past. Never trust a removal loop that you only tested on data
whose targets are spread out.
The second trap is writing part (b) as an enhanced for loop. Removing from a
list while a for (Reading r : readings) loop is iterating over it throws
java.util.ConcurrentModificationException at run time, which is a real crash
and costs the correctness points for the part. The enhanced for is the right
tool for part (a), where nothing is modified, and the wrong tool for part (b). Two more
point-losers show up every year: comparing station names with ==, which
compares references and returns false for two equal names built separately;
and returning 0.0 or 0 instead of -1.0 for the
no-match case, which throws away the edge-case point even though the rest of the method is
perfect. Finally, the design point goes to responses that do one job per method: an
averageFor that "helpfully" deletes bad readings, or a
removeBelow that prints its count as well as returning it, has side effects
the specification never asked for.
FRQ 6 · Data Analysis with ArrayList · 22 minutes · 5 points
Keeping a delivery log sorted and reporting the late orders
Directions
Write your answer to each part in the space below. Your response is scored on Java that
would compile: each method header must match the header given in the question exactly,
every variable must be declared with a type, and every object you create must use a
constructor that exists. Use the given classes as specified: read an Order
through its accessor methods rather than its private fields, and use the
ArrayList methods size, get and add
rather than writing your own. Do not write anything the question does not ask for: a method
told to return a value must return it rather than print it, and it must not change data the
question does not tell it to change. You have about 22 minutes.
A delivery service records each completed order together with the number of minutes the
delivery took. The dispatcher wants the log kept in increasing order of delivery time at all
times, so that the slowest deliveries are always at the end and no sorting pass is ever
needed, and wants to be able to pull the names of the customers whose orders ran long.
The Order class below is given to you. You will not write any part of it; you
will only call its accessor methods.
public class Order
{
/** The name of the customer who placed this order; never null. */
private String customer;
/** The delivery time of this order, in minutes; never negative. */
private int minutes;
public Order(String c, int m)
{
customer = c;
minutes = m;
}
/** @return the name of the customer who placed this order */
public String getCustomer()
{
return customer;
}
/** @return the delivery time of this order, in minutes */
public int getMinutes()
{
return minutes;
}
}
The class DeliveryLog stores the completed orders. Its list is always kept in
increasing order of getMinutes(). You will write two of its methods; their
declarations, preconditions and postconditions are shown below.
public class DeliveryLog
{
/** The completed orders, in increasing order of getMinutes().
* Guaranteed not to be null, but it may be empty.
*/
private ArrayList<Order> orders;
/** Inserts o into orders so that orders remains in increasing order of
* getMinutes(), placing o after every order already in the list whose
* minutes are equal to o.getMinutes(), and returns the index at which
* o was inserted.
* Precondition: o is not null; orders is in increasing order of getMinutes().
* Postcondition: orders has one more element than before, it is still in
* increasing order of getMinutes(), and the returned index
* is the position of o in orders.
*/
public int insertInOrder(Order o)
{ /* to be implemented in part (a) */ }
/** Returns a new list containing the customer name of every order in this log
* whose delivery time is strictly greater than limit, in the order those
* orders appear in orders, keeping repeated names.
* Postcondition: orders is unchanged; an empty list is returned when no
* order took more than limit minutes.
*/
public ArrayList<String> lateCustomers(int limit)
{ /* to be implemented in part (b) */ }
// There may be instance variables, constructors, and methods that are not shown.
}
Part (a). Write the method insertInOrder. The method puts
o into orders at the one position that keeps the list in increasing
order of getMinutes(), and it returns the index where o ended up.
When the list already contains one or more orders with exactly the same delivery time,
o goes after all of them. Inserting into an empty log puts
o at index 0 and returns 0; inserting an order slower than every order already
in the log appends it to the end. Write the complete method, beginning with the header
public int insertInOrder(Order o).
Part (b). Write the method lateCustomers. The method returns a
new ArrayList<String> holding the customer name of every order whose
delivery time is strictly greater than limit, in the same order those orders
appear in orders. A customer who has two late orders appears twice. An order
that took exactly limit minutes is not late. If no order qualifies, the method
returns an empty list, not null. The log itself must not change. Write the
complete method, beginning with the header
public ArrayList<String> lateCustomers(int limit).
In the examples below, log is a DeliveryLog whose
orders list starts as Ortiz/22, Chen/35,
Ortiz/41, and empty is a DeliveryLog whose
orders list is empty. Each call on log is made on the list the row
above it left behind.
Call
Contents of orders before
Value returned
Contents of orders after
log.insertInOrder(new Order("Chen", 35))
Ortiz/22, Chen/35, Ortiz/41
2
Ortiz/22, Chen/35, Chen/35, Ortiz/41
log.insertInOrder(new Order("Nawaz", 50))
Ortiz/22, Chen/35, Chen/35, Ortiz/41
4
Ortiz/22, Chen/35, Chen/35, Ortiz/41, Nawaz/50
log.lateCustomers(30)
Ortiz/22, Chen/35, Chen/35, Ortiz/41, Nawaz/50
[Chen, Chen, Ortiz, Nawaz]
unchanged
log.lateCustomers(41)
Ortiz/22, Chen/35, Chen/35, Ortiz/41, Nawaz/50
[Nawaz]
unchanged
log.lateCustomers(90)
Ortiz/22, Chen/35, Chen/35, Ortiz/41, Nawaz/50
[]
unchanged
empty.insertInOrder(new Order("Pike", 15))
(empty)
0
Pike/15
Your code
Scoring notes, where the 5 points are
A reader applies nine checks to your code. This question is scored out of 5, so the checks are grouped into the 5 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 Traversal. Part (a) scans orders from index 0 with a bound that stops at orders.size(), so an empty log and a new slowest order both fall out of the scan instead of reading an element that is not there; part (b) visits every element of orders exactly once, from index 0 to orders.size() - 1.
+1 Accessing elements with get. Reads each stored order as orders.get(i) and takes its data from the given accessors getMinutes() and getCustomer(), never by naming a field of Order. Same point, also required:Uses the given classes as specified. Uses the ArrayList API correctly (size(), get(int), add(int, Order) for the insertion and add(String) for the result) with the type parameters ArrayList<Order> and ArrayList<String>, and calls the supplied Order methods instead of re-implementing them.
+1 Comparison logic. Part (a) keeps scanning while the stored order's minutes are less than or equal too.getMinutes(), which is what places a tie after the orders it ties with; part (b) tests getMinutes() > limit strictly, so an order of exactly limit minutes is not reported.
+1 Accumulation. Part (b) creates a new ArrayList<String> before the loop and adds getCustomer() to it on exactly the qualifying passes, so repeated names are kept and the names come out in list order. Same point, also required:Correct insertion without skipping or disturbing order. Part (a) calls orders.add(index, o) exactly once, at the index the scan stopped at, and does not remove, re-add or rebuild the list; every element from that index on shifts right by one and the list is still sorted.
+1 Return. Part (a) returns the index at which o landed, after the insertion, not from inside the scan, and not printed; part (b) returns the built list after the loop, returning an empty list rather than null when nothing qualifies. Same point, also required:Java that would compile. Both headers match public int insertInOrder(Order o) and public ArrayList<String> lateCustomers(int limit) exactly, the result list is created with new ArrayList<String>(), every local variable is declared, the index variable is declared outside the scan so it is still in scope at the return, and braces, parentheses and semicolons balance. Same point, also required:Design and encapsulation. No side effects beyond the specification and no unnecessary code: lateCustomers builds a new list and leaves orders completely untouched, insertInOrder changes orders only by the single insertion the question asks for, neither method prints when it is asked to return, neither traverses the list a second time, and no variable is declared that is never used.
Show a full-credit (5/5) solution
Part (a).
public int insertInOrder(Order o)
{
int index = 0;
while (index < orders.size() && orders.get(index).getMinutes() <= o.getMinutes())
{
index++;
}
orders.add(index, o);
return index;
}
Part (b).
public ArrayList<String> lateCustomers(int limit)
{
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < orders.size(); i++)
{
Order o = orders.get(i);
if (o.getMinutes() > limit)
{
names.add(o.getCustomer());
}
}
return names;
}
Part (a) is a scan that stops, not a scan that finishes. The while loop walks
index forward as long as two things are true: there is still an element to
look at, and that element belongs in front of o. The moment either fails,
index is exactly the slot o should occupy, and
add(index, o) puts it there and shifts everything from that slot onward one
place to the right. The order of the two tests joined by && is not a
style choice: && short-circuits, so index < orders.size()
must come first or the call orders.get(index) will run on an index past the
end. Part (b) is the plainest possible build-a-new-list traversal: declare the result
before the loop, look at every order once, append a name when the test passes, return the
result after the loop. A driver that builds the example log, makes each call in turn and
prints each order as customer/minutes produces exactly the table values:
Point 1.Traversal: the while in part (a) starts at 0 and is guarded by index < orders.size(), so on an empty log it never runs (index stays 0) and on the 50-minute insertion it stops with index equal to 4, the size of the list. The for in part (b) runs i from 0 through 4 on the five-element list.
Point 2.Accessing elements with get: part (a) uses orders.get(index).getMinutes() and part (b) pulls the element into Order o once and then asks it for both its minutes and its customer. Neither touches customer or minutes directly, which would not compile outside Order. Uses the given classes as specified: only size(), get(int), add(int, Order) and add(String) are used, each on a list with the right type parameter, and both Order accessors do all the reading.
Point 3.Comparison logic:<= in part (a) is what makes the tie land after the existing 35-minute order and return 2 instead of 1; > limit in part (b) is what keeps the 41-minute order out of lateCustomers(41) while leaving Nawaz in.
Point 4.Accumulation:names is created before the loop, so it survives every pass, and names.add(o.getCustomer()) runs only inside the if, which is why lateCustomers(30) returns four names, keeping the repeated Chen, and lateCustomers(90) returns an empty list. Correct insertion without skipping or disturbing order: a single orders.add(index, o) does the whole job. The list is never rebuilt, nothing is removed, and the elements at and after index shift right, so Ortiz/41 moves from index 2 to index 3 and the list is still sorted.
Point 5.Return: part (a) returns index after the insertion, so the caller learns where the order landed; part (b) returns names after the loop rather than returning on the first match, which is why all four late names come back instead of only the first. Java that would compile: both headers are copied from the question, int index is declared before the while so it is still in scope at the return, names is declared as ArrayList<String> and created with new, and every path out of each method returns a value of the declared type. Design and encapsulation:lateCustomers calls no mutator on orders, so the postcondition "orders is unchanged" holds, as the last driver line confirms; insertInOrder performs exactly one insertion; neither method prints; and neither walks the list twice when one pass does the work.
Common ways to lose points. The first is the comparison that decides the
tie. Writing the scan as orders.get(index).getMinutes() < o.getMinutes()
stops one slot too early on a tie: on the example list that call returns 1 instead of 2
and leaves the new order in front of the 35-minute order already there. The list
is still sorted, so the bug is easy to miss, but the returned index is wrong and the
specification's "after any order with the same minutes" is broken. The second is dropping
the index < orders.size() guard, or putting it after the get.
Inserting Nawaz/50 then crashes with
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3, and
inserting into an empty log crashes with
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0:
both of the edge cases the question spells out.
The third is reaching for an enhanced for loop in part (a). An
ArrayList may not be structurally modified while a
for (Order cur : orders) loop is iterating over it, so a version that calls
orders.add(index, o) inside the loop and keeps going throws
java.util.ConcurrentModificationException at run time. The enhanced
for also hides the index, and the index is the value you have to return, so
it is the wrong tool here twice over. The fourth is answering part (b) by emptying
orders of the on-time orders and reading off what is left. That is where the
forward-removal skip from the sibling question bites: a
for (int i = 0; i < orders.size(); i++) loop that removes at
i steps over the element that slides into the vacated slot, so on the final
list it reports [Chen, Ortiz, Nawaz] for limit 40 instead of the
correct [Ortiz, Nawaz], and the same idea written with an enhanced
for throws ConcurrentModificationException instead. Even when
such a version somehow produces the right names, it destroys the caller's log, which
costs the design point outright: the question says to return a new list, so build a new
list. Finally, printing the index or the names instead of returning them, or returning
null when nothing qualifies, both fail the return point even though the
traversal above them is correct.
FRQ 7 · 2D Array · 22 minutes · 6 points
Seating chart
A campus lecture hall tracks its seats in a rectangular grid. The class SeatingChart
stores that grid in a private two-dimensional array of int called seats,
where seats[r][c] is 0 when the seat in row r, column
c is empty and 1 when it is taken. Row 0 is the front row
and column 0 is the left-hand aisle. The grid is rectangular: every row has the same
number of columns, so seats.length is the number of rows and
seats[0].length is the number of columns in each row. The constructor is written for
you.
The registrar needs two pieces of information. First, when a block of seats is reserved for a
visiting group, the office needs to know how many seats inside that block are already taken.
Second, when a late student arrives, the usher needs to know which row has the most room. You
will write the two methods that answer those questions. Both methods read the grid; neither one
changes it.
public class SeatingChart
{
/** seats[r][c] is 0 when the seat in row r, column c is empty
* and 1 when that seat is taken.
*/
private int[][] seats;
/** Constructs a seating chart from initial.
* Precondition: initial is rectangular and contains only 0 and 1.
*/
public SeatingChart(int[][] initial)
{
seats = initial;
}
/** Returns the number of taken seats inside the rectangle whose opposite
* corners are (startRow, startCol) and (endRow, endCol), counting both
* corners and every seat between them.
* Precondition: 0 <= startRow <= endRow < seats.length
* 0 <= startCol <= endCol < seats[0].length
* Postcondition: seats is not changed.
*/
public int countTaken(int startRow, int startCol, int endRow, int endCol)
{
/* to be implemented in part (a) */
}
/** Returns the index of the row that holds the most empty seats.
* If two or more rows tie, the smallest such index is returned.
* Returns -1 if seats has no rows.
* Postcondition: seats is not changed.
*/
public int emptiestRow()
{
/* to be implemented in part (b) */
}
// There may be instance variables, constructors, and methods that are not shown.
}
The examples below all refer to a SeatingChart named hall built from
this 4-by-5 grid. The row and column labels are the indexes, not part of the data.
col 0
col 1
col 2
col 3
col 4
row 0
1
0
1
0
1
row 1
0
1
1
0
1
row 2
0
0
1
1
0
row 3
1
1
0
1
1
Call
Value returned
Why
hall.countTaken(1, 1, 2, 3)
4
Rows 1 and 2, columns 1 through 3: the 1s at (1,1), (1,2), (2,2) and (2,3).
hall.countTaken(0, 0, 3, 4)
12
The whole hall: 3 + 3 + 2 + 4 taken seats.
hall.countTaken(0, 2, 0, 2)
1
A one-seat rectangle. Both corners are the same seat, and it is taken.
hall.countTaken(3, 0, 3, 4)
4
All of row 3, which holds four taken seats and one empty seat.
hall.emptiestRow()
2
Empty counts by row are 2, 2, 3, 1, so row 2 has the most room.
Part (a). Write the method countTaken. It returns how many taken
seats lie inside the rectangle whose opposite corners are row startRow column
startCol and row endRow column endCol. Both corners count,
and so does every seat between them, so a rectangle from row 1 to row 2 covers rows 1 and
2. Precondition: all four values are legal indexes, startRow is at most
endRow, and startCol is at most endCol. Postcondition:
seats is unchanged. Complete the method below.
public int countTaken(int startRow, int startCol, int endRow, int endCol)
Part (b). Write the method emptiestRow. It returns the index of the
row holding the most empty seats. If two or more rows are tied for the most empty seats, return
the smallest of those indexes. If the chart has no rows at all, return -1. There is
no precondition on the number of rows, so seats.length may be 0; you may
assume that when there is at least one row the grid is rectangular. Postcondition:
seats is unchanged. Complete the method below.
public int emptiestRow()
Directions
You have 22 minutes and 6 points. Write your answer in Java, as a method body that would
compile if it were dropped into the SeatingChart class exactly as shown. Use the
class as it is given: seats is the instance variable you read, and you may not add
parameters to a header or change a header that the question supplies. Size your loops from the
array itself with seats.length and seats[0].length rather than the
numbers 4 and 5, because the grader will run your code on charts of other sizes. Do not print
anything; each method returns a value. Do not modify seats. Partial credit is real,
so write the loop you are sure of even if an edge case is still troubling you, but code that
cannot compile earns nothing in that part.
Your code
Scoring notes · 6 points
A reader applies nine checks to your code. This question is scored out of 6, so the checks are grouped into the 6 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 traverses every row and every column of the chart in emptiestRow, the outer loop over rows and the inner loop over columns, visiting each seat exactly once.
+1 uses two-dimensional array syntax correctly: seats[r][c] with the row index first and the column index second, and seats.length for the number of rows and seats[0].length for the number of columns, each written with no parentheses.
+1 tests the condition the specification states: counts a seat in countTaken when its value is 1, and counts a seat in emptiestRow when its value is 0.
+1 declares and initializes the local variables before the loops that use them: a counter set to 0 in countTaken, and in emptiestRow both a best-row index and a most-empty-so-far value, with the per-row empty counter reset to 0 at the top of every row. Same point, also required: accumulates correctly: increments the rectangle counter on every taken seat, and after each row compares that row's empty count against the best seen so far, storing both the new count and the row index when it is larger.
+1 uses a nested loop with correct bounds in countTaken: the outer loop runs from startRow while the index is at most endRow, the inner loop from startCol while the index is at most endCol. The tests are at-most, not less-than, so the last row and last column of the rectangle are counted.
+1 returns the right value at the right time: the rectangle count after both loops finish, not inside them; the best row index after the outer loop; and -1 before any loop runs when seats.length is 0. Ties keep the smaller index because the comparison is strictly greater, never greater-or-equal. Same point, also required: writes Java that would compile: both headers copied exactly as given and returning int, every local variable declared with a type, every loop variable used inside its own scope, and braces and semicolons balanced. Same point, also required: design and encapsulation: neither method assigns to seats or to any of its elements, neither prints instead of returning, each traverses only the data it needs one time, no variable is declared and never used, and seats stays private and is read directly only inside SeatingChart.
Show a full-credit (6/6) solution
Part (a). The rectangle is given by its two corners, so the loop variables start at the
corner indexes and the tests are <=. Nothing else about the grid matters.
public int countTaken(int startRow, int startCol, int endRow, int endCol)
{
int count = 0;
for (int r = startRow; r <= endRow; r++)
{
for (int c = startCol; c <= endCol; c++)
{
if (seats[r][c] == 1)
{
count++;
}
}
}
return count;
}
Part (b). Here the whole chart is traversed. The outer loop walks the rows; the inner loop
counts the empty seats in one row; after the inner loop finishes, that row's count is compared
against the best seen so far. Starting mostEmpty at -1 guarantees
that row 0 replaces it, even in a chart where every seat is taken and every row has zero empty
seats.
public int emptiestRow()
{
if (seats.length == 0)
{
return -1;
}
int best = 0;
int mostEmpty = -1;
for (int r = 0; r < seats.length; r++)
{
int empty = 0;
for (int c = 0; c < seats[0].length; c++)
{
if (seats[r][c] == 0)
{
empty++;
}
}
if (empty > mostEmpty)
{
mostEmpty = empty;
best = r;
}
}
return best;
}
Compiled and run on the 4-by-5 chart above, the two methods print exactly the values in the
examples table, plus the per-row empty counts that explain part (b):
Point 1.Full traversal:emptiestRow runs r from 0 to seats.length - 1 and c from 0 to seats[0].length - 1, so every seat is examined once and no row is skipped.
Point 2.Array syntax: every access is seats[r][c], row first and column second; the sizes come from seats.length and seats[0].length, written without parentheses, so the methods work on a chart of any rectangular size.
Point 3.The test:seats[r][c] == 1 for taken in part (a) and seats[r][c] == 0 for empty in part (b). Reversing these is the single most common way to lose this point.
Point 4.Local variables:int count = 0; sits before the nested loop, and best, mostEmpty and the per-row empty are each declared where they belong. empty is declared inside the outer loop, which is what resets it to zero at the start of every row. Accumulation:count++ on each taken seat; empty++ on each empty seat; and the update of mostEmpty and best together, so the stored index always belongs to the stored count.
Point 5.Bounds:r = startRow; r <= endRow and c = startCol; c <= endCol. The rectangle is inclusive at both ends, so both tests are at-most.
Point 6.Returns and edge cases:return count; is after both loops, return best; is after the outer loop, and the guard if (seats.length == 0) return -1; handles the no-rows chart before seats[0] is ever evaluated. The strict > keeps the smaller index on a tie: the run above shows a tied chart returning 0. It compiles: both headers match the ones in the class exactly, every variable has a declared type, and each loop variable is used only inside its own loop. No side effects: neither method writes to seats, neither prints, each makes one pass over the data it needs, and no unused variable is declared. seats remains private and is touched only from inside its own class.
Common ways to lose points. The first is the off-by-one: writing
r < endRow and c < endCol out of habit. That drops the last row
and last column of the rectangle, and the compiler will never complain. Run on the chart above
it turns countTaken(1, 1, 2, 3) into 2 and
countTaken(0, 0, 3, 4) into 6: both wrong, and it costs the bounds
point. The second is swapping the indexes, writing seats[c][r] inside the column
loop. On a square grid that quietly returns the wrong answer; on this 4-by-5 chart the column
index reaches 4 and the run ends in
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4. The
third is confusing the two lengths: seats.length is the number of rows
and seats[0].length is the number of columns, so using
seats.length as the column bound is another out-of-bounds crash on any chart that
is not square. A fourth, quieter mistake is initializing mostEmpty to 0
instead of -1 and forgetting the no-rows guard: in a completely full hall every row
ties at zero empty seats, and an accidental >= comparison would then return the
last row instead of the first, losing the edge-case point.
FRQ 8 · 2D Array · 22 minutes · 6 points
Rainfall grid
A weather station logs its rainfall readings in a rectangular grid. The class
RainfallGrid stores that grid in a private two-dimensional array of
int called data. Each row is one week and each
column is one of the fixed collection days in that week, so
data[r][c] is the rainfall recorded in week r on collection
day c, measured in whole millimeters and never negative. The grid is
rectangular: data.length is the number of weeks and
data[0].length is the number of collection days per week. The constructor
is written for you.
The station's report needs two summaries. The first is a day-by-day total: how much rain
fell on collection day 0 across all the weeks, on day 1 across all the weeks, and so on.
That summary is a one-dimensional array with one slot per column, which means the traversal
has to run down a column before it moves to the next one. The second summary counts
peaks: cells that are strictly wetter than every neighbor directly above, below,
left and right of them. A cell in the top row has no neighbor above it, a cell in the left
column has none to its left, and a corner cell has only two neighbors: a peak is judged
only against the neighbors it actually has.
public class RainfallGrid
{
/** data[r][c] is the rainfall recorded in week r on collection day c.
* Every value is at least 0.
*/
private int[][] data;
/** Constructs a rainfall grid from initial.
* Precondition: initial is rectangular and contains only values >= 0.
*/
public RainfallGrid(int[][] initial)
{
data = initial;
}
/** Returns a new one-dimensional array whose element at index c is the
* sum of all the values in column c of data.
* Returns an array of length 0 when data has no rows.
* Postcondition: data is not changed.
*/
public int[] columnTotals()
{
/* to be implemented in part (a) */
}
/** Returns the number of cells of data whose value is strictly greater
* than the value of every neighbor that exists directly above, below,
* to the left of, and to the right of that cell. Diagonal cells are not
* neighbors. A cell on an edge or in a corner simply has fewer
* neighbors to beat.
* Postcondition: data is not changed.
*/
public int countPeaks()
{
/* to be implemented in part (b) */
}
// There may be instance variables, constructors, and methods that are not shown.
}
The examples below refer to a RainfallGrid named season built from
this 3-by-4 grid, and to three smaller grids: oneWeek, which holds the single
row 5 2 9; flat, which holds the two rows 4 4 and
1 2; and blank, which has no rows at all. The row and column labels
are the indexes, not part of the data.
col 0
col 1
col 2
col 3
row 0
3
8
2
5
row 1
4
6
9
1
row 2
7
2
5
3
Call
Value returned
Why
season.columnTotals()
an array holding 14, 16, 16, 9
Column 0 is 3 + 4 + 7, column 1 is 8 + 6 + 2, column 2 is 2 + 9 + 5, column 3 is 5 + 1 + 3.
season.countPeaks()
4
The cells holding 8, 5, 9 and 7: that is (0,1), (0,3), (1,2) and (2,0).
oneWeek.columnTotals()
an array holding 5, 2, 9
With one row, each column total is that row's single value.
oneWeek.countPeaks()
2
5 beats its only neighbor 2, and 9 beats its only neighbor 2. The 2 in the middle beats neither.
flat.countPeaks()
0
The two 4s are tied with each other, and a tie is not strictly greater, so neither one is a peak.
blank.columnTotals()
an array of length 0
A grid with no rows has no columns to total.
Part (a). Write the method columnTotals. It returns a
new one-dimensional array whose element at index c is the sum of every
value in column c of data. The returned array must have exactly one
slot per column. Precondition: none beyond the class invariant; data.length may
be 0, and in that case the method returns an array of length 0.
Postcondition: data is unchanged. Complete the method below.
public int[] columnTotals()
Part (b). Write the method countPeaks. It returns how many cells
of data are strictly greater than every neighbor that exists directly above,
below, to the left of and to the right of that cell. Diagonals are not neighbors, a cell on
an edge is judged only against the neighbors it has, and a cell tied with any one of its
neighbors is not a peak. Precondition: none beyond the class invariant. Postcondition:
data is unchanged. Complete the method below.
public int countPeaks()
Directions
You have 22 minutes and 6 points. Write your answer in Java, as method bodies that would
compile if they were dropped into the RainfallGrid class exactly as shown. Use
the class as it is given: data is the instance variable you read, and you may
not change a header the question supplies or add parameters to it. Take every bound from the
array itself: data.length for weeks, data[0].length for collection
days, because the grader will run your code on grids of other sizes. Do not print anything;
part (a) returns an array and part (b) returns an int. Do not modify
data or any of its elements. Partial credit is real, so write the traversal you
are sure of even if one bounds guard is still troubling you, but code that cannot compile
earns nothing in that part.
Your code
Scoring notes · 6 points
A reader applies nine checks to your code. This question is scored out of 6, so the checks are grouped into the 6 points the exam awards for this type of question, and a point is earned when every check inside it is met.
+1 uses array syntax and the Java API correctly: data[r][c] with the row index first and the column index second, data.length and data[0].length written with no parentheses, and the result array created with new int[…] at a length taken from the grid rather than a hard-coded 3 or 4.
+1 guards all four neighbor accesses with a bounds test evaluated before the element is read: r - 1 >= 0, r + 1 < data.length, c - 1 >= 0 and c + 1 < data[0].length, so an edge or corner cell is judged only against the neighbors that exist and no access runs off the grid.
+1 compares strictly: a cell counts only when its value is greater than each existing neighbor, so a cell tied with a neighbor is disqualified and a greater-or-equal test does not earn this point.
+1 declares and initializes before looping: creates the result array with new int[data[0].length] (one slot per column, not one per row), and sets a running sum to 0 at the start of each column, and a peak counter to 0 before the traversal in part (b). Same point, also required: accumulates correctly: adds data[r][c] into the running sum on every pass of the inner loop, stores that sum at totals[c] once the column is finished, and increments the peak counter exactly once per qualifying cell in part (b).
+1 uses a column-major nested loop with correct bounds in columnTotals: the outer loop over columns while the index is less than data[0].length, the inner loop over rows while the index is less than data.length, so every cell of every column is added and no first or last column is missed.
+1 returns the right value of the right type at the right time: the totals array after the loops finish rather than inside them, an array of length 0 when data.length is 0, and the peak count after the whole grid has been traversed. Same point, also required: writes Java that would compile: both headers copied exactly as given, part (a) declared to return int[] and part (b) int, every local variable declared with a type, each loop variable used only inside its own scope, and braces and semicolons balanced. Same point, also required: design and encapsulation: builds and returns a new array instead of writing into data, changes no element of the grid, prints nothing, makes a single pass for each summary rather than re-traversing, declares no variable it never uses, and keeps data private and read only from inside RainfallGrid.
Show a full-credit (6/6) solution
Part (a). The shape of the answer decides the shape of the loop. One result per column means
the column index is the one that advances on the outside, and the row index runs down the
column on the inside. The guard for the empty grid comes first, because
data[0].length cannot be evaluated on a grid with no rows.
public int[] columnTotals()
{
if (data.length == 0)
{
return new int[0];
}
int[] totals = new int[data[0].length];
for (int c = 0; c < data[0].length; c++)
{
int sum = 0;
for (int r = 0; r < data.length; r++)
{
sum += data[r][c];
}
totals[c] = sum;
}
return totals;
}
Part (b). Here the traversal order does not matter, every cell is tested, but each of the
four neighbor comparisons must be protected by its own bounds test. Writing the test as
"assume it is a peak, then look for a reason it is not" keeps the four guards independent,
and because Java evaluates && left to right, the bounds test always runs
before the array access it protects.
public int countPeaks()
{
int count = 0;
for (int r = 0; r < data.length; r++)
{
for (int c = 0; c < data[0].length; c++)
{
boolean peak = true;
if (r - 1 >= 0 && data[r][c] <= data[r - 1][c])
{
peak = false;
}
if (r + 1 < data.length && data[r][c] <= data[r + 1][c])
{
peak = false;
}
if (c - 1 >= 0 && data[r][c] <= data[r][c - 1])
{
peak = false;
}
if (c + 1 < data[0].length && data[r][c] <= data[r][c + 1])
{
peak = false;
}
if (peak)
{
count++;
}
}
}
return count;
}
Compiled and run on the four grids named in the question, the two methods produce exactly the
values in the examples table:
columnTotals() -> [14, 16, 16, 9]
countPeaks() -> 4
-- which cells are peaks --
peak at (0, 1) value 8
peak at (0, 3) value 5
peak at (1, 2) value 9
peak at (2, 0) value 7
one-row grid 5 2 9: columnTotals() -> [5, 2, 9], countPeaks() -> 2
tied grid 4 4 / 1 2: countPeaks() -> 0
empty grid: columnTotals().length -> 0, countPeaks() -> 0
Where the 6 points are earned
Point 1.Array syntax: every access is data[r][c], row first and column second, even in part (a) where the column index is the outer loop variable; length is written with no parentheses; the new array's size comes from the grid.
Point 2.The four bounds guards:r - 1 >= 0, r + 1 < data.length, c - 1 >= 0 and c + 1 < data[0].length, each joined to its comparison with &&, so the guard is evaluated first and the element is never read out of bounds. The value 5 at (0,3) is a peak precisely because it has no neighbor above it and none to its right.
Point 3.Strictly greater: the disqualifying test is <=, which means a cell counts only when it is strictly greater than each existing neighbor. On the grid 4 4 / 1 2 the run above returns 0, which is the behavior this point is checking.
Point 4.Declaration and array creation:new int[data[0].length] gives one slot per column, and int sum = 0; is declared inside the outer loop so it resets at the top of every column. The peak counter is initialized to 0 before the traversal. Accumulation:sum += data[r][c]; on each pass down the column, then totals[c] = sum; exactly once when that column finishes; count++ once per peak.
Point 5.Column-major bounds: the outer loop is c < data[0].length and the inner is r < data.length. Getting these two the wrong way round is the defining error of this question type.
Point 6.Returns and the empty grid:return totals; comes after the loops, return count; after the whole traversal, and return new int[0]; handles the no-rows grid before data[0] is ever evaluated. It compiles:public int[] columnTotals() and public int countPeaks() match the given headers exactly, totals, sum, count and peak are all declared with types, and peak is declared inside the inner loop so it is fresh for every cell. No side effects: part (a) returns a brand-new array and never assigns to data[r][c]; neither method prints; each makes one pass over the grid; no unused variable is declared; and data stays private, read only from inside its own class.
Common ways to lose points. The first is confusing the two lengths.
data.length is the number of rows and data[0].length is the
number of columns, so new int[data.length] builds an array of 3 slots for
a grid that has 4 columns; the fourth totals[c] = sum; then ends the run with
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3.
The second is swapping the roles of the indexes: looping row-major and storing at
totals[r] instead of totals[c] compiles cleanly and quietly returns
[18, 20, 17, 0], the three row sums followed by an untouched zero, so
only running the examples catches it. The third is dropping the bounds guards in part (b) and
reading data[r - 1][c] on the top row, which fails immediately with
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3;
the related off-by-one is writing r + 1 <= data.length, which lets the last row
reach one past the end. The fourth is the tie: using < instead of
<= as the disqualifier turns the test into greater-or-equal and reports
2 peaks on the grid 4 4 / 1 2 where the correct answer is
0. Note that this last error is invisible on the 3-by-4 sample grid, which has no
ties and still returns 4 either way: a reminder that passing the given examples is not the
same as being correct.
Unit recap
Unit recap
0:00 / 0:00
Animated recap with on-screen narration. Turn on Voice to
have it read aloud (uses your device's built-in voice). Pressing play
counts as your one free video.
Free preview complete
That's the end of the free preview.
You've opened five lessons, which is
as much as we can show without a subscription. Everything you've
already opened stays available; use the outline on the left to go
back to it.