AP Computer Science A Study Guide - Primitive Types

AP Computer Science A Study Guide

  • AP is a registered trademark of the College Board.

Key Exam Details

  • The AP® Computer Science A course is equivalent to a first-semester, college-level course in computer science.

  • The 3-hour exam is comprised of 44 questions:

    • 40 multiple-choice questions (50% of the exam)
    • 4 free-response questions (50% of the exam)
  • Exam Content Categories:

    • Primitive Types: 2.5%–5% of test questions
    • Using Objects: 5%–7.5% of test questions
    • Boolean Expressions and if Statements: 15%–17.5% of test questions
    • Iteration: 17.5%–22.5% of test questions
    • Writing Classes: 5%–7.5% of test questions
    • Array: 10%–15% of test questions
    • ArrayList: 2.5%–7.5% of test questions
    • 2D Array: 7.5%–10% of test questions
    • Inheritance: 5%–10% of test questions
    • Recursion: 5%–7.5% of test questions

Printing and Comments

  • System.out.print and System.out.println are used to display output on the console.
  • System.out.println moves the cursor to a new line after displaying data.
  • A comment is text in the source code file which is ignored by the computer.
  • Single-line comments are denoted by //.
  • Multiline comments are demarcated by /* and */.

Data Types

  • Every value in a program has a type.
  • Types are either primitive or reference types.
  • AP Computer Science A uses only three primitive types:
    • int: integer numbers (e.g., 3, -14, 21860)
    • double: floating-point numbers (e.g., 3.14, -1.0, 48.7662)
    • boolean: true and false (e.g. true, false)
  • Literals are representations in code of exact values.

Arithmetic Expressions

  • int and double can be used in arithmetic expressions.
  • Arithmetic operators:
    • +: addition
    • -: subtraction
    • *: multiplication
    • /: division
    • %: modulus
  • Precedence rules:
    • 1. *, /, %
    • 2. +, -
  • Operators within the same group are evaluated from left to right.
  • Parentheses override precedence rules.
    • Example: 4+32=104 + 3 * 2 = 10, (4+3)2=14(4 + 3) * 2 = 14
  • When an arithmetic operation involves two int values, the result is an int.
    • Example: 7/4=17 / 4 = 1
  • If an operation involves at least one double value, the result will be a double.
  • Division will behave as expected mathematically when doubles are involved.

Variable Declaration and Assignment

  • A variable is a name associated with a piece of computer memory that stores a value.
  • Every variable has a type.
  • A variable declaration statement consists of a type followed by a name.
    • Example: int age;
  • An assignment statement has a variable on the left side of an equal sign and an expression on the right side.
  • Declaration and assignment can be combined:
    • int age;
    • age = 18;
    • Is equivalent to:
    • int age = 18;
  • The value of a variable can be changed using another assignment statement:
    • double fin = 3.2;
    • System.out.println(fin); // prints 3.2
    • fin = 4.5 – 5.1;
    • System.out.println(fin); // prints -0.6
  • final keyword: If a variable is intended to refer to a value that will never change, it can be declared using the final keyword.
    • final int x = 5;
    • x = x - 2; // this line will cause a compiler error

Compound Operators

  • A common operation is to retrieve the value of a variable, update it using an arithmetic operation, and store the result back in the same variable.
  • For every arithmetic operator, there is a corresponding compound operator.
  • Compound operators:
    • +=: x+=3x += 3 is equivalent to x=x+3x = x + 3
    • -=: x=1x -= 1 is equivalent to x=x1x = x - 1
    • *=: x=2x *= 2 is equivalent to x=x2x = x * 2
    • /=: x/=10x /= 10 is equivalent to x=x/10x = x / 10
    • %=: xx %= 10 is equivalent to x=xx = x % 10
  • Increment and decrement operations:
    • Increment: Adding one to a variable.
      • x++
      • x += 1
      • x = x + 1
    • Decrement: Subtracting one from a variable.
      • x--
      • x -= 1
      • x = x - 1

Casting

  • Values of a certain type can only be stored in a variable of that type.
  • Example of an error:
    • int myVariable = 6.3;
  • Casting operators (int) and (double) create temporary values converted to another type.
  • Casting a double to an int results in truncation (digits after the decimal points are dropped). Example: (int)12.8 evaluates to 12.
    • int x = (int)points;
  • In some cases, int values will automatically be cast to double values.
    • int x = 10;
    • double y = 2 * x + 3; // y will store the value 23.0
  • When calling a method that declares a double parameter, it is legal to pass an integer value in as the actual parameter.

