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 Math class 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 22.     4. Display the result.

  • Java Implementation:     * int num1 = 10;     * int num2 = 20;     * double average = (num1 + num2) / 2.0;     * System.out.println(average); // Output: 15.0

  • The 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 a NullPointerException).     * 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: 3232-bits. Examples: 5-5, 00, 4242, 10000001000000.     * double: Used for decimal numbers. Size: 6464-bits. Examples: 3.143.14, 0.5-0.5, 2.02.0.     * boolean: Used for logical values. Size: 11-bit. Values: true or false.

  • 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 (Score is different from score).     * 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 the final keyword (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 an int and is truncated (decimal part is removed, not rounded).     * int a = 7 / 3; results in 2.     * double d = 7 / 3; results in 2.0 because the truncation happens before assignment.     * If either operand is a double, the result is a double (e.g., 7.0 / 3 = 2.333...).

  • Modulus Applications:     * x % 2 == 0: Identifies if x is even.     * x % 2 != 0: Identifies if x is 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: " + 7 results 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 of x.

  • 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 next int.         * nextDouble(): Reads the next double.         * 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 in 10.0).

  • Explicit Casting (Narrowing): Converting a larger type to a smaller type manually; results in truncation.     * (int) 9.7 results in 9.     * (int) -3.9 results in -3 (truncates toward zero).     * Fixing Division: (double) num / denom performs floating-point division; (double) (num / denom) is incorrect because truncation occurs inside the parentheses first.

  • Integer Range:     * Range: 2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647.     * Constants: Integer.MAX_VALUE and Integer.MIN_VALUE.     * Overflow: Adding 1 to Integer.MAX_VALUE results in Integer.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) and x--; (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.lang is auto-imported (includes String, 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 (x|x|).     * Math.pow(base, exp): Power (baseexpbase^{exp}). Always returns a double.     * Math.sqrt(x): Square root (x\sqrt{x}).     * Math.random(): Generates a random double in the range [0.0,1.0)[0.0, 1.0).

  • Random Integer Formula: To get a random integer from min to max inclusive:     * (int) (Math.random() × (max - min + 1)) + min\text{(int) (Math.random() } \times \text{ (max - min + 1)) + min}

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.     * null signifies no object reference. Calling a method on null triggers a NullPointerException runtime 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 00 and ends at length()1length() - 1.

  • Essential Methods:     * length(): Returns the number of characters.     * substring(int start, int end): Returns characters from index start to end - 1. The end index is exclusive.     * substring(int start): Returns characters from start to the end of the text.     * indexOf(String str): Returns the index of the first occurrence of str; returns 1-1 if not found.     * equals(String str): Checks for content equality (use this instead of ==).     * compareTo(String str): Lexicographic comparison. Returns 00 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 is 3.0 because 17/5 truncates to 3 before 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 + 77 + "5" + 6 + 7"7567".

  • Q6 (Math.pow): (int) Math.pow(3, 2) + 19 + 1 = 10.

  • Q7 (indexOf): "Mississippi".indexOf("ss") → First occurrence starts at index 2.

  • Q8 (Random Range): (int) (Math.random() * 6) + 1 → Produces range [1,6][1, 6].

  • Q9 (Call Syntax): Math.sqrt(16); is correct for static methods.

  • Q10 (Comparison): s1 == s2 is false (different memory addresses); s1.equals(s2) is true (same content).

Final Exam Checklist

  • Ensure integer division is cast to double if decimals are needed.

  • Always use .equals() for String content comparison.

  • Verify substring end 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 null to avoid NullPointerException crashes.