Unit 01
Using Objects and Methods
By the end of this unit you can read a line of Java out loud, say what every piece of it does, and predict what it prints before you run it.
Every check for understanding filed under this unit, and where each one stands with your classes. The whole console →
- Picking the type checking
- Where the remainder went checking
- What binds tighter checking
- Counting from zero checking
- Copies and arrows checking
Programming is not typing. Programming is deciding exactly what should happen, in what order, with no step left implied. Then typing. The typing is the easy part, which is why this unit spends as much time on reading code as on writing it.
Everything in Unit 1 is in service of one skill: look at a few lines of Java and say what they do before you run them. That is what the exam asks, over and over, and it is also what separates a programmer from someone who changes things until the errors stop.
1.1 · Algorithms, programming, and compilers
An algorithm is a step-by-step process for finishing a task. You already write them: a recipe, directions to the gym, the order you put on hockey gear. What makes them algorithms rather than suggestions is that the steps are sequenced: step four assumes steps one through three already happened.
Java is how we hand an algorithm to a machine that has no judgment whatsoever. Between your typing and the machine there are two translations:
- The compiler reads your source file (
Hello.java) and turns it into bytecode (Hello.class). It refuses if you broke the rules of the language. - The Java Virtual Machine (JVM) runs that bytecode. Because every platform
has its own JVM, the same
.classfile runs on your Mac, the lab PCs, and a server in Virginia.
That two-step is why Java errors arrive at two different times, and telling them apart is worth real points:
- A compile-time error means the code never became a program. A missing
semicolon, a misspelled type, a
Stringwhere anintwas required. Nothing ran. - A run-time error means it compiled fine and then failed while running, like dividing by zero or reaching past the end of an array. The compiler could not have known.
- A logic error means it compiled and ran and gave the wrong answer. No error message at all. These are the expensive ones.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
A program compiles and runs, but the average it prints is always slightly too low. What kind of error is this?
No message, no crash, wrong answer. That is a logic error. The machine did exactly what you said, which was not what you meant. Integer division is a common culprit for an average that comes out low.
1.2 · Variables and data types
A type is a set of values plus the operations you can perform on them. That definition does real work: it tells you that choosing a type is choosing what is possible, not just what fits.
This course uses exactly three primitive types:
| Type | Holds | Examples |
|---|---|---|
int |
whole numbers | -4, 0, 2026 |
double |
real numbers | 3.5, -0.001 |
boolean |
one of two truth values | true, false |
Java has five more primitives (long, short, byte, float, char) and
they are explicitly outside this course. Don’t use them; they will not
appear on the exam.
Everything else is a reference type: String, Math, and any class you
write. The difference matters later, and matters a lot. A primitive variable
holds a value. A reference variable holds a way to find a value.
int students = 24;
double average = 91.5;
boolean isHockeySeason = true;
A variable is a named storage location with a type attached. The type never changes; the value can. Read the declaration right to left: take 24, and store it in an int called students.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
You need to store the price of a textbook. Which declaration is best?
Pick the type whose set of values matches the fact you are storing. Prices have fractional parts, so double. Note that int price = 74.95; is a compile-time error. Java will not quietly drop the cents for you.
What things are called
The compiler accepts any legal name. It does not care. Everyone who reads your code afterwards cares a great deal, because the shape of a name is how you tell at a glance what kind of thing it is.
| Kind of thing | Convention | Yes | No |
|---|---|---|---|
| Variable | camelCase | totalPoints | Total_Points |
| Method | camelCase, a verb | getScore() | Score() |
| Class | PascalCase, a noun | Scanner | scanner |
| Constant | SCREAMING_SNAKE_CASE | MAX_SCORE | maxScore |
| Package | all lowercase | java.util | Java.Util |
Two rules cover almost everything:
- Capital first letter means a type.
Scanner,String,Math. If it starts with a capital, you can saynewin front of it or call a method on the name itself. - Lowercase first letter means a value.
total,name,getScore().
Which case to use is one of the oldest arguments in programming, and it is not settled anywhere except within a language. Java picked camelCase. Python picked snake_case. Both work. Mixing them inside one file does not.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Which line follows Java naming convention?
The compiler accepts all four. Every one of them runs. Convention is not about legality — it is about the next person reading your code being able to tell a variable from a class at a glance: totalPoints is a variable, Scanner is a class, MAX_SCORE is a constant.
1.3 · Expressions and output
An expression is anything that evaluates to a value. 7, x + 2, and
students * 3 - 1 are all expressions. Java evaluates them using the same
precedence you learned in algebra: *, /, % before + and -, with
parentheses overriding everything.
The one operator that may be new is %, modulus, the remainder after
division:
System.out.println(17 / 5); // 3 (how many whole fives)
System.out.println(17 % 5); // 2 (what was left over)
% is worth more than it looks. n % 2 == 0 tests evenness. n % 10 peels off
the last digit. Anything that cycles is a modulus problem: days of the week,
positions on a board.
To show a value, hand it to System.out:
System.out.print("Score: ");
System.out.println(42);
System.out.println("Next line starts here");
println moves the cursor to a new line afterward; print leaves it where it
is. Joining a String to something else with + is concatenation, and it has
a trap in it:
System.out.println("Total: " + 3 + 4); // Total: 34
System.out.println("Total: " + (3 + 4)); // Total: 7
Left to right: "Total: " + 3 is already a String, so the 4 gets glued on
rather than added. Parentheses fix it.
| Operators | What they are | Reads |
|---|---|---|
( ) | Parentheses — override everything | inside out |
! (type) ++ -- | Unary: not, cast, increment | right to left |
* / % | Multiply, divide, remainder | left to right |
+ - | Add, subtract — and String + | left to right |
< <= > >= | Comparison | left to right |
== != | Equality | left to right |
&& | And — short-circuits | left to right |
|| | Or — short-circuits | left to right |
= += -= *= /= | Assignment | right to left |
One expression, one bracket at a time
-
2 + 3 * 4 % 5as written -
2 + (3 * 4) % 5* binds tighter than + -
2 + (12 % 5)* and % are equal, so left to right -
2 + 212 % 5 is 2 -
4the answer
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
System.out.println(2 + 3 * 4 % 5); *, / and % share the same precedence level and associate left to right, and all three bind tighter than +. So: 3 * 4 is 12, 12 % 5 is 2, 2 + 2 is 4. When in doubt, add parentheses — they cost nothing and they are free documentation.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
System.out.println(1 + 2 + " points"); Evaluation runs left to right: 1 + 2 is int addition giving 3, and only then does 3 + " points" concatenate. Flip it to "points " + 1 + 2 and you get points 12.
1.4 · Assignment statements and input
The = sign is not equality. It is an instruction: evaluate what is on the
right, store it in the variable on the left. Once you read it that way, this
stops being confusing:
int count = 5;
count = count + 1; // evaluate 5 + 1, store 6 back in count
For input, this course uses Scanner:
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("How many players? ");
int players = input.nextInt();
nextInt() reads an integer, nextDouble() a real number, nextLine() a whole
line of text. Ask for the wrong one and the program crashes at run time. The
compiler cannot know what a user will type.
1.5 · Casting and the range of a variable
Here is the single most tested idea in this unit.
When both operands are int, the result is an int. Java throws the
remainder away. It does not round.
System.out.println(7 / 2); // 3, not 3.5
System.out.println(7.0 / 2); // 3.5 (one double is enough)
System.out.println((double) 7 / 2); // 3.5
A cast forces a value into another type: (double) x or (int) x. Casting a
double to an int truncates toward zero. (int) 3.99 is 3, and (int) -3.99
is -3. If you want rounding, ask for it: (int) (x + 0.5) for positives, or
Math.round.
Watch where the cast lands:
int a = 7, b = 2;
System.out.println((double) (a / b)); // 3.0 divided first, damage done
System.out.println((double) a / b); // 3.5 cast first, then divide
An int also has a range: roughly ±2.1 billion. Exceed it and the value
silently wraps around to a negative number rather than erroring. That is an
overflow.
A double has enormous range but limited precision, which is why
0.1 + 0.2 == 0.3 is false in Java, as it is in nearly every language.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
int wins = 3;
int games = 4;
System.out.println((double) (wins / games)); The parentheses make Java evaluate wins / games first. That is int division, so 0, and only then does it cast to 0.0. Move the cast onto one operand, (double) wins / games, and you get 0.75.
1.6 · Compound assignment operators
Shorthand for changing a variable using its own value:
score += 10; // score = score + 10
score -= 3; // score = score - 3
score *= 2; // score = score * 2
score /= 4; // score = score / 4
score %= 5; // score = score % 5
count++; // count = count + 1
count--; // count = count - 1
These are conveniences, not new ideas. Note that /= on an int is still int
division, and ++ on an int is still bounded by the same range.
1.7 · APIs and libraries
Nobody writes everything from scratch. A library is code somebody else wrote and packaged; an API (Application Program Interface) is the documentation of how to use it: what to call, what to pass, what comes back.
Learning to read the Java API is a course skill, not a side quest. On the exam
you get a Java Quick Reference: a short list of the exact methods you are
expected to know for String, Math, Integer, Double, ArrayList, and
Object. It is deliberately short. Memorising beyond it is wasted effort;
knowing everything on it cold is not.
1.8 · Comments
Three ways to leave a note:
// one line
/* several
lines */
/** a documentation comment, describing what the method below does */
The useful rule: comments should say why, not what. count++; // add one to count is noise. count++; // players who already checked in is worth reading.
For methods, describe the contract: what must be true before it runs (preconditions) and what will be true after (postconditions).
1.9 · Method signatures
A method is a named block of code you can run by calling it. Its signature is the name plus the ordered list of parameter types. That pair is how Java tells one method from another.
public static int max(int a, int b)
// ^ ^ ^ ^-------^
// | | | parameters
// | | name
// | return type
// modifier
Two vocabulary words people mix up all year:
- A parameter is the variable in the method’s declaration.
- An argument is the actual value you pass when you call it.
If a method’s return type is void, it hands nothing back. You call it for
what it does, not for what it gives.
1.10 · Calling class methods
Some methods belong to the class itself rather than to any object. You call them on the class name:
int biggest = Math.max(3, 9);
These are static (or class) methods. Math.max needs no Math object to
exist, because it needs no state. Give it two numbers, get one back.
When you call a method, three things happen in order: the arguments are evaluated, control jumps to the method, and when it finishes the returned value takes the place of the call in your expression.
1.11 · The Math class
The four you must know cold, straight off the Quick Reference:
Math.abs(-4) // 4 absolute value
Math.pow(2, 10) // 1024.0 always a double
Math.sqrt(144) // 12.0 always a double
Math.random() // 0.0 <= r < 1.0
Math.random() returns a double from 0 up to but not including 1. The pattern
for a random integer in a range is worth committing to memory:
// a random int from min to max, inclusive of both
int roll = (int) (Math.random() * (max - min + 1)) + min;
// a die: 1 through 6
int die = (int) (Math.random() * 6) + 1;
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Which expression produces a random integer from 5 to 10, including both ends?
Count the values you want. 5,6,7,8,9,10 is six of them, so multiply by 6, then shift by the minimum. The general form is (int)(Math.random() * (max - min + 1)) + min. And note the last option: casting before multiplying throws the whole thing away.
1.12 · Objects: instances of classes
A class is a blueprint. An object is a thing built from that blueprint.
One Dog class; many dogs, each with its own name and weight.
The blueprint describes two things: what an object knows (its attributes, or
state) and what it can do (its behaviours, or methods). String is a class
you have already been using. Every literal in quotes is a String object, and
.length() is behaviour that object provides.
One blueprint, many objects
Press new and watch what changes and what doesn't. The drawing on the left is the class. Every robot on the right is an instance of that class.
class Robot
static Robot.totalCount = 0
One counter for the whole class. Not one per robot.
Nothing built yet. The blueprint is not an object — you cannot paint it, and you cannot point at it and say "that one".
Three things in that yard are worth saying out loud, because they are the three places this idea usually goes wrong.
The blueprint never became a robot. It is still sitting there, unchanged,
after twenty of them. new does not consume the class or copy it — it builds
one more thing from it.
Each robot has its own colour. Painting r3 did nothing to r4. Anything
declared without static belongs to the object, and every object gets its own.
The counter belongs to the class. It went up no matter which robot was
built, and clearing the yard did not put it back to zero. There is exactly one
Robot.totalCount in the whole program, and it outlives every object that
touched it — which is what static means and why it is on the drawing rather
than on any of the robots.
1.13 · Creating objects
You build an object with new, which calls a constructor:
Scanner input = new Scanner(System.in);
String greeting = new String("hello");
Now the important part, and the thing that will bite you in Unit 3 if you skip it here. A variable of a reference type does not hold the object. It holds a reference, the address where the object lives.
String a = "hello";
String b = a; // b now refers to the SAME object as a
A reference variable can also hold null, meaning refers to nothing yet.
Calling a method on a null reference throws a NullPointerException at run
time. It is one of the two or three exceptions you will meet most often.
Strings are a special case worth naming: they are immutable. No method changes a String; every one returns a new one.
String name = "gilmour";
name.toUpperCase(); // computed, then thrown away
System.out.println(name); // gilmour
name = name.toUpperCase(); // keep the result
System.out.println(name); // GILMOUR
| Primitive | Reference | |
|---|---|---|
| Examples | int, double, boolean, char | String, Scanner, anything you write |
| Holds | the value itself | an arrow to an object elsewhere |
b = a copies | the value — they are independent | the arrow — two names, one object |
a == b asks | are these the same value? | are these the same object? |
| Compare text with | == | .equals() |
| Default value | 0, 0.0, false | null |
| Can be null | no — there is no such value | yes, and calling a method on it throws |
| Starts with | a lowercase type name | a capital type name |
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Two variables, one object. What does this print?
int a = 5;
int b = a;
b = 9;
System.out.println(a); This is the difference the whole unit turns on. Assigning a primitive copies the value, so a and b are independent. Assigning a reference copies the arrow, not the object — two names for one thing, and a change through either is visible through both.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
String s = "java";
s.toUpperCase();
System.out.println(s); Strings are immutable: toUpperCase() returns a new String and leaves s alone. The fix is assignment: s = s.toUpperCase();. Any time you call a String method and nothing seems to happen, this is why.
1.14 · Calling instance methods
An instance method is called on an object rather than on a class, and the object it is called on is part of the meaning:
String team = "Lancers";
System.out.println(team.length()); // 7
System.out.println(team.indexOf("nc")); // 2
Read team.length() as ask this particular String how long it is. The dot is
the whole idea: receiver . message. Math.max(3, 9) sends a message to a
class; team.length() sends one to an object.
Some methods return a value you should capture; others return void and are
called for their effect. Chaining is allowed, and reads inside out:
System.out.println(team.substring(0, 3).toUpperCase()); // LAN
1.15 · String manipulation
The String methods on the Quick Reference. These are the ones to know:
String s = "Gilmour Academy";
s.length() // 15
s.substring(8) // "Academy" from index 8 to the end
s.substring(0, 7) // "Gilmour" from 0 up to but NOT including 7
s.indexOf("Acad") // 8 first position, or -1 if absent
s.equals("gilmour") // false case-sensitive comparison
s.compareTo("Apple") // a negative int dictionary order
Two rules cause most of the lost points on this topic:
Indices start at zero. The first character is at index 0 and the last is at
length() - 1. Asking for s.charAt(s.length()) throws
StringIndexOutOfBoundsException.
substring(from, to) excludes to. The length of what comes back is always
to - from, which is a fast way to check yourself.
And never compare Strings with ==. That asks whether two references point at
the same object; .equals() asks whether the text matches, which is nearly
always what you meant.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Two Strings hold the same text but were built separately. What does == report?
String a = "yes";
String b = new String("yes");
System.out.println(a == b);
System.out.println(a.equals(b)); == asks "are these the same object?" and new String(...) guarantees a second one, so it is false. .equals() asks "is the text the same?", which is true. Use .equals() for Strings, always.
Where this goes next
Everything in Unit 2 assumes you can already read an expression and predict its value, because you are about to wrap those expressions in decisions and loops. If any of the quick checks above still feel like guesses, that is the honest signal to re-read before moving on. Unit 2 is 25–35% of the exam and it is built directly on this.
The framework, in full
Every topic College Board lists for this unit, with the learning objectives and essential knowledge in their words rather than mine. If something below isn't covered above yet, that gap is real. Open it, read the objective, then come find me.
-
1.1 Introduction to Algorithms, Programming, and Compilers 3 objectives
1.1.A Represent patterns and algorithms found in everyday life using written language or diagrams.
- 1.1.A.1Algorithms 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.2Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.
1.1.B Explain the code compilation and execution process.
- 1.1.B.1Code 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.2A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.
1.1.C Identify types of programming errors.
- 1.1.C.1A 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.2A 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.3A 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.4An 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.
-
1.2 Variables and Data Types 2 objectives
1.2.A Identify the most appropriate data type category for a particular specification.
- 1.2.A.1A 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.2The 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.3A reference type is used to define objects that are not primitive types.
1.2.B Develop code to declare variables to store numbers and Boolean values.
- 1.2.B.1The 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.
- 1.2.B.2A 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.
-
1.3 Expressions and Output 3 objectives
1.3.A Develop code to generate output and determine the result that would be displayed.
- 1.3.A.1System.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 Develop code to utilize string literals and determine the result of using string literals.
- 1.3.B.1A literal is the code representation of a fixed value.
- 1.3.B.2A string literal is a sequence of characters enclosed in double quotes.
- 1.3.B.3Escape 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 Develop code for arithmetic expressions and determine the result of these expressions.
- 1.3.C.1Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
- 1.3.C.2The 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.
- 1.3.C.3When 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.4The remainder operator % is used to compute the remainder when one number a is divided by another number b.
- 1.3.C.5Operators 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.6An attempt to divide an integer by the integer zero will result in an ArithmeticException.
-
1.4 Assignment Statements and Input 2 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.A.1Every 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.2The 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.
- 1.4.A.3During 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 Develop code to read input.
- 1.4.B.1Input 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.
-
1.5 Casting and Range of Variables 3 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.A.1The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
- 1.5.A.2Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
- 1.5.A.3Some code causes int values to be automatically cast (widened) to double values.
- 1.5.A.4Values 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 Describe conditions when an integer expression evaluates to a value out of range.
- 1.5.B.1The 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.2Integer 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.3If 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 Describe conditions that limit accuracy of expressions.
- 1.5.C.1Computers 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.
-
1.6 Compound Assignment Operators 1 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.
- 1.6.A.1Compound 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.2The 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.
-
1.7 Application Program Interface (API) and Libraries 1 objective
1.7.A Identify the attributes and behaviors of a class found in the libraries contained in an API.
- 1.7.A.1Libraries 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.2Attributes 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 Documentation with Comments 1 objective
1.8.A Describe the functionality and use of code through comments.
- 1.8.A.1Comments 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.2A 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.3A 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.
-
1.9 Method Signatures 2 objectives
1.9.A Identify the correct method to call based on documentation and method signatures.
- 1.9.A.1A 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.2A 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 Describe how to call methods.
- 1.9.B.1A void method does not have a return value and is therefore not called as part of an expression.
- 1.9.B.2A 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.3An 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.4Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
- 1.9.B.5A 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.
-
1.10 Calling Class Methods 1 objective
1.10.A Develop code to call class methods and determine the result of those calls.
- 1.10.A.1Class 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.2Class 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.
-
1.11 Math Class 1 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.
- 1.11.A.1The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
- 1.11.A.2The 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.3The 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.
-
1.12 Objects: Instances of Classes 2 objectives
1.12.A Explain the relationship between a class and an object.
- 1.12.A.1An 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.2A 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.
- 1.12.A.3All classes in Java are subclasses of the Object class.
1.12.B Develop code to declare variables to store reference types.
- 1.12.B.1A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
-
1.13 Object Creation and Storage (Instantiation) 3 objectives
1.13.A Identify, using its signature, the correct constructor being called.
- 1.13.A.1A class contains constructors that are called to create objects. They have the same name as the class.
- 1.13.A.2A 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.3Constructors are said to be overloaded when there are multiple constructors with different signatures.
1.13.B Develop code to declare variables of the correct types to hold object references.
- 1.13.B.1A variable of a reference type holds an object reference or, if there is no object, null.
1.13.C Develop code to create an object by calling a constructor.
- 1.13.C.1An object is typically created using the keyword new followed by a call to one of the class’s constructors.
- 1.13.C.2Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
- 1.13.C.3A 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.4A 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.
-
1.14 Calling Instance Methods 1 objective
1.14.A Develop code to call instance methods and determine the result of these calls.
- 1.14.A.1Instance 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.2A method call on a null reference will result in a NullPointerException.
-
1.15 String Manipulation 2 objectives
1.15.A Develop code to create string objects and determine the result of creating and combining strings.
- 1.15.A.1A 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.2The String class is part of the java.lang package. Classes in the java.lang package are available by default.
- 1.15.A.3A 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.4Two 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.5A 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.
1.15.B Develop code to call methods on string objects and determine the result of calling these methods.
- 1.15.B.1A 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. 50 Using Objects and Methods UNIT 1
- 1.15.B.2The following String methods—including what they do and when they are used—are part of the Java Quick Reference: Bullet int length() returns the number of characters in a String object. Bullet String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1. Bullet String substring(int from) returns substring(from, length()). Bullet int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found. Bullet boolean equals(Object other) returns true if this corresponds to the same sequence of characters as other; returns false otherwise. Bullet 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.
- 1.15.B.3A string identical to the single element substring at position index can be created by calling substring(index, index + 1).
Where you are
Not startedAnswer the checks above whenever you like. They're not graded, and you can retry any of them.
Sources
- College Board — AP Computer Science A Course and Exam Description, Effective Fall 2025
AP Computer Science A · members' unit
Using Objects and Methods is behind a locked door
Units in AP Computer Science A are for people taking the course. Getting in takes a link or a key — signing in on its own doesn't do it.
What's in this unit · 14 min read
- 1.1 · Algorithms, programming, and compilers
- 1.2 · Variables and data types
- 1.3 · Expressions and output
- 1.4 · Assignment statements and input
- 1.5 · Casting and the range of a variable
- 1.6 · Compound assignment operators
- 1.7 · APIs and libraries
- 1.8 · Comments
- 1.9 · Method signatures
- 1.10 · Calling class methods
- 1.11 · The Math class
- 1.12 · Objects: instances of classes
- 1.13 · Creating objects
- 1.14 · Calling instance methods
- 1.15 · String manipulation
- Where this goes next
10 quick checksobject instantiation yard
1 Sign in
With your school Google account. This is how your work reaches the gradebook — it doesn't open the unit by itself.
A key unlocks this browser and keeps your progress here; signing in keeps it with you across devices. Either way the key itself is only ever checked as a hash. Manage all of this on your account, read what signing in stores, or go back to AP Computer Science A.