Unit 2 Using Objects

5 Steps to a 5: AP Computer Science A 2024 - Klipp D.B., Johnson D.R., Paymer C.A. 2023

Unit 2 Using Objects
STEP 4 Review the Knowledge You Need to Score High

IN THIS UNIT

Summary: This chapter introduces you to the most fundamental object-oriented features of Java. It explains the relationship between an object and a class. You will learn how to use objects created from classes that are already defined in Java. More advanced aspects of classes and objects will be discussed in Unit 5. You will learn how letters, words, and even sentences are stored in variables. String objects can store alphanumerical data, and the methods from the String class can be used to manipulate this data. The Java API (application programming interface) contains a library of thousands of useful classes that you can use to write all kinds of programs. Because the Java API is huge, the AP Computer Science A Exam only tests your knowledge of a subset of these classes. This unit provides practice working with four of those classes: String, Math, Integer, and Double.

Image

Key Ideas

Image Java is an object-oriented programming language whose foundation is built on classes and objects.

Image A class describes the characteristics of any object that is created from it.

Image An object is a virtual entity that is created using a class as a blueprint.

Image Objects are created to store and manipulate information in your program.

Image A method is an action that an object can perform.

Image The keyword new is used to create an object.

Image A reference variable stores the address of the object, not the object itself.

Image The Java API contains a library of thousands of classes.

Image Strings are used to store letters, words, and other special characters.

Image To concatenate strings means to join them together.

Image The String class has many methods that are useful for manipulating String objects.

Image The Math class contains methods for performing mathematical calculations.

Image The Integer class is for creating and manipulating objects that represent integers.

Image The Double class is for creating and manipulating objects that represent decimal numbers.

The Java API and the AP Computer Science A Exam Subset

Want to make a trivia game that poses random questions? Want to flip a coin 1 million times to test the laws of probability? Want to write a program that uses the quadratic formula to do your math homework? If so, you will want to learn about the Java API.

The Java API, or application programming interface, describes a set of classes and files for building software in Java. The classes in the APIs and libraries are grouped into packages, such as java.lang. The documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. It shows how all the Java features work and interact. Since the Java API is gigantic, only a subset of the Java API is tested on the AP Computer Science A Exam. All of the classes described in this subset are required. The Appendix contains the entire Java subset that is on the exam. The String, Math, Integer, and Double classes are part of the java.lang package and are available by default.

The String Variable

How does Twitter know when a tweet has more than 280 characters? How does the computer know if your username and password are correct? How are Facebook posts stored? We need a way to store letters, characters, words, or even sentences if we want to make programs that are useful to people. The String data type helps solve these problems.

When we wanted to store numbers so that we can retrieve them later, we created either an int or double variable. Now that we want to store letters or words, we need to create String variables. A String can be a single character or group of characters like a word or a sentence. String literals are characters surrounded by double quotation marks.

General Way to Make a String Variable and Assign It a Value

Image

Examples

Make some String variables and assign them values:

Image

The String Object

String variables are actually objects. The String class is unique because String objects can be created by simply declaring a String variable like we did above or by using the constructor from the String class. The reference variable knows the address of the String object. The object is assigned a value of whatever characters make up the String literal.

General Way to Make a String Object Using the Constructor from the String Class

Image

Example 1

Make a String object and assign it a value:

Image

Example 2

Create a String object, but don’t give it an initial value (use the empty constructor from the String class). The String object contains an empty string, which means that the value exists (it is not null); however, there are no characters in the String literal and it has a length of 0 characters.

Image

Example 3

Create a String reference variable but don’t create a String object for it. The String reference variable is assigned a value of null because there isn’t an address of a String object for it to hold.

Image

null String Versus Empty String

A null string is a string that has no value and no length. It does not hold an address of a String object.

An empty string is a string that has a value of "" and its length is zero. There is no space inside of the double quotation marks, because the string is empty.

It may seem like they are the same thing, but they are not. The difference is subtle. The empty string has a value and the null string does not. Furthermore, you can perform a method on an empty string, but you cannot perform a method on a null string.

Any attempt to execute a method on a null string will result in a run-time error called a NullPointerException.

A Visual Representation of a String Object

