zuai-logo

If Statements and Control Flow

Caleb Thomas

Caleb Thomas

12 min read

Listen to this study note

Study Guide Overview

This AP Computer Science A study guide covers program control (conditional statements like if and loops like for and while), string manipulation (common methods, immutability), arrays (declaration, access, iteration), classes and objects (basics, creation, methods), and inheritance and polymorphism (extends, method overriding). It emphasizes practice with multiple-choice and free-response questions and offers last-minute exam tips.

AP Computer Science A: Ultimate Night-Before Review ๐Ÿš€

Hey there! Feeling the pre-exam jitters? No worries, we've got you covered. This guide is designed to be your best friend tonight, helping you quickly review and feel confident for tomorrow. Let's dive in!

1. Program Control: Conditional Statements and Loops

1.1 Conditional Statements: Making Decisions ๐Ÿšฆ

Conditional statements are the backbone of decision-making in code. They allow your program to execute different blocks of code based on whether a condition is true or false. Think of them as the "if this, then that" logic of programming.

  • Header: Contains the condition to be evaluated.
  • Body: Contains the code to be executed if the condition is true.

1.2 If Statements: The Simplest Choice โœ…

The if statement is a one-way selection. It executes a block of code only if a specified condition is true.

if (condition) { // Condition in parentheses
    // Code to execute if condition is true
}
// Code here always runs after the if statement
  • The condition is always enclosed in parentheses ().
Quick Fact

Parentheses are a must!

- The code block is enclosed in curly braces `{}`.
Quick Fact

Braces are needed for multi-line bodies!

- Indentation makes your code readable.
Quick Fact

Indentation is your friend!

Common Mistake

Forgetting curly braces {} for multi-line if blocks will lead to only the first line being considered part of the if block!

Example: Even Number Checker

public static int numberHalver(int number) {
    if (number % 2 == 0) { // Check if number is even
        number /= 2; // Halve the number if even
    }
    return number; // Return the (possibly halved) number
}

public static boolean isEven(int number) {
    if (number % 2 == 0) {
        return true; // Return true immediately if even
    }
    return false; // Return false if not even
}
Key Concept

A return statement inside an if block will immediately exit the method. The rest of the code in the method will not be executed.

Memory Aid

Think of an if statement like a doorway: If the condition is true (the door is open), you walk through and execute the code inside. Otherwise, you skip it.

Practice Question
{
  "multiple_choice": [
    {
      "question": "What is the output of the following code snippet? \n```java\nint x = 5;\nif (x % 2 == 0) {\n    x = x + 1;\n}\nSystem.out.println(x);\n```",
      "options": ["5", "6", "7", "Error"],
      "answer": "5"
    },
    {
      "question": "Which of the following is the correct syntax for an if statement?",
      "options": ["if condition { code }", "if (condition) code", "if (condition) { code }", "if condition code"],
      "answer": "if (condition) { code }"
    }
  ],
  "free_response": {
    "question": "Write a method `checkPositive` that takes an integer as input and returns `true` if the number is positive, and `false` otherwise.",
    "solution": "```java\npublic static boolean checkPositive(int num) {\n    if (num > 0) {\n        return true;\n    }\n    return false;\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct method signature.",
      "+1 point: Correct if condition.",
      "+1 point: Correct return true.",
      "+1 point: Correct return false."
    ]
  }
}

2. Program Control: Iteration (Loops)

2.1 For Loops: Repeating a Specific Number of Times ๐Ÿ”„

for loops are used when you know how many times you need to repeat a block of code. They consist of three parts:

  1. Initialization: Executed only once at the beginning of the loop.
  2. Condition: Checked before each iteration. The loop continues as long as the condition is true.
  3. Increment/Decrement: Executed after each iteration.
for (initialization; condition; increment/decrement) {
    // Code to be repeated
}

Example: Printing Numbers

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
// Output: 0 1 2 3 4
Quick Fact

The loop variable i is often used as a counter.

2.2 While Loops: Repeating Until a Condition is Met โณ

while loops are used when you need to repeat a block of code until a condition becomes false. The condition is checked before each iteration.

while (condition) {
    // Code to be repeated
}
Common Mistake

