Using Objects and Methods
What you must know
Every AP CSA object question rests on a few ideas: a reference variable holds the address of an object, not the object itself; the dot operator calls a method or reads a field; and method calls pass arguments whose types must match the parameter list. Know the difference between a class (the blueprint) and an object (an instance). Understand that String objects are immutable, so methods like substring, toUpperCase, and replace return a new string and leave the original unchanged. Be fluent with String methods (length, indexOf, substring, equals, compareTo), Integer/Double parsing and boxing, and the Math class (Math.random, Math.abs, Math.pow).
Traps
- Using
==to compare strings.==compares references;equalscompares contents.new String("hi") == "hi"is usuallyfalse. - Forgetting that
substring(a, b)includes indexabut excludes indexb, and that an out-of-range index throws an exception. - Assuming a method mutates a
Stringwhen it actually returns a new one. - Mixing up integer and floating-point division:
7 / 2is3, but7 / 2.0is3.5. - Passing an object reference to a method: the method can mutate the object's state, but reassigning the parameter does not affect the caller's variable.
Rule of thumb
When a question shows a chain of String calls, evaluate left to right, tracking the current value after each call, because each call produces a fresh string.
Worked example: String s = "Computer"; String t = s.substring(3, 6).toUpperCase(); - substring(3,6) is "put", and toUpperCase gives "PUT"; s is unchanged.