This is a visual representation of what a string looks like in memory. The numbers below the characters are called the indices (plural of index) of the string. Each index represents the location of where each of the characters lives within the string. Notice that the first index is zero. An example of how we read this is: the character at index 4 of myFavoriteFoodGroup is the character “c”. Also, spaces count as characters. You can see that the character at index 3 is the space character.

Image

String Concatenation

Now that you know how to create a string and give it a value, let’s make lots of them and string them together (Ha!). The process of joining strings together is called concatenation. The + and += signs are used to concatenate strings.

Example 1

Concatenate two strings using +.

Image

Example 2

Concatenate two strings using +=.

Image

Example 3

Concatenate a number and a string using +.

Image

Example 4

Incorrectly concatenate a string and the sum of two numbers using +. Notice that the sum is not computed since the + operator follows a string variable and is treated as concatenation.

Image

Example 5

Correctly concatenate a string and the sum of two numbers using +. Notice the () are evaluated first which means the + is treated as addition.

Image

Example 6

Concatenate the sum of two numbers and a string in a different order. Notice that when the numbers come first in the concatenation, the sum is computed.

Image

Image

Concatenation

Strings can be joined together to form a new string using concatenation. The + sign or the += operation may be used to join strings.

You can even join an int or a double along with a string. These numbers will be rendered useless for any mathematical purpose because they are turned into strings.

The Correct Way to Compare Two String Objects

Everyone reading this book has had to log in to a computer at some time. How does the computer know if the user typed the username and password correctly? The answer is that the software uses an operation to compare the input with the information in a database.

In Java, we can determine if two strings are equal to each other. This means that the two strings have exactly the same characters in the same order.

Image

The Correct Way to Compare Two String Objects

Use the equals method or the compareTo method to determine if two String variables contain the exact same character sequence.

Important String Methods

The equals Method

The equals method returns a boolean answer of true if the two strings are identical and it returns an answer of false if the two strings differ in any way. The equals method is case-sensitive, so, for example, the uppercase “A” is different than the lowercase “a”. The ! operator can be used in combination with the equals method to compare if two strings are not equal.

Example 1

Determine if two strings are equal:

Image

Example 2

Determine if two strings are not equal:

Image

Image

Never Use == to Compare Two String Objects

We used the double equals (==) to compare if two numbers were the same. However, == does not correctly tell you if two strings are the same. What’s worse is that comparing two strings using == does not throw an error; it simply compares whether or not the two String references point to the same object. Even worse is that sometimes it appears to work correctly. Just don’t do it!

Image

The compareTo Method

The second way to compare two strings is to use the compareTo method. Instead of returning an answer that is a boolean like the equals method did, the compareTo method returns an integer. The result of the compareTo method is a positive number, a negative number, or zero. This integer describes how the two strings are ordered lexicographically; a case-sensitive ordering of words similar to a dictionary but using the UNICODE codes of each character.

Image

The compareTo Method

The compareTo method returns an integer that describes how the two strings compare.

Image

The answer is zero if the two strings are exactly the same.

The answer is negative if firstString comes before secondString (lexicographically).

The answer is positive if firstString comes after secondString (lexicographically).

Example 1

The answer is zero if the two strings are exactly the same:

Image

Example 2

The answer is negative when the first string comes before the second string (lexicographically):

Image

Example 3

The answer is positive when the first string comes after the second string (lexicographically):

Image

Example 4

Uppercase letters come before their lowercase counterparts. "Hello" comes before "hello" when comparing them using lexicographical order:

Image

Image

Fun Fact: Unicode is a worldwide computing standard that assigns a unique number to nearly every possible character (including symbols) for every language. There are more than 120,000 characters listed in the latest version of Unicode. For example, the uppercase letter "A" is 41 (hexadecimal), the lowercase letter "a" is 61 (hexadecimal), and "ñ" is F1 (hexadecimal).

The length Method

The length method returns the number of characters in the specified string (including spaces).

Example 1

Find the length of a string:

Image

Example 2

Find the length of a string that is empty, but not null (it has "" as its value):

Image

Example 3

Attempt to find the length of a string that is null:

Image

Image

The NullPointerException

Attempting to use a method on a string that has not been initialized will result in a run-time error called a NullPointerException. The compiler is basically telling you that there isn’t an object to work with, so how can it possibly perform any actions with it?

The indexOf Method

To find if a string contains a specific character or group of characters, use the indexOf method. It searches the string and if it locates what you are looking for, it returns the index of its location. Remember that the first index of a string is zero and the last index is length -1. If the indexOf method doesn’t find the string that you are looking for, it returns -1.