Forgetting to update the loop variable inside a while loop can lead to an infinite loop!

Example: Counting Down

int count = 5;
while (count > 0) {
    System.out.println(count);
    count--;
}
// Output: 5 4 3 2 1
Key Concept

Choose for loops when you know the number of iterations, and while loops when you need to repeat until a condition is met.

Memory Aid

Think of a for loop like a recipe: you know how many steps to take. Think of a while loop like a game: you keep playing until you win (condition is met).

Practice Question
{
  "multiple_choice": [
    {
      "question": "How many times will the following loop execute? \n```java\nfor (int i = 1; i <= 10; i += 2) {\n    System.out.println(i);\n}\n```",
      "options": ["4", "5", "6", "10"],
      "answer": "5"
    },
    {
      "question": "What is the output of the following code snippet? \n```java\nint x = 0;\nwhile (x < 3) {\n    x++;\n}\nSystem.out.println(x);\n```",
      "options": ["0", "1", "2", "3"],
      "answer": "3"
    }
  ],
  "free_response": {
    "question": "Write a method `sumOfSquares` that takes an integer `n` as input and returns the sum of the squares of all numbers from 1 to `n` (inclusive) using a for loop.",
    "solution": "```java\npublic static int sumOfSquares(int n) {\n    int sum = 0;\n    for (int i = 1; i <= n; i++) {\n        sum += i * i;\n    }\n    return sum;\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct method signature.",
      "+1 point: Correct initialization of sum.",
      "+1 point: Correct for loop.",
      "+1 point: Correct calculation of sum."
    ]
  }
}

3. Working with Strings

3.1 String Basics ๐Ÿงต

  • Strings are sequences of characters.
Quick Fact

Strings are objects in Java!

- They are immutable (cannot be changed after creation).
Quick Fact

Once created, a String cannot be altered!

- Use double quotes `"` to create string literals.
Quick Fact

Always use double quotes for strings!

Example: String Declaration

String message = "Hello, AP Comp Sci!";

3.2 Common String Methods ๐Ÿ› ๏ธ

MethodDescriptionExample
length()Returns the number of characters in the string."hello".length() returns 5
charAt(int i)Returns the character at the specified index i."hello".charAt(1) returns 'e'
substring(int begin, int end)Returns a substring starting from begin index up to (but not including) end index."hello".substring(1, 4) returns "ell"
equals(String other)Checks if two strings have the same content."hello".equals("hello") returns true
indexOf(String str)Returns the starting index of the first occurrence of str."hello".indexOf("ll") returns 2
Common Mistake

String indices start at 0, not 1!

Key Concept

Use .equals() to compare string content, not ==!

Example: Using String Methods

String str = "Programming";
int len = str.length(); // len is 11
char firstChar = str.charAt(0); // firstChar is 'P'
String sub = str.substring(3, 7); // sub is "gram"
boolean isEqual = str.equals("Programming"); // isEqual is true
int index = str.indexOf("ram"); // index is 4
Memory Aid

Remember that substring(begin, end) goes up to, but does not include, the end index.

Practice Question
{
  "multiple_choice": [
    {
      "question": "What is the output of the following code? \n```java\nString s = \"JavaProgramming\";\nSystem.out.println(s.substring(4, 8));\n```",
      "options": ["Java", "Prog", "gram", "Progr"],
      "answer": "Prog"
    },
    {
      "question": "Which method should be used to compare the content of two strings?",
      "options": ["==", "equals()", "compareTo()", "length()"],
      "answer": "equals()"
    }
  ],
  "free_response": {
    "question": "Write a method `reverseString` that takes a string as input and returns the reversed string.",
    "solution": "```java\npublic static String reverseString(String str) {\n    String reversed = \"\";\n    for (int i = str.length() - 1; i >= 0; i--) {\n        reversed += str.charAt(i);\n    }\n    return reversed;\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct method signature.",
      "+1 point: Correct initialization of reversed string.",
      "+1 point: Correct loop.",
      "+1 point: Correct character concatenation."
    ]
  }
}

4. Working with Arrays

4.1 Array Basics ๐Ÿ“ฆ

  • Arrays are used to store multiple values of the same type.
Quick Fact

Arrays hold multiple elements of the same data type!