Free Response Tip

  • Be careful about storing accumulated values in an int variable, especially if the task requires you to find an average.
  • Store the accumulated value in a double variable, or be sure to cast to a double before dividing to find the average to get the correct average instead of a truncated value.

Sample primitive types questions

  • Question 1
    • Code:
      • int x = 9;
      • int y = 2;
      • int z = 1;
      • System.out.println(x / y * 1.5 - z);
    • What is output?
      • Answer: B. 5.0
      • Explanation: integer division 9/2 results in 4. Then 4*1.5 = 6.0. Then 6.0-1 = 5.0
  • Question 2
    • Code:
      • double a = 3.6;
      • int b = (int)a + 2;
      • double c = b;
      • System.out.print(a + " " + b + " " + c);
    • What is output?
      • Answer: A. 3.6 5 5.0
      • Explanation: a = 3.6. b = 3+2 = 5. c = 5.0
  • Question 3
    • Code:
      • int a = 8;
      • System.out.print("*");
      • System.out.println(a);
      • System.out.println(a + 2);
      • System.out.println("*");
    • What is output?
      • Answer: A.
        8
        10
      • Explanation: System.out.print does not advance to the next line, while System.out.println does.

Using Objects

  • 5–7.5% of questions.
  • Values in Java are either primitive or reference types.
  • An object is a compound value that has attributes (data) and methods.
  • A class is a blueprint for objects.

Constructing and Storing Objects

  • An object is created by calling the class constructor with the new keyword.

  • The constructor name is the same as the class name.

  • The constructor may have a list of parameters representing initial values.

  • The signature of a constructor: name of the constructor + list of types of parameters.

  • A class may define multiple constructors if their signatures differ (constructor overloading).

  • Valid constructor calls for a Rectangle class with constructors Rectangle(int width, int height) and Rectangle(int x, int y, int width, int height):

    • new Rectangle(5, 6)
    • new Rectangle(-1, 2, 3, 8)
  • Invalid constructor calls:

    • new Rectangle(3.2, 1)
    • new Rectangle(1, 2, 3)
  • An object needs to be stored in a variable whose type is compatible with the class the object belongs to.

  • Example: Rectangle myRectangle = new Rectangle(5, 6);

  • A reference variable refers to an object (stores the location in memory where the object exists).

  • null is a special value for reference variables that do not contain a reference to any actual object.

Calling Void Methods

  • Interaction with objects is done primarily by calling their methods.
  • Every method has a signature: name + list of the types of parameters it defines.
  • Methods can be overloaded (multiple methods with the same name as long as their signatures are different).
  • When a method is called, the program's execution is interrupted, and control is transferred to the method.
  • When the method is complete, execution continues at the method call.
  • Some methods return a result when they are complete.
  • void methods do not return a value and can only be called as standalone statements.
  • A method is called using the dot operator: object name . method name(parameters).
  • Example: myRectangle.grow(4, 4); (myRectangle stores a reference to a Rectangle object.)
  • A method cannot be called on a null value (NullPointerException will be thrown).

Calling Non-Void Methods

  • When a method is not void, it has a return type.

  • The method returns a value, and the method call expression evaluates to this value.

  • Since it has a value, it can be used as part of an expression in place of any value of the specified type.

  • Example: If the method getHeight() in the Rectangle class returns a value of type int, then the following is a valid statement:

    • int someValue = 2 * myRectangle.getHeight() + 1;
  • If, in addition to returning a value, a method has side effects, there may be instances when you do not care about the returned value.

  • If you only care about the side effects of a method, it can be called as if it were a void method, even if it returns a value.

    • myRectangle.getHeight();is legal, although it may not be useful in many situations.

Strings

  • A string is a sequence of characters.

  • String literals are enclosed in double quotes (e.g., "Hello", "32", "").

  • The empty string: ""

  • Strings are an exception to the general rule of object construction (can be constructed using literal values).

  • Strings can be combined (concatenated) using the + operator.

  • Example: String str1 = "AP";String str2 = "Exam";String combined = str1 + " " + str2;

  • When primitive values are concatenated with strings, they are automatically cast to strings.

    • "I am " + (14 + 4) + " years old" evaluates to "I am 18 years old".
  • An escape sequence is a series of characters beginning with a backslash that has special meaning in Java.

    • \": double quote character
    • \\: backslash character
    • \n: new line character
  • The characters in a string are classified by their position or index starts at 0

  • Any attempt to refer to a character at an invalid index will result in a StringIndexOutOfBoundsException being thrown.

