4 Using Classes and Objects

AP Computer Science A Prep, 2024 - Rob Franek 2023

4 Using Classes and Objects
Part V: Content Review for the AP Computer Science A Exam

An object is an entity or data type we create in Java. To do so, we use a class built specifically for this purpose. Classes contain instance fields (data) belonging to the object and methods to manipulate that data. We will review this in more detail in a later chapter. For now, let’s dive into the Math class.

THE Math CLASS

Part of the AP Computer Science Java subset is the Math class. The Math class stores common numbers used in mathematical calculations (Math.PI and Math.E) and methods to perform mathematical functions. The methods of the Math class are static. There will be more on static methods later, but, for now, understand that to call the methods of the Math class, the programmer must type Math. before the name of the method. The Math class contains many methods, but only a few are part of the AP Computer Science Java Subset. Unlike most classes that we use to create an object, we normally do not create Math objects.

Common Math Methods

Method

Return

Math.abs(x) //x is an int

An int equal to the absolute value of x

Math.abs(x) //x is a double

A double equal to the absolute value of x

Math.pow(base, exponent)

A double equal to the base raised to the exponent

Math.sqrt(x)

A double equal to the square root of x

Math.random()

A random double in the range (0, 1)

Understanding operator precedence is essential for multiple-choice questions on the AP Exam and, perhaps more importantly, for showing off on social media when those “solve this problem” memes pop up and everyone argues over the right answer.

Image

1.A math teacher is writing a program that will correctly calculate the area of a circle. Recall that the area of a circle is pi times the radius squared (πr2). Assuming Math.PI returns an accurate decimal approximation of pi, which of the following statements WILL NOT calculate an accurate area of a circle with radius 22 ?

(A) r*r*Math.PI; // r is the int 22

(B) r*r*Math.PI; // r is the double 22.0

(C) (double)r*r*Math.PI; // r is the int 22

(D) (double)(r*r)*Math.PI; // r is the int 22

(E) All of the above choices will calculate an accurate area.

Here’s How to Crack It

Choice (A) will use integer multiplication for r*r but will then convert everything to doubles when it multiplies by Math.PI, a double. Choice (B) is obviously correct. Choices (C) and (D) will cast some of the values to double, but as stated above, this will not impact the result in an undesired way. Therefore, the answer is (E).

It is important to note that Math.PI is a static variable of the Math class. Therefore, it can be called only if the class has been imported by putting the following statement at the top of the class coding:

import java.lang.Math;

Image

THE String CLASS

String is an object data type, meaning it has a class with many methods describing the behavior of the object. Below is a table of common methods utilized in the String class.

Common String Methods

Method

Return

length()

An int equal to the length of the string

substring(int beginIndex)

A String that is a substring of this string starting at the character at the beginIndex, through to the end of the string

substring(int beginIndex, int endIndex)

A String that is a substring of this string starting at the character at the beginIndex, up to but not including the character at the endIndex

equals(Object anObject)

A boolean reflecting the status after comparing this string to the specified object.

String str1 = “frog”;

String str2 = “frog”;

boolean isEqual = str1.equals(str2);

// returns true

compareTo(String anotherString)

An int reflecting the status after comparing two strings lexicographically.

-Returns an integer < 0 if string1 comes before string2

-Returns an integer 0 if string1 is the same as string2

-Returns an integer > 0 if string1 comes after string2

String str1 = “cat”;

String str2 = “dog”;

str1.compareTo(str2); // returns —1

str1.compareTo(“cat”); // returns 0

str2.compareTo(str1); // returns 1

While the char data type is not directly tested, it can be useful to understand that the data in the String class is an array of characters. Therefore, strings have many analogous tools to arrays. Consider the coding below.

String sample = “Sample”

System.out.print(sample.length());

The coding will output the number 6. The length() method of the String class will output the number of characters in the string, much as length is the number of elements in an array. Furthermore, the strings use indices in much the same way. The index of the first character in a string is 0, and the index of the last character is length() — 1.

Indices are useful when dealing with substrings, which are portions of strings. The String class has two substring methods. One has two integer parameters

String substring (int from, int to)

This method returns, as a String object, the substring starting at index from and ending at index to — 1. Note that the character at index to will NOT be included in the substring. Therefore, using the String sample from above, the command

System.out.print(sample.substring(1, 4));

will display

amp

Note that

System.out.println(sample.substring(1, 7));

will result in an IndexOutOfBoundsException since the index 7 — 1 = 6 is outside the bounds of the string.

The other substring method works similarly but uses only one parameter, to indicate the starting index. The resulting substring will continue to the end of the string. Therefore, the command

System.out.print(sample.substring(1));

will display

ample

This process can be reversed using the indexOf method of the String class. This method takes a substring as a parameter and returns the first occurrence of that substring. For example,