- They have a fixed size.
Quick Fact

Array size is fixed after creation!

- Array indices start at 0.
Quick Fact

Remember, arrays are zero-indexed!

Example: Array Declaration

int[] numbers = new int[5]; // Array to hold 5 integers
String[] names = {"Alice", "Bob", "Charlie"}; // Array initialization

4.2 Accessing and Modifying Array Elements ๐Ÿงฎ

  • Use the index to access elements: array[index]
  • Use the index to modify elements: array[index] = value

Example: Array Access and Modification

int[] nums = {10, 20, 30};
int first = nums[0]; // first is 10
nums[1] = 25; // nums is now {10, 25, 30}

4.3 Iterating Through Arrays ๐Ÿšถ

  • Use a for loop to iterate through each element of an array.

Example: Printing Array Elements

int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
Common Mistake

ArrayIndexOutOfBoundsException occurs when trying to access an index that is out of the array's bounds.

Key Concept

Use array.length to get the size of an array.

Memory Aid

Think of an array like a row of numbered boxes. Each box holds a value, and you use the index to access a particular box.

Practice Question
{
  "multiple_choice": [
    {
      "question": "What is the value of `arr[2]` after the following code executes? \n```java\nint[] arr = {1, 2, 3, 4, 5};\narr[2] = 10;\n```",
      "options": ["1", "2", "3", "10"],
      "answer": "10"
    },
    {
      "question": "What is the index of the last element in an array of size 10?",
      "options": ["9", "10", "11", "0"],
      "answer": "9"
    }
  ],
  "free_response": {
    "question": "Write a method `arraySum` that takes an integer array as input and returns the sum of all elements in the array.",
    "solution": "```java\npublic static int arraySum(int[] arr) {\n    int sum = 0;\n    for (int i = 0; i < arr.length; i++) {\n        sum += arr[i];\n    }\n    return sum;\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct method signature.",
      "+1 point: Correct initialization of sum.",
      "+1 point: Correct loop.",
      "+1 point: Correct sum calculation."
    ]
  }
}

5. Classes and Objects

5.1 Class Basics ๐Ÿ›๏ธ

  • A class is a blueprint for creating objects.
Quick Fact

Classes are blueprints for objects!

- It defines the data (fields/attributes) and behavior (methods) of objects.
Quick Fact

Classes define data and behavior!

- Use the `class` keyword to define a class.
Quick Fact

Use class keyword to define a class!

Example: Simple Class Definition

public class Dog {
    String name;
    int age;

    public void bark() {
        System.out.println("Woof!");
    }
}

5.2 Creating Objects ๐Ÿ‘ถ

  • Objects are instances of a class.
Quick Fact

Objects are instances of classes!

- Use the `new` keyword to create objects.
Quick Fact

Use new keyword to create objects!

Example: Creating Dog Objects

Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();

5.3 Methods โš™๏ธ

  • Methods define the behavior of objects.
Quick Fact

Methods define object behavior!

- They can take parameters and return values.
Quick Fact

Methods can have parameters and return values!

Example: Method with Parameters

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Key Concept

Classes define the type, and objects are instances of that type.

Memory Aid

Think of a class like a cookie cutter and objects like the cookies made with that cutter.

Practice Question
{
  "multiple_choice": [
    {
      "question": "Which keyword is used to create an object of a class?",
      "options": ["class", "object", "new", "instance"],
      "answer": "new"
    },
    {
      "question": "What does a class define?",
      "options": ["Only data", "Only behavior", "Data and behavior", "Neither data nor behavior"],
      "answer": "Data and behavior"
    }
  ],
  "free_response": {
    "question": "Create a class `Rectangle` with fields `width` and `height` and a method `area` that returns the area of the rectangle.",
    "solution": "```java\npublic class Rectangle {\n    int width;\n    int height;\n
    public int area() {\n        return width * height;\n    }\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct class declaration.",
      "+1 point: Correct fields.",
      "+1 point: Correct method signature.",
      "+1 point: Correct area calculation."
    ]
  }
}

6. Inheritance and Polymorphism

6.1 Inheritance: Reusing Code ๐Ÿ‘ช

  • Allows a class (subclass) to inherit properties and methods from another class (superclass).