Example 1

Find the index of a specific character in a string.

Image

Example 2

Find the index of a character in a string when it appears more than once.

Image

Example 3

Attempt to find the index when the character is not in the string.

Image

Example 4

Find the index of a string inside a string.

Image

The substring Method

The substring method is used to extract a specific character or group of characters from a string. All you have to do is tell the substring method where to start extracting and where to stop.

The substring method is overloaded. This means that there is more than one version of the method.

Image

Example 1

Extract every character starting at a specified index from a string.

Image

Example 2

Extract one character from a string.

Image

Example 3

Extract two characters from a string.

Image

Example 4

Extract the word “force” from a string:

Image

Example 5

Use numbers that don’t make any sense:

Image

Image

The StringIndexOutOfBoundsException

If you use an index that doesn’t make any sense, you will get a run-time error called a StringIndexOutOfBoundsException. Using an index that is greater than or equal to the length of the string or an index that is negative will produce this error.

Example 6

Extract the word "the" from the following string by finding and using the first and second spaces in the string:

Image

Image

Helpful Hint for the substring Method

To find out how many characters to extract, subtract the first number from the second number.

Image

Since 13 − 5 = 8, the result contains a string that is a total of eight characters.

Note: When the start index and end index are the same number, the substring method does not return a character of the string; it returns the empty string "".

Image

You will receive a Java Quick Reference sheet to use on the Multiple-choice and Free-response sections, which lists the String class methods that may be included in the exam. Make sure you are familiar with it before you take the exam.

Image

A String Is Immutable

An immutable object is an object whose state cannot be modified after it is created. String objects are immutable, meaning that the String methods do not change the String object. String variables are actually references to String objects, but they don’t operate the same way as normal object reference variables.

Every time you make a change to a String variable, Java actually tosses out the old object and creates a new one. You are never actually making changes to the original String object and resaving the same object with the changes. Java makes the changes to the object and then creates a brand-new String object and that is what you end up referencing.

Example

Demonstrate how a String variable is immutable through concatenation. Even though it seems like you are modifying the String variable, you are not. A completely brand-new String object is created and the variable is now referencing it:

Image

Escape Sequences

How would you put a double quotation mark inside of a string? An error occurs if you try because the double quotes are used to define the start and end of a String literal. The solution is to use an escape sequence.

Escape sequences are special codes that are embedded in String literals that are sent to the computer that say, “Hey, watch out, something different is coming.” They use a backslash followed by a special character. Escape sequences are commonly used when concatenating strings to create a single string. Here are the most common escape sequences (\t is not tested on the AP Computer Science A exam but is useful for displaying output in columns).

Image

The Math Class

The Math class was created to help programmers solve problems that require mathematical computations. Most of these methods can be found on a calculator that you would use in math class. In fact, if you think about how you use your calculator, it will make it easier to understand how the Math class methods work. The Math class also includes a random number generator to help programmers solve problems that require random events.

Compared to the other classes in the AP Computer Science A subset, the Math class is special in that it contains only static methods. This means that you don’t need to create an object from the class in order to use the methods in the class. All you have to do is use the class name followed by the dot operator and then the method name.

Image

The Math Class Doesn’t Need an Object

The methods and fields of the Math class are accessed by using the class name followed by the method name.

Math.methodName();

Important Math Class Methods

The Math class contains dozens of awesome methods for doing mathematical work. The AP Computer Science A exam only requires you to know a small handful of them.

Image

Example 1

Demonstrate how to use the absolute value method on an integer:

Image

Example 2

Demonstrate how to use the absolute value method on a double:

Image

Example 3

Demonstrate how to use the square root method. The sqrt method will compute the square root of any number that is greater than or equal to 0. The result is always a double, even if the input is a perfect square number.

Image

Example 4

Demonstrate how to use the power method. The pow method always returns a double.

Image

Example 5

Demonstrate how to use the random method.

Image

Example 6

Demonstrate how to access the built-in value of pi from the Math class.

Image

Random Number Generator in the Math Class

The random number generator from the Math class returns a double value in the range from 0.0 to 1.0, including 0.0, but not including 1.0. Borrowing some notation from math, we say that the method returns a value in the interval [0.0, 1.0).