String methods (AP Computer Science A exam)

  • String(String str): constructs a new string that is identical to str.
  • int length(): returns the number of characters in the string.
  • String substring(int from, int to): returns a new string consisting of the characters that range from index from to index to - 1.
  • String substring(int from): returns a new string consisting of the characters beginning at index from and continuing to the end of the string.
  • int indexOf(String str): returns the index of the first occurrence of str within the string, if any, and -1 otherwise.
  • boolean equals(String other): returns true if the string is equal to other, and false otherwise.
  • int compareTo(String other): returns a negative value if the string comes before other, a positive value if the string comes after other, and 0 if the two are equal.
  • The charAt method is not covered; retrieving a single character (as a string) at index n can be accomplished by calling substring(n, n+1). Strings are immutable.

Wrapper Classes

  • There are various circumstances in which it is more convenient to work with objects rather than primitive values.
  • Java provides the wrapper classes Integer and Double.
  • Each of these classes has a constructor that accepts a primitive value of the appropriate type, and a method that returns the primitive value.
  • The Integer class also provides static fields that represent the maximum and minimum values that can be represented by an int.
Integer
  • Integer(int value): Constructs an Integer object with the specified value.
  • int intValue(): Returns the stored int value.
  • Integer.MAX_VALUE: The maximum value that can be represented by an int.
  • Integer.MIN_VALUE: The minimum value that can be represented by an int.
Double
  • Double(double value): Constructs a Double object with the specified value.

  • double doubleValue(): Returns the stored double value.

  • The Java compiler has features called autoboxing and unboxing that automatically convert between these wrapper classes and the corresponding primitive types.

  • When a method expects a double, a Double can be passed, and vice versa.

Static Methods and Math

  • A static method is called using the name of the class to which it belongs, rather than an object.
  • The Math class is an example of a class that contains only static methods.
Math Methods
  • int abs(int x): Returns the absolute value of x.
  • double abs(double x): Returns the absolute value of x.
  • double pow(double b, double e): Returns $b^e$.
  • double sqrt(double x): Returns the square root of x.
  • double random(): Returns a value in the interval [0,1).

Free Response Tip

  • When writing code in a free response question, think carefully about whether every method you call is static or not.
  • If it is static, make sure it is preceded by a class name. If not, make sure it is preceded by an object name.
  • The only time you can call a method without any dot operator is when you are calling a method within the same class.

Sample Using Objects Questions

  • Question 1
    • Code:
      • ```java
        public class Toy
        {
        private String name;
        public Toy()
        {
        name = "Venus";
        }
        public Toy(String s)
        {
        name = s;
        }
        public void printName()
        {
        System.out.println("This toy is named: " + name);
        }
        }
        ```
    • Which statements correctly creates an instance of a Toy object named Mars?
      • Answer: B. Toy t = new Toy(“Mars”);
      • Explanation: Every object is created using the keyword new followed by a call to one of the class’s constructors.
  • Question 2
    • Code:
      • ```java
        String s1 = "Hello";
        String s2 = "World";
        System.out.println(s1 + ", " + s2);
        String s3 = new String("Hi");
        s3 += ",\nWorld";
        System.out.println(s3);
        ```
    • What is printed?
      • Answer: B.
        Hello, World
        ```
        Hi,
        World
        ```
      • Explanation: The + operator is used to concatenate Strings in Java. String objects can either be created by a literal String, or by the new operator. \n represents the newline character. The += operator concatenates onto the end of the specified String.
  • Question 3
    • Which is a code segment that would yield a compiler error?
      • Answer: C. int x = Math.pow(4.0,3.0);
      • Explanation: The Math.pow method returns a double, which cannot be automatically narrowed into the int datatype. An int typecast is necessary.

Boolean Expressions and if Statements

  • About 15–17.5% of the questions.

Boolean Expressions

  • A Boolean value is either true or false.
  • Boolean values are commonly created using the relational operators with primitive values.
  • Six relational operators: <, <=, >, >=, ==, and !=.
  • Any expression that evaluates to a Boolean value is called a Boolean expression.
  • More complex Boolean expressions can be formed using the logical operators:
    • && (and): A && B is true only when A and B are both true.
    • || (or): A || B is true when at least one of A or B is true.
    • ! (not): !A is true only when A is false.
  • Two Boolean expressions are equivalent if they evaluate to the same truth value for all possible values of their variables.
  • De Morgan's Laws provide a common method for transforming Boolean expressions into equivalent ones:
    • !(A && B) is equivalent to !A || !B
    • !(A || B) is equivalent to !A && !B