sample.indexOf(“amp”)

will return 1, as the substring first occurs at index 1. However,

sample.indexOf(“amb”)

will return —1, as this substring does not occur.

The String class is an immutable class. In other words, it has no mutator methods. Thus, if you wish to change the contents of a String object, the new contents must be reassigned to the variable.

Let’s look at the following code:

String sample = “Sample”;

sample.substring(1, 4);

While this code will not cause an error, “amp” is not stored, making it rather useless. Instead, we assign the String obtained from the substring command back into the original variable so that sample will now contain the literal “amp”.

sample = sample.substring(1, 4);

When using methods of any class, you should remember that the parameters used to call the method must match the data types of the arguments of the defined method.

For example, substring is defined as:

substring(int beginIndex, int endIndex)

Therefore, the following code would cause a compiler error because the parameters are expected to be int data types.

sample = sample.substring(1.0, 4.0);

Image

2.Consider the following code segment:

String s = “This is the beginning”;

String t = s.substring(5);

int n = t.indexOf(“the”);

Which of the following will be the value of n ?

(A) —1

(B) 3

(C) 7

(D) 9

(E) n will have no value because of a run-time error.

Here’s How to Crack It

The question asks for the value of n, which is IndexOf “the” in String t, which is a substring of s. First determine t, which is the substring beginning at the index 5 of s. Remember to start with 0 and to count the spaces as characters. Index 0 is ’T’, index 1 is ’h’, index 2 is ’i’, index 3 is ’s’, and index 4 is the space. Therefore, index 5 is the ’i’ at the beginning of “is.” There is only one parameter in the call of the substring method, so continue to the end of String s to get that String t is assigned “is the beginning.” Now, find the index of “the.” Since index 0 is ’i’, index 1 is ’s’, and index 2 is the space, the substring “the” begins at index 3. Therefore, the value of n is 3, which is (B).

Image

Image

3.Given the following code, what line will cause a compiler error?

1 String word = “Sunday Funday Celebration 1.0”;

2 word.substring(7);

3 word.substring(3, 6);

4 word.indexOf(“day”);

5 word.indexOf(1.0);

6 word.compareTo(“day”);

(A) line 2

(B) line 3

(C) line 4

(D) line 5

(E) line 6

Here’s How to Crack It

When looking for a compiler error, syntax is usually the culprit. At first glance, it appears all the method names have been spelled correctly, so next move on to the number and data types of the parameters, ensuring they match the expected arguments for each method. The substring method can have 1 or 2 arguments, as long as they represent integers that are valid indices of the string in question. Thus, lines 2 and 3 are fine. The compareTo method compares the string invoking the method to some other string (or String variable) in the parentheses, so line 6 is fine. The indexOf method looks for a specific string. Line 4 uses a string but line 5 attempts to use a double data type. Thus, line 5 (choice D) will cause an error.

Image

KEY TERMS

object

class

immutable

CHAPTER 4 REVIEW DRILL

Answers to the review questions can be found in Chapter 13.

1.Given the following code, which of the following would cause a run-time error?

String s1 = “pizza”;

(A) String s2 = s1.substring(0, 2);

(B) String s2 = s1.substring(1, 3);

(C) String s2 = s1.substring(3, 3);

(D) String s2 = s1.substring(2, 3);

(E) String s2 = s1.substring(4, 6);

2.Given the following code, what is the final value stored in s3?

String s1 = “kangaroo”;

String s3 = s1.substring(1, 2);

(A) “k”

(B) “ka”

(C) “a”

(D) “an”

(E) “kn”

3.Given the following code, what is the final value stored in s4?

String s1 = “tango”;

String s4 = s1.substring(s1.length() - 2);

(A) “g”

(B) “go”

(C) “o”

(D) “og”

(E) A compiler error will occur.

4.Given that “A” comes before “a” in the dictionary and the following variables have been defined and initialized, which is true?

String str1 = “january”;

String str2 = “June”;

String str3 = “July”;

(A) str1.compareTo(str3) < 0

(B) str3.compareTo(str2) > 0

(C) str1.compareTo(str2) < 0

(D) str1.compareTo(str2) > 0

(E) str2.compareTo(str3) < 0

5.Given the following code, what is the final value stored in p?

1 String word = “boottool”;

2 int p = word.indexOf(“oo”);

3 word.substring(p + 2);

4 p = word.indexOf(“oo”);

(A) 0

(B) 1

(C) 2

(D) 5

(E) 6

Summary

o When invoking a method, pay close attention to the number and type of parameters the method is expecting, as well as what is being returned.

o Immutable objects cannot be modified. The variable holding the object can only be assigned a new value.

o Indices of characters within a string start at 0 and extend to length() — 1.