The word inclusive means to include the endpoints of an interval. For example, the interval [3,10] means all of the numbers from 3 to 10, including 3 and 10. Written mathematically, it’s the same as 3 ≤ x ≤ 10. Finally, you could say you are describing all the numbers between 3 and 10 (inclusive).

Image

Using Math.random() to Generate a Random Integer

The random method is great for generating a random double, but what if you want to generate a random integer? The secret lies in multiplying the random number by the total number of choices and then casting the result to an integer.

General Form for Generating a Random Integer Between 0 and Some Number

Image

General Form for Generating a Random Integer Between Two Positive Numbers

Image

Example 1

Generate a random integer between 0 and 12 (inclusive):

Image

Example 2

Generate a random integer between 4 and 20 (inclusive):

Image

Example 3

Pick a random character from a string. Use the length of the string in the calculation.

Image

Image

The Integer Class

The Integer class has the power to turn a primitive int into an object. This class is called a wrapper class because the class wraps the primitive int into an object. A major purpose for the Integer class will be revealed in Unit 7. Java can convert an Integer object back into an int using the intValue method.

Example 1

Create an Integer object from an int.

Image

Example 2

Obtain the value of an Integer object using the intValue() method.

Image

Example 3

Attempt to create an Integer object using a double value.

Image

Example 4

Attempt to create an Integer object without using a value.

Image

Fields of the Integer Class

MAX_VALUE and MIN_VALUE are public fields of the Integer class. A field is a property of a class (like an instance variable). These two are called constant fields and their values cannot be changed during run-time. By naming convention, constants are typed using only uppercase and underscores. Also, they don’t have a pair of parentheses, because they are not methods.

Why is there a maximum or minimum integer? Well, Java sets aside 32 bits for every int. So, the largest integer that can be stored in 32 bits would look like this: 01111111 11111111 11111111 11111111. Notice that the leading bit is 0. That’s because the first bit is used to assign the sign (positive or negative value) of the integer. If you do the conversion to decimal, this binary number is equal to 2,147,483,647; the largest integer that can be stored in an Integer object. It’s also equal to one less than 2 to the 31st power.

If you add one to this maximum number, the result causes an arithmetic overflow and the new number is pretty much meaningless. Worse yet, the overflow does not cause a run-time error, so your program doesn’t crash. Moral of the story: Be careful when you are using extremely large positive or small negative integers.

Example 1

Obtain the maximum value represented by an int or Integer.

Image

Example 2

Obtain the minimum value represented by an int or Integer.

Image

Image

MAX_VALUE and MIN_VALUE Are Constants

A constant in Java is a value that is defined by a programmer and cannot be changed during the running of the program. The two values, MAX_VALUE and MIN_VALUE, are constants of the Integer class that were defined by the creators of Java. By naming convention, constants are always typed in uppercase letters and underscores.

Image

Fun Fact: Java has different data types for storing numbers. The long data type uses 64 bits and the largest number it can store is 9,223,372,036,854,775,807. This is not on the AP Computer Science A exam.

The Double Class

The Double class is a wrapper class for primitive doubles. The Double class is used to turn a double into an object.

Example 1

Create a Double object from a double.

Image

Example 2

Obtain the value of a Double object by using the doubleValue() method.

Image

Example 3

Create a Double object using an int value.

Image

Example 4

Attempt to create a Double object without using a value.

Image

Image

Fun Fact: The Double class also has a MAX_VALUE and MIN_VALUE, but they are not tested on the AP Computer Science A exam.

Autoboxing and Unboxing

Conversion between primitive types (int, double, boolean) and the corresponding object wrapper class (Integer, Double, Boolean) is performed automatically by the compiler. This process is called “autoboxing.” Conversely, “unboxing” is the automatic conversion from the wrapper class to the primitive type. The reason we need to know this conversion will be relevant in Unit 7.

Example 1

Autobox a Double object from a double.

Image

Example 2

Unbox an Integer object to an integer.

Image

Example 3

Multiply the value of a Double object by 3 and store its value into a double.

Image

Example 4

Multiply the value of a Double object by 3 and store its value into a double without using the automatic unboxing feature.

Image

Summary of the Integer and Double Classes

Image

Image

You will receive a Java Quick Reference sheet to use on the Multiple-choice and Free-response sections, which lists the Math, Integer, and Double class methods that may be included in the exam. Make sure you are familiar with it before you take the exam.