Comparing Objects

  • Reference variables store references to objects, rather than the objects themselves.
  • When objects are compared using == and !=, it is only the references that are being compared, not the contents of the actual objects.
  • These operators only check if two references are aliases of each other.
  • == and != can be used to check whether a reference variable is null.
  • Comparing objects themselves for equality can only be achieved if the class provides an equals method, as we saw exists for String.

Free Response Tip

  • Only use == and != if you are either comparing primitive values or checking to see if a reference variable is null.
  • If an object has an equals method, and you want to check if it is not equal to another object, you can use the following idiom: !obj1.equals(obj2). Remember to only use == for primitive values

if and if-else Statements

  • Control flow statements are used when a program needs to make decisions based on its current state.
  • An if statement allows the program to either execute or skip a section of code based on whether a Boolean expression is true or false.
  • Syntax:

```
if (expression) {
// one or more statements
}
```

  • If expression evaluates to true, the statements in the block are executed. Otherwise, the statements in the body are skipped.
  • Optionally, an else clause can be added:

```
if (expression) {
// one or more statements
} else {
// one or more statements
}
```

  • If expression evaluates to true, the statements in the if block are executed. Otherwise, the statements in the else block are executed.
  • For both the if and else blocks, the curly braces can optionally be omitted if they consist of only a single statement.

if-else-if Statements

  • To check for multiple possibilities, an if can be followed by one or more else if clauses.

```
if (expression1) {
// statements1
} else if (expression2) {
// statements2
} else if (expression3) {
// statements3
} else {
// statements4
}
```

  • In this code, there are four possible execution paths. If expression1 is true, statements1 is executed. Otherwise, if expression2 is true, statements2 is executed. If neither of the first two expressions are true, but expression3 is, then statements3 is executed. Finally, if none of the expressions are true, the else block is executed.
  • There can be an arbitrary number of else if clauses, and the else block at the end is optional.
  • If no else block is provided, and none of the expressions are true, then nothing will be executed.

Free Response Tip

  • When writing if-else-if statements, keep in mind that each expression is only evaluated if none of the previous ones have evaluated as true yet; at most one of the statement blocks will be executed.
  • This contrasts with consecutive if statements, where all of the Boolean expressions will be checked, and many of the statement blocks can potentially be run.

Sample Boolean Expressions and if Statements Questions

  • Question 1
    • Code:
      • (temperature >= 20 && temperature <= 80) && (humidity <= .5)
    • Which expressions are equivalent?
      • Answer: C. II and III only
      • Explanation: The original expression returns True if temperature is between 20 and 80 inclusive, and humidity is less than or equal to .5.
  • Question 2
    • Code:

