zuai-logo

If Statements and Control Flow

Caleb Thomas

Caleb Thomas

13 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.

java
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

java
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

Question 1: What is the output of the following code snippet?

python
def foo(x):
    return x + 1

def bar(y):
    return foo(y) * 2

print(bar(5))

Options: A. 10 B. 11 C. 12 D. 13

Answer: 12

Question 2: Which of the following is NOT a valid Python data type?

Options: A. List B. Tuple C. Dictionary D. Array

Answer: Array

Question 3: What will be the value of 'a' after the following code is executed?

python
a = [1, 2, 3]
a.append(4)
a.pop(0)
print(a)

Options: A. [1, 2, 3] B. [2, 3, 4] C. [1, 2, 4] D. [3, 4]

Answer: [2, 3, 4]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." ] } }


</div>

## 2. Program Control: Iteration (Loops) <a name="loops"></a>

### 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.

java for (initialization; condition; increment/decrement) { // Code to be repeated }


#### Example: Printing Numbers

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


<div data-custom-tag="quick_fact"> 

The loop variable `i` is often used as a counter.

</div>

### 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.

java while (condition) { // Code to be repeated }


<div data-custom-tag="common_mistake"> 

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

</div>

#### Example: Counting Down

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


<div data-custom-tag="key_point"> 

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

</div>

<div data-custom-tag="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).

</div>

<div data-custom-tag="practice_question"> 

multiple_choice:
  - question: How many times will the following loop execute?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

java
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

java
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 Questions

Question 1:

What is the output of the following code?

python
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Options:

  • a) Hello, Alice!
  • b) Hello, Alice
  • c) greet(Alice)
  • d) Error

Answer: a) Hello, Alice!

Explanation: The greet function takes a name argument and returns a formatted string. When called with "Alice", it returns "Hello, Alice!". The print statement then outputs this string to the console.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." ] } }


</div>

## 4. Working with Arrays <a name="arrays"></a>

### 4.1 Array Basics ๐Ÿ“ฆ

-   Arrays are used to store multiple values of the same type. 
<div data-custom-tag="quick_fact"> 

Arrays hold multiple elements of the same data type!

</div>

-   They have a fixed size. 
<div data-custom-tag="quick_fact"> 

Array size is fixed after creation!

</div>

-   Array indices start at 0. <div data-custom-tag="quick_fact"> 

Remember, arrays are zero-indexed!

</div>

#### Example: Array Declaration

java 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

java 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

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


<div data-custom-tag="common_mistake"> 

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

</div>

<div data-custom-tag="key_point"> 

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

</div>

<div data-custom-tag="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.

</div>

<div data-custom-tag="practice_question"> 

### Question 1: What is the value of `arr[2]` after the following code executes?

python arr = [1, 2, 3, 4, 5] arr.pop() arr.insert(0, 0)


- A) 2
- B) 3
- C) 4
- D) 5

**Answer:** B) 3

### Question 2: Which of the following is the correct way to create an empty dictionary in Python?

- A) `dict = {}`
- B) `dict = []`
- C) `dict = ()`
- D) `dict = new dict()`

**Answer:** A) `dict = {}`

### Question 3: What will be the output of the following code?

python def greet(name): return f"Hello, {name}!"

print(greet("Alice"))


- A) Hello, Alice!
- B) Hello, Alice
- C) Hello Alice!
- D) greet(Alice)

**Answer:** A) Hello, Alice!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

java
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

java
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

java
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 Questions:

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:

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." ] } }


</div>

## 6. Inheritance and Polymorphism <a name="inheritance-polymorphism"></a>

### 6.1 Inheritance: Reusing Code ๐Ÿ‘ช

-   Allows a class (subclass) to inherit properties and methods from another class (superclass). 
<div data-custom-tag="quick_fact"> 

Inheritance promotes code reuse!

</div>

-   Use the `extends` keyword to inherit. 
<div data-custom-tag="quick_fact"> 

Use `extends` to inherit!

</div>

#### Example: Inheritance

java 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. 
<div data-custom-tag="quick_fact"> 

Polymorphism enables flexibility!

</div>

-   Method overriding is a key part of polymorphism. 
<div data-custom-tag="quick_fact"> 

Method overriding is crucial for polymorphism!

</div>

#### Example: Polymorphism

java 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!


<div data-custom-tag="key_point"> 

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.

</div>

<div data-custom-tag="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.

</div>

<div data-custom-tag="practice_question"> 

### Multiple Choice Questions

**1. Which keyword is used to implement inheritance?**
*   implements
*   inherits
*   extends
*   subclass
**Answer:** extends

**2. What is polymorphism in the context of object-oriented programming?**
*   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

**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?

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

10

12

8

5