Image Rapid Review

Strings

• The String class is used to store letters, numbers, or other symbols.

• A String literal is a sequence of characters contained within double quotation marks.

• You can create a String variable by declaring it and directly assigning it a value.

• You can create a String variable using the keyword new along with the String constructor.

• Strings are objects from the String class and can utilize methods from the String class.

• Strings can be concatenated by using the + or += operators.

• Compare two String variables using the equals method or the compareTo method.

• Strings should never be compared using the == comparator.

• Every character in a string is assigned an index. The first index is zero. The last index is one less than the length of the string.

• Escape sequences are special codes that are embedded in String literals to perform such tasks as issuing a new line or a tab, or printing a double quote or a backslash.

• A null string does not contain any value. It does not reference any object.

• If a string is null, then no methods can be performed on it.

• A NullPointerException is thrown if there is any attempt to perform a method on a null string.

• An empty string is not the same as a null string.

• An empty string has a value of "" and a length of zero.

String Methods

• The equals(String other) method returns true if the two strings that are being compared contain exactly the same characters.

• The compareTo(String other) method compares two strings lexicographically.

• Lexicographical order is a way of ordering words based on their Unicode values.

• The length() method returns the number of characters in the string.

• The indexOf(String str) method finds and returns the index value of the first occurrence of str within the String object that called the method. The value of -1 is returned if str is not found.

• The substring(int index) method returns a new String object that begins with the character at index and extends to the end of the string.

• The substring(int beginIndex, int endIndex) method returns a new String object that begins at the beginIndex and extends to the character at endIndex - 1.

• Strings are immutable. A new String object is created each time changes are made to the value of a string.

• A StringIndexOutOfBoundsException error is thrown for any attempt to access an index that is not in the bounds of the String literal.

Math Class

• The Math class has static methods, which means you don’t create a Math object in order to use the methods or fields from the class.

• The dot operator is used to call the methods from the Math class: Math.methodName().

• The Math.abs(int x) method returns an int that is the absolute value of x.

• The Math.abs(double x) method returns a double that is the absolute value of x.

• The Math.sqrt(double x) method returns a double that is the square root of x.

• The Math.pow(double base, double exponent) method returns a double that is the value of base raised to the power of exponent.

• The Math.random() method returns a double that is randomly chosen from the interval [0.0, 1.0).

• By casting the result of a Math.random() statement, you can generate a random integer.

Integer and Double Classes

• The Integer and Double classes are called wrapper classes, since they wrap a primitive int or double value into an object.

• An Integer object contains a single field whose type is int.

• The Integer(int value) constructor constructs an Integer object using the int value.

• The intValue() method returns an int that is the value of the Integer object.

• The Integer.MAX_VALUE constant is the largest possible int in Java.

• The Integer.MIN_VALUE constant is the smallest possible int in Java.

• The Double(double value) constructor constructs a Double object using the double value.

• The doubleValue() method returns a double value that is the value of the Double object.

Image Review Questions

Basic Level

1. The relationship between a class and an object can be described as:

(A) The terms class and object mean the same thing.

(B) A class is a program, while an object is data.

(C) A class is the blueprint for an object and objects are instantiated from it.

(D) An object is the blueprint for a class and classes are instantiated from it.

(E) A class can be written by anyone, but Java provides all objects.

2. Consider the following code segment.

Image

What is printed as a result of executing the code segment?

(A) HomeHello

(B) HelloHello

(C) WelcomeHello

(D) Welcome Hello

(E) Home Hello

3. What is printed as a result of executing the following statement?

Image

(A) 7878Hello7878

(B) 7815Hello7815

(C) 30Hello30

(D) 30Hello7815

(E) 7815Hello30

4. Consider the following code segment.

Image

What is printed as a result of executing the code segment?

(A) p0

(B) r9

(C) r10

(D) ra9

(E) ra10

5. Consider the following code segment.

Image

Which of these could be the result of executing the code segment?

Image

6. Which of the following returns the last character of the string str?

Image

7. Which statement assigns a random integer from 13 to 27 inclusive to the variable rand?

Image

8. After executing the code segment, what are the possible values of the variable var?

int var = (int) Math.random() * 1 + 10;

(A) All integers from 1 to 10

(B) All real numbers from 1 to 10 (not including 10)

(C) 10 and 11

(D) 10