```
int score = 5;
if (score >= 2)
{
score = 1;
System.out.print("A");
}
else
{
System.out.print("B");
}
if (score

  • Question 3
    • Code:
      • ```The following table maps a temperature in Fahrenheit to a qualitative description.
        Temperature in Fahrenheit Description
        90 or above Hot
        70 – 89 Warm
        45 – 69 Mild
        44 or below Chilly
        Which of the following code segments will print the correct description for a given integer temperature?
        ```
    • Which code segments will print the correct description for a given integer temperature?
      • Answer: E. I, II, and III
      • Explanation: In a multiway condition statement, the first section of code is executed based on whichever condition is first true. For any possible integer value, the same string will print in all three code segments.

Iteration

  • 17.5–22.5% of questions.

while Loops

  • The while statement allows a code block to repeat as long as a condition is true.

```
while (expression) {
// one or more statements
}
```

  • The block will be executed if expression is true. After execution, the condition is checked again, and if true, the block is executed again. This continues until the condition becomes false, at which point the rest of the program continues.
  • If expression is false the first time it is encountered, the body of the loop is never run.
  • It is important to make sure that the condition eventually becomes false, or the loop will be executed infinitely.
  • Example of an infinite loop:

```
int x = 12;
while (x > 0) {
System.out.println("A");
}
```

  • Fixed version:

```
int x = 12;
while (x > 0) {
System.out.println("A");
x--;
}
```

for Loops

  • A for loop uses a variable to count the iterations of a loop.
  • Structure:

```
for (initialization; expression; increment) {
// statements
}
```

  • When the loop is first encountered, the initialization statement is executed. Then expression is evaluated. If it is true, the loop body is executed. After execution, increment is executed, and expression is evaluated again. This continues until expression is false, at which point the loop is done. The order of execution

    • Initialization
    • Expression/Condition check
    • If True, Body
    • Increment
  • The initialization statement usually consists of a variable declaration and assignment.

  • The increment modifies that variable by adding or subtracting a fixed value.

  • Examples:

    • for (int i = 0; i < 5; i++) { … }
    • for (int count = 100; count >= 0; count -= 2) { … }
  • There are several standard algorithms that use for loops with which you should be familiar:

    • Identify the individual digits within an integer using a while loop, modulus, and division.
    • Count the number of times that a criterion is met within a range of values.

Free Response Tip

  • When writing code, there are no absolute rules for deciding when to use a while loop vs a for loop.
  • Either kind of loop can be used in any situation.
  • while loops are generally better for situations in which you don't know in advance how many times the code needs to be executed, and need to check a condition to know whether or not to continue.
  • for loops are easier to use when you can explicitly count the repetitions.

String Algorithms

  • Loops are often used in the context of processing strings.
  • Combined with the indexOf and substring methods, loops are essential for examination of different parts of strings.
  • Two particular patterns that frequently occur:

```
for (int i = 0; i < myStr.length() – k + 1; i++) {
String subs = myStr.substring(i, i + k);
// do something with subs
}
```

  • In this code, the variable i is used to keep track of the index in a string. In each iteration, a substring of length k is retrieved starting at index i.
  • Note carefully the value used in the loop condition: i < str.length() – k + 1.

```
int pos = myStr.indexOf(target);
while (pos > 0) {
// target string was found
pos = myStr.indexOf(target, pos + 1);
}
```

  • Here, a string is repeatedly searched for some target. When it is no longer found, the indexOf method will return -1, which will cause the loop to terminate.

Nested Loops

  • When a loop is used in the body of another loop, it is referred to as a nested loop.
  • Nested loops are often used in more complex string and array algorithms and are very common with 2D arrays.
  • They are also commonly used for printing tabular data and patterns.
  • Example:

```
for (int x = 5; x >= 1; x--) {
for (int y = 0; y < x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
```

  • Output:

```
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
```

Sample Iteration Questions

  • Question 1
    • Code:
      • ```java
        public static String reverse(String s)
        {
        String toReturn = "";
        for ( /* missing code */ )
        {
        toReturn += s.charAt(i);
        }
        return toReturn;
        }
        ```
    • Which code completes the loop?
      • Answer: D. int i = s.length() - 1; i >= 0; i--
      • Explanation: The desired behavior of this method is to return a new string that is a reversal of the characters in the argument. One algorithm is that the for loop should iterate from the last character in the string to the first. The index of the last character is one less than the length of the string. The update of the for loop decrements to count backwards.
  • Question 2
    • Code:

`` int i, j; for (i = 1; i <= 3; i++) { System.out.print(i + " "); j = i; while (j > 0) { System.out.print(j + " "); j--; } } \``` * What is the output? * Answer: C. 1 1 2 2 1 3 3 2 1 * Explanation: When a loop is placed inside of another loop, the inner loop must complete all of its iterations before the outer loop can continue. In this code segment, the outer loop iterates and prints1 2 3`. After 1 is printed, the inner loop prints 1; after 2 is printed, the inner loop prints 2 1; after 3 is printed, the inner loop prints 3 2 1.

  • Question 3
    • Code:

`` 1 int i; 2 for (i = 1; i <= 100; i += 2) 3 { 4 if (i >= 10 && i < 100) 5 { 6 System.out.print(i + " "); 7 } 8 } \``` * How does the result change if Line 2 is changed tofor (i = 100; i >= 1; i -= 2)`?
* Answer: D. The initial program prints all two-digit odd numbers in increasing order; the modified program prints all two-digit even numbers in decreasing order.
* Explanation: Line 4 of the code segment enforces the condition that only two-digit integers are printedin Line 6. The initial program’s for loop iterates over every odd integer from 1 to 100; the modified program’s for loop iterates over every even integer from 100 to 1.

Writing Classes

  • About 5–7.5% of the questions.

Class Structure and Visibility

  • Basic structure:

```
public class MyClass {
// instance variables
// constructor
// methods
}
```

  • Instance variables are the data or attributes associated with an object.
  • Constructors are the means by which the objects are constructed.
  • Methods are the behaviors that the objects have available to them.
  • Every declaration in a class has a visibility modifier attached to it
    • Can be public or private
  • public: can be directly accessed from outside of the class.
  • private: restricts access to code inside the class itself.
  • For the purposes of the AP Computer Science A exam, the following guidelines apply:
    *