Quick Fact

Inheritance promotes code reuse!

- Use the `extends` keyword to inherit.
Quick Fact

Use extends to inherit!

Example: Inheritance

class Animal {
    String name;
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Woof!");
    }
}

6.2 Polymorphism: Many Forms ๐ŸŽญ

  • Allows objects of different classes to be treated as objects of a common superclass.
Quick Fact

Polymorphism enables flexibility!

- Method overriding is a key part of polymorphism.
Quick Fact

Method overriding is crucial for polymorphism!

Example: Polymorphism

class Animal {
    public void makeSound() {
        System.out.println("Generic animal sound");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

Animal animal1 = new Cat();
animal1.makeSound(); // Output: Meow!
Animal animal2 = new Dog();
animal2.makeSound(); // Output: Woof!
Key Concept

Inheritance creates an "is-a" relationship (e.g., a Dog is an Animal). Polymorphism allows you to treat different types of objects in a uniform way.

Memory Aid

Think of inheritance like a family tree: children inherit traits from their parents. Polymorphism is like a group of animals making their own unique sounds, but all are still animals.

Practice Question
{
  "multiple_choice": [
    {
      "question": "Which keyword is used to implement inheritance?",
      "options": ["implements", "inherits", "extends", "subclass"],
      "answer": "extends"
    },
    {
       "question": "What is polymorphism in the context of object-oriented programming?",
       "options": ["The ability of a class to have multiple constructors", "The ability of an object to take on many forms", "The ability of a method to have multiple parameters", "The ability of a class to have multiple fields"],
       "answer": "The ability of an object to take on many forms"
    }
  ],
  "free_response": {
    "question": "Create a class `Shape` with a method `calculateArea`. Create two subclasses, `Circle` and `Square`, that override this method to calculate their respective areas. Assume a field `radius` for `Circle` and `side` for `Square` is available.",
    "solution": "```java\nclass Shape {\n    public double calculateArea() {\n        return 0; // Default implementation\n    }\n}

class Circle extends Shape {\n    double radius;\n    @Override\n    public double calculateArea() {\n        return Math.PI * radius * radius;\n    }\n}

class Square extends Shape {\n    double side;\n    @Override\n    public double calculateArea() {\n        return side * side;\n    }\n}\n```",
    "scoring_guidelines": [
      "+1 point: Correct `Shape` class and `calculateArea` method.",
      "+1 point: Correct `Circle` class and `calculateArea` override.",
      "+1 point: Correct `Square` class and `calculateArea` override.",
      "+1 point: Correct usage of `@Override` annotation."
    ]
  }
}

7. Final Exam Focus ๐ŸŽฏ

7.1 High-Priority Topics

  • Conditional Statements and Loops: Master if, for, and while statements. They are fundamental to almost every program.
  • Arrays: Understand how to declare, access, and iterate through arrays. Be comfortable with array manipulation.
  • Strings: Know the common string methods and how to use them. Pay attention to string immutability.
  • Classes and Objects: Understand the concepts of classes, objects, and methods. Be able to create and use objects.
  • Inheritance and Polymorphism: Understand how to create subclasses and override methods.

7.2 Common Question Types

Exam Tip
  • Multiple Choice Questions (MCQs): Focus on tracing code execution, understanding syntax, and identifying errors.
  • Free Response Questions (FRQs): Practice writing complete methods and classes. Pay attention to method signatures, return types, and parameter lists.

7.3 Last-Minute Tips ๐Ÿ’ก

  • Time Management: Don't spend too long on any one question. Move on and come back later if needed.
  • Tracing Code: Practice tracing code execution step-by-step. This will help you understand how loops and conditional statements work.
  • Read Carefully: Pay close attention to the question requirements. Don't make assumptions.
  • Syntax: Be careful with syntax. Small errors can lead to big problems.
  • Practice: Do as many practice questions as possible. The more you practice, the more confident you will feel.
  • Stay Calm: You've got this! Take deep breaths and focus on what you know.

Good luck! You're going to do great! ๐Ÿ’ช

Question 1 of 19

What will be the value of 'x' after executing the following code snippet?

int x = 10;
if (x > 5) {
   x = x + 2;
}

10

12

8

5