(E) No value. Compile-time error.

9. Which of the following statements generates a random integer between -23 and 8 (inclusive)?

(A) int rand = (int)(Math.random() * 32 - 23);

(B) int rand = (int)(Math.random() * 32 + 8);

(C) int rand = (int)(Math.random() * 31 - 8);

(D) int rand = (int)(Math.random() * 31 - 23);

(E) int rand = (int)(Math.random() * 15 + 23);

10. Consider the following code segment.

Image

What is printed as a result of executing the code segment?

(A) 30000

(B) 31415

(C) 31416

(D) 31415.9265359

(E) Nothing will print. The type conversion will cause an error.

Advanced Level

11. Consider the following code segment.

Image

What is printed as a result of executing the code segment?

(A) amxem

(B) amxema

(C) amxepma

(D) ampxepm

(E) The program will terminate with a StringIndexOutOfBoundsException.

12. Which print statement will produce the following output?

Image

13. Consider the following code segment.

Image

After executing the code segment, what are the possible values for the variable rand?

(A) 3, 4, 5, 6, 7

(B) 9, 16, 25, 36, 49

(C) 5, 6, 7

(D) 25, 36, 49

(E) 9

14. Consider the following code segment.

Image

After executing the code segment, what is the possible range of values for val3?

(A) All integers from 2 to 17

(B) All integers from 2 to 75

(C) All integers from 75 to 76

(D) All integers from 2 to 74

(E) All integers from 2 to 18

15. Assume double dnum has been correctly declared and initialized with a valid value. What is the correct way to find its absolute value, rounded to the nearest integer?

Image

16. Which of these expressions correctly computes the positive root of a quadratic equation assuming coefficients a, b, c have been correctly declared and initialized with valid values? Remember, the equation is:

Image

Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

1. The answer is C.

• A class is a blueprint for constructing objects of the type described by the class definition.

2. The answer is A.

• When two strings are concatenated (added together), the second one is placed right after the first one (do not add a space).

Image

3. The answer is D.

• This question requires that you understand the two uses of the + symbol.

• First, execute what is in the parentheses. Now we have:

Image

• Now do the addition left to right. That’s easy until we hit the string:

Image

• When you add a number and a string in any order, Java turns the number into a string and then concatenates the string:

Image

• Now every operation we do will have a string and a number, so they all become string concatenations, not number additions.

Image

4. The answer is B.

• The indexOf method returns the index location of the parameter.

• The letter "a" has index 9 in "presto chango" (remember to start counting at 0).

• The substring will start at index 9 and stop before index 10, meaning it will return only the letter at index 9 in "abracadabra".

• Once again, start counting at 0. Index 9 of "abracadabra" is "r".

• Concatenate that with i which equals 9. Print "r9".

5. The answer is C.

• CompareTo takes the calling string and compares it to the parameter string. If the calling string comes before the parameter string, it returns a negative number. If it comes after the parameter string, it returns a positive number. If they are equal, it returns 0.

• The first compareTo is "avocado".compareTo("banana") so it returns -1.

• The second compareTo switches the order to "banana".compareTo("avocado") so it returns 1.

• Note that although we often only care about whether the answer is positive or negative, the actual number returned has meaning. Because "a" and "b" are one letter apart, 1 (or -1) is returned. If the example had been "avocado" and "cucumber", 2 (or -2) would have been returned.

6. The answer is D.

• Let’s take the word "cat" as an example. It has a length of 3, but the indices of its characters are 0, 1, 2, so the last character is at length - 1.

• We need to start our substring at str.length() - 1. We could say:

Image

but since we want the string all the way to the end we can use the single parameter version of substring.

7. The answer is C.

• The basic form for generating a random int between high and low is:

Image

• Our "high" is 27, and our "low" is 13, so the answer is C.

• Be sure to place the parentheses correctly. They can go after the multiplication or after the addition, but not after the Math.random().

8. The answer is D.

• This problem doesn’t have the necessary parentheses discussed in the explanation for problem 7.

• As a result, the (int) cast will cast only the value of Math.random(). Since Math.random() returns a value between 0 and 1 (including 0, not including 1), truncating will always give a result of 0.

• Multiplying by 1 still gives us 0, and adding 10 gives us 10.

9. The answer is A.

• This problem is similar to problem 7.

