AP CSA Unit 1: Using Objects and Methods Study Guide
Unit 1 Overview: Using Objects and Methods
Foundational Role: Unit 1 introduces core Java programming concepts including variable management, method calls, object creation, and String manipulation. These skills constitute 15-17.5% of the AP Computer Science A Multiple Choice exam.
Key Recurring Concepts: * Variable declarations and fundamental data types. * Distinction between calling static (class) methods and instance methods. * Standard procedure for creating objects via constructors. * String manipulation techniques (highly emphasized on the exam). * Application of the
Mathclass methods.Required Mastery Skills: * Understanding algorithms and program structures. * Declaring and initializing various variable types. * Writing arithmetic expressions and interpreting output results. * Handling integer division and performing type casting. * Reading and interpreting API documentation effectively. * Using built-in String methods and constructors.
Algorithms, Programming, and Compilers (Topic 1.1)
Algorithm Definition: A step-by-step procedure for solving a problem or accomplishing a task. Algorithms are language-independent; they describe the logic/steps rather than the specific syntax.
Algorithm Characteristics: * Precise: Every step is clearly and unambiguously defined. * Finite: The procedure must eventually terminate. * Effective: Every step is achievable and performable. * Input/Output: The algorithm accepts inputs and generates defined outputs.
Sample Algorithm (Finding an Average): 1. Get two numbers. 2. Add them together. 3. Divide the sum by . 4. Display the result.
Java Implementation: *
int num1 = 10;*int num2 = 20;*double average = (num1 + num2) / 2.0;*System.out.println(average); // Output: 15.0The Compilation Process: * Compiler: Translates Java source code (file extension
.java) into bytecode (file extension.class). * JVM (Java Virtual Machine): Runs the bytecode to produce output. * Workflow:YourProgram.java→ [Compiler] →YourProgram.class→ [JVM] → Output.Error Types: * Syntax Error (Compile-time): Detected during compilation; occurs when code violates language rules (e.g.,
int x = ;missing a value). * Runtime Error: Occurs during execution, causing the program to crash (e.g., division by zero or aNullPointerException). * Logic Error: The program runs but produces the wrong output (e.g., using addition operator+instead of multiplication*).
Variables and Data Types (Topic 1.2)
Variable Definition: A named storage location in memory holding a specific value. Every variable must have a designated type.
Primitive Data Types (AP Subset): *
int: Used for integers (whole numbers). Size: -bits. Examples: , , , . *double: Used for decimal numbers. Size: -bits. Examples: , , . *boolean: Used for logical values. Size: -bit. Values:trueorfalse.Reference Types (Objects): *
String: Represents text as a sequence of characters (e.g.,"Hello"). * Other Objects: Instances of classes created via keywords (e.g.,new Scanner(...)).Variable Declaration and Initialization: * Declaration only:
int age;(In instance variables, these get default values; in local methods, initialization is required before use). * Initialization:int age = 17;double price = 19.99;String name = "Alice";boolean isStudent = true;.Naming Rules and Conventions: * Valid: Must start with a letter,
$, or_. Can include digits. Case-sensitive (Scoreis different fromscore). * Invalid: Cannot start with a digit (2ndPlace) or contain illegal symbols (@name,high-score, spaces). Cannot be a reserved keyword (class,int,for). * CamelCase: Used for variables and methods (e.g.,studentAge). * PascalCase: Used for class names (e.g.,StudentRecord). * ALL_CAPS: Used for constants, often combined with thefinalkeyword (e.g.,final double TAX_RATE = 0.0825;).
Primitive vs. Reference Types
Primitive Types: * Store the actual value directly. * Variable names are lowercase (e.g.,
int,double). * They do not possess methods. * Compared using==.Reference Types: * Store a memory address (reference) to an object. * Names are typically capitalized (e.g.,
String). * They possess methods for data manipulation. * Content should be compared using the.equals()method rather than==.
Expressions, Arithmetic, and Output (Topic 1.3)
Arithmetic Operators: * Addition (
+):7 + 3 = 10. * Subtraction (-):7 - 3 = 4. * Multiplication (*):7 * 3 = 21. * Division (/):7 / 3 = 2(Integer division). * Modulus (%):7 % 3 = 1(Remainder).Integer Division Trap: If both operands are
int, the result is anintand is truncated (decimal part is removed, not rounded). *int a = 7 / 3;results in2. *double d = 7 / 3;results in2.0because the truncation happens before assignment. * If either operand is adouble, the result is adouble(e.g.,7.0 / 3 = 2.333...).Modulus Applications: *
x % 2 == 0: Identifies ifxis even. *x % 2 != 0: Identifies ifxis odd. *12345 % 10: Extracts the last digit (5). * Small number mod large number:3 % 7 = 3.Console Output: *
System.out.println(): Prints content and moves to the next line. *System.out.print(): Prints content without adding a newline.String Concatenation: *
"Sum: " + 7results in"Sum: 7". * Evaluation order matters:1 + 2 + "3"→3 + "3"→"33". *"1" + 2 + 3→"12" + 3→"123". * Parentheses override:"1" + (2 + 3)→"1" + 5→"15".
Assignment and User Input (Topic 1.4)
Assignment Operator (
=): Assigns the value on the right to the variable on the left.x = x + 5;adds 5 to the current value ofx.Swapping Values: Requires a temporary variable to avoid data loss. *
int temp = a; a = b; b = temp;.Scanner Class: Used for reading input. Requires
import java.util.Scanner;. *Scanner input = new Scanner(System.in);creates the scanner. * Methods: *nextInt(): Reads the nextint. *nextDouble(): Reads the nextdouble. *next(): Reads the next word (token). *nextLine(): Reads the entire line. *input.close();is good practice to free resources.
Casting and Range of Variables (Topic 1.5)
Implicit Casting (Widening): Converting a smaller type to a larger type internally; occurs automatically (e.g.,
int x = 10; double y = x;results in10.0).Explicit Casting (Narrowing): Converting a larger type to a smaller type manually; results in truncation. *
(int) 9.7results in9. *(int) -3.9results in-3(truncates toward zero). * Fixing Division:(double) num / denomperforms floating-point division;(double) (num / denom)is incorrect because truncation occurs inside the parentheses first.Integer Range: * Range: to . * Constants:
Integer.MAX_VALUEandInteger.MIN_VALUE. * Overflow: Adding 1 toInteger.MAX_VALUEresults inInteger.MIN_VALUE(wraps around) without throwing an error.
Operators, APIs, and Documentation (Topics 1.6 - 1.8)
Compound Assignment Operators: *
x += 5;↔x = x + 5;*x -= 3;↔x = x - 3;*x *= 2;,x /= 4;,x %= 3;.Increment/Decrement:
x++;(increment by 1) andx--;(decrement by 1).APIs (Application Program Interface): Pre-written classes and methods available for use. *
import java.util.*;imports everything in the utility package. *java.langis auto-imported (includesString,Math,Integer,Double).Comments: * Single-line:
// comment. * Multi-line:/* comment */. * Javadoc:/** ... */. Used with tags like@param(parameter info) and@return(return value info).Contracts: * Precondition: Requirement that must be true before a method runs. * Postcondition: The state or condition guaranteed after the method completes.
Method Signatures and Static Methods (Topics 1.9 - 1.11)
Method Signature Anatomy:
public static int add(int a, int b)*public: Access modifier. *static: Method belongs to the class, not instance. *int: Return type. *add: Method name. *(int a, int b): Parameters.Return Types:
void(returns nothing),int,double,boolean,String.Parameter vs. Argument: * Parameter: The variable defined in the method signature (formal). * Argument: The actual value passed during the method call (actual).
Static vs. Instance Methods: * Static: Called using the class name (
Math.sqrt(16)). No object needed. * Instance: Called on a specific object (str.length()). Requires instantiation.Math Class Methods: *
Math.abs(x): Absolute value (). *Math.pow(base, exp): Power (). Always returns adouble. *Math.sqrt(x): Square root (). *Math.random(): Generates a randomdoublein the range .Random Integer Formula: To get a random integer from
mintomaxinclusive: *
Objects and Instantiation (Topics 1.12 - 1.13)
Class vs. Object Analogy: * Class = Cookie cutter (blueprint). * Object = Individual cookie (instance).
Object Components: * State: Data stored in instance variables. * Behavior: Actions performed via methods.
Creation:
ClassName objectName = new ClassName(arguments);.Constructors: Special methods used to initialize new objects. They share the class name and have no return type.
Reference Variables: * If
s2 = s1, both variables point to the same object in memory. *nullsignifies no object reference. Calling a method onnulltriggers aNullPointerExceptionruntime error.
String Manipulation (Topics 1.14 - 1.15)
Immutability: Strings cannot be changed once created. Methods like
toUpperCase()return a new String rather than modifying the original. * Correct use:s = s.toUpperCase();.String Indexing: Starts at and ends at .
Essential Methods: *
length(): Returns the number of characters. *substring(int start, int end): Returns characters from indexstarttoend - 1. Theendindex is exclusive. *substring(int start): Returns characters fromstartto the end of the text. *indexOf(String str): Returns the index of the first occurrence ofstr; returns if not found. *equals(String str): Checks for content equality (use this instead of==). *compareTo(String str): Lexicographic comparison. Returns if equal, a negative value if the object comes before the argument, and a positive value if it comes after.
Practice Questions & Exam Traps
Q1 (Integer Division):
int a = 17, b = 5; double result = a / b;→ Result is3.0because17/5truncates to3before being stored as a double.Q2 (Substring):
"computer".substring(3, 6)→ Indices 3, 4, 5 →"put".Q3 (Mod/Div):
int x = 47; System.out.println(x % 10 + x / 10);→7 + 4 = 11.Q4 (Casting):
(int) -2.7→-2(truncates toward zero).Q5 (Concatenation):
3 + 4 + "5" + 6 + 7→7 + "5" + 6 + 7→"7567".Q6 (Math.pow):
(int) Math.pow(3, 2) + 1→9 + 1 = 10.Q7 (indexOf):
"Mississippi".indexOf("ss")→ First occurrence starts at index2.Q8 (Random Range):
(int) (Math.random() * 6) + 1→ Produces range .Q9 (Call Syntax):
Math.sqrt(16);is correct for static methods.Q10 (Comparison):
s1 == s2isfalse(different memory addresses);s1.equals(s2)istrue(same content).
Final Exam Checklist
Ensure integer division is cast to double if decimals are needed.
Always use
.equals()for String content comparison.Verify
substringend indices are exclusive.Remember casting truncates; it does not round.
Reassign String variables when calling methods to preserve changes due to immutability.
Static methods use the Class name; instance methods use the object reference.
Check for
nullto avoidNullPointerExceptioncrashes.