Bright Sprouts AcademyColumbia & Imperial educators

AP Computer Science A · Topic notes

Using Objects and Methods

Key ideas, common mistakes, and a worked example for Using Objects and Methods in AP Computer Science A.

Practice Using Objects and Methods

9 untimed questions from the free practice test.

Exam weighting: 15–25%

Using Objects and Methods covers the building blocks of Java: primitive types, expressions, casting, calling methods, creating objects, and working with strings. Many multiple-choice questions ask exactly what a short code segment prints, so careful tracing matters more than memorizing.

Key ideas

  • Integer division drops the fractional part: 17 / 5 is 3, and 17 % 5 is 2. If either operand is a double, the result is a double.
  • A cast applies to the value right after it. (int) x * 10 casts first, while (int) (x * 10) multiplies first. Casting a positive double to int truncates it.
  • (int) (Math.random() * n) + k gives an integer from k to k + n - 1, so the multiplier is the number of possible values.
  • Strings are immutable. Methods such as substring return a new string, and substring(a, b) includes index a but not index b.
  • Once the left operand of + is a String, + joins text, and the expression is evaluated from left to right.

Common mistakes

  • Expecting 7 / 2 to be 3.5. Both operands are int, so the result is 3.
  • Counting string positions from 1. The first character is at index 0, and the last is at length() - 1.
  • Comparing strings with == instead of equals.
  • Forgetting that int arithmetic can overflow past Integer.MAX_VALUE without any error message.

Worked example

What is printed by the following code segment?

String s = "computer";
int k = s.indexOf("p");
System.out.println(s.substring(k) + s.substring(0, k) + k / 2);

Solution

indexOf("p") returns 3, because p is the fourth character. s.substring(3) is "puter", and s.substring(0, 3) is "com". Division happens before +, and k / 2 is integer division, so it is 1. The left operand is already a String, so 1 is added as text. The output is putercom1.

Stuck on Using Objects and Methods?

A tutor can find the gap in one session. Book a free consultation.

Every question on this site is original and written by Bright Sprouts Academy. AP, Advanced Placement, SAT, and PSAT/NMSQT are registered trademarks of College Board, which is not affiliated with and does not endorse this site. PSAT/NMSQT is also a trademark jointly owned by College Board and National Merit Scholarship Corporation.

Last updated . Exam board and university requirements change, so always check the official specification and admissions pages.