• Fill in (high — low + 1) = (8 — (-23)) + 1 = 32 and low = -23 and the answer becomes (int)(Math.random() * 32 - 23).

• Notice that this time the parentheses were placed around the whole expression, not just the multiplication.

10. The answer is B.

Image

11. The answer is B.

• ex1.substring(1, ex1.indexOf("p")) starts at the character at index 1 (remember we start counting at 0) and ends before the index of the letter "p". ex1 now equals "xam".

• Let’s take this one substring at a time. At the beginning of the statement, ex2 = "elpmaxe".

• ex2.substring(3, ex1.length()) The length of ex1 is 3, so this substring starts at the character at index 3 and ends before the character at index 3. It stops before it has a chance to begin and returns the empty string. Adding that to the current value of ex2 does not change ex2 at all.

• ex2.substring(3, ex2.length()) starts at the character at index 3 and goes to the end of the string, so that’s "maxe".

• Add that to the current value of ex2 and we have "elpmaxemaxe".

• We are going to take two substrings and assign them to ex3.

• The first one isn’t too bad. ex1 = "xam", so ex1.substring(1) = "am". Remember that if substring only has 1 parameter, we start there and go to the end of the string.

• The second substring has two parameters. Let’s start by figuring out what the parameters to the substring are equal to.

• Remember ex2 = "elpmaxemaxe" so indexOf("x") is 5.

• The second parameter is ex2.length() - 2. The length of ex2 = 11, subtract 2 and the second parameter = 9.

• Now we can take the substring from 5 to 9, or from the first "x" to just before the second "x", which gives us "xema".

• Add the two substrings together: "amxema".

12. The answer is A.

• Let’s take this piece by piece. A forward slash "/" does not require an escape sequence, but a backslash needs to be doubled since "\" is a special character. Our print sequence needs to start: /\\

• The next interesting thing that happens is the tab before "time". The escape sequence for tab is "\t". Our print sequence is now: /\\what\ttime (Don’t be confused by the double t. One belongs to "\t" and the other belongs to "time".)

• Now we need to go to the next line. The newline escape sequence is "\n"

• We also need escape sequences for the quote symbols, so now our print sequence is: /\\what\ttime\n\"is it\"

• Add the last few slashes, remembering to double the "\" and we’ve got our final result. /\\what\ttime\n\"is it?\"//\\\\

13. The answer is B.

• This problem is like problem 7 only backwards. If (high — low + 1) = 5 and low = 3, then high = 7. The first line gives us integers from 3 to 7 inclusive.

• The second line squares all those numbers, giving us: 9, 16, 25, 36, 49.

14. The answer is E.

• Taking it line by line, val1 = 10, val2 = 7 so:

Image

• The next statement becomes:

Image

• We know low = 2 and (high — low + 1) = 17, so high = 18.

• val3 will contain integers from 2 to 18 inclusive.

15. The answer is C.

• The easiest way to solve this is to plug in examples. We need to make sure we test both positive and negative numbers, so let’s use 2.9 and -2.9. The answer we are looking for in both cases is 3.

• Choice A:

(int) Math.abs(2.9 - 0.5) = (int) Math.abs(2.4) = (int) 2.4 = 2

NO (but interestingly, this works for -2.9).

(int) Math.abs(2.9 + 0.5) = (int) Math.abs(3.4) = (int) 3.4 = 3

• Choice B:

YES, but does it work in the negative case?

(int) Math.abs(-2.9 + 0.5)= (int) Math.abs(-2.4) = (int) 2.4 = 2

NO, keep looking.

• Choice C:

(int)(Math.abs(2.9) + 0.5) = (int)(2.9 + 0.5) = (int) 3.4 = 3

YES, but does it work in the negative case?

int)(Math.abs(-2.9) + 0.5) = (int)(2.9 + 0.5) = (int) 3.4 = 3

YES, found it!

16. The answer is E.

• Options A and B are incorrect. They use the math notation 4ac and 2a for multiplication instead of 4 * a * c and 2 * a.

• Solution C is incorrect. This option divides by 2 and then multiplies that entire answer by a, which is not what we want. 2 * a needs to be in parentheses.

• Look carefully at D and E. What’s the difference? The only difference is the placement of the closing parenthesis, either after the (b, 2) or after the 4 * a * c. Which should it be? The square root should include both the Math(b, 2) and the 4 * a * c, so the answer is E.