5 Steps to a 5 AP Computer Science A 2017 (2016)

STEP 4

Review the Knowledge You Need to Score High

CONCEPT 4

The Math , Integer , and Double Classes

IN THIS CONCEPT

Summary: 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 concept provides practice working with three of those classes: the Math, Integer, and Double classes.

Key Ideas

   The Java API contains a library of thousands of classes.

   The Math class contains methods for performing mathematical calculations.

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

   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. 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 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 (RNG) to help programmers solve problems that require random events.

Compared to the other classes in the AP Computer Science 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.

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 exam only requires you to know a small handful of them.

Example 1

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

Example 2

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

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.

Example 4

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

Example 5

Demonstrate how to use the random method.

Example 6

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

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

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

General Form for Generating a Random Integer Between Two Positive Numbers

Example 1

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

Example 2

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

Example 3

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

Example 4

Simulate flipping a coin a million times:

The Correct Way to Compare If Two double Values Are Equal

It is never a good idea to compare if two double values are equal using the == sign. Calculations with a double can contain rounding errors. You may have seen this when printing the result of some kind of division and you get something like this as a result: 7.00000000002 .

The correct way to compare if two doubles are equal is to use a tolerance . If the difference between the two numbers is less than or equal to the tolerance, then we say that the two numbers are close enough to be considered equal. Since we might not know which of the two numbers is bigger, subtract the two numbers and find the absolute value of the result. This way, the difference between the two numbers is always positive.

General Form for Comparing If Two double Values Are Equal

Example

Determine if two doubles are “equal” using a very small tolerance:

Avoid Using the == Sign When Comparing double Values

Rounding errors cause problems when trying to determine if two double values are equal. Never use == to compare if two doubles are equal. Instead, determine if the difference between the two doubles is close enough for the two doubles to be considered equal.

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 the Data Structures concept. Java can convert an Integer object back into an int using the intValue method.

Example 1

Create an Integer object from an int.

Example 2

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

Example 3

Attempt to create an Integer object using a double value.

Example 4

Attempt to create an Integer object without using a value.

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.

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 value of the largest Integer:

Example 2

Obtain the value of the smallest Integer:

MAX_VALUE and MIN_VALUE Are Constants

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.

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

Example 2

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

Example 3

Attempt to create a Double object without using a value.

Summary of the Integer and Double Classes

 Rapid Review

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.
  • Avoid comparing double values using the== sign. Instead, use a tolerance.

Integer and Double Classes

  • The Integer and Double classes are called wrapper classes, since theywrap 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.

 Review Questions

Basic Level

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

(A) int rand = (int)(Math.random() * 13) + 27;

(B) int rand = (int)(Math.random() * 27) + 13;

(C) int rand = (int)(Math.random() * 15) + 13;

(D) int rand = (int)(Math.random() * 14) + 27;

(E) int rand = (int)(Math.random() * 14) + 13;

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

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

   3 .    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);

   4 .    Consider the following code segment.

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.

   5 .    Consider the following code segment.

Which of the following should replace /* missing condition */ to ensure that a + b will not be too large to be held correctly in result?

(A) a + b < Integer.MAX_VALUE

(B) a + b <= Integer.MAX_VALUE

(C) Integer.MIN_VALUE + a <= b

(D) Integer.MAX_VALUE – a <= b

(E) Integer.MAX_VALUE – a >= b

Advanced Level

   6 .    Consider the following code segment.

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

(A) 20.0

(B) 6.0

(C) 19.0

(D) 9.0

(E) -40.0

   7 .    Consider the following code segment.

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

   8 .    Consider the following code segment.

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

   9 .    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?

(A) (int) Math.abs(dnum - 0.5);

(B) (int) Math.abs(dnum + 0.5);

(C) (int) (Math.abs(dnum) + 0.5);

(D) Math.abs((int)dnum - 0.5);

(E) Math.abs((int)dnum) - 0.5;

10 .    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:

(A) (-b + Math.sqrt (Math.pow(b, 2)) - 4ac) / 2a

(B) (-b + Math.sqrt (Math.pow(b, 2) - 4ac)) / 2a

(C) (-b + Math.sqrt (Math.pow(b, 2) - 4 * a * c)) / 2 * a

(D) (-b + Math.sqrt (Math.pow(b, 2)) - 4 * a * c) / (2 * a)

(E) (-b + Math.sqrt (Math.pow(b, 2) - 4 * a * c)) / (2 * a)

 Answers and Explanations

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

   1 .    The answer is C.

  • The basic form for generating a random int between high and low is:
  • 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().

   2 .    The answer is D.

  • This problem doesn’t have the necessary parentheses discussed in the explanation for problem 1.
  • 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 willalways give a result of 0.
  • Multiplying by 1 still gives us 0, and adding 10 gives us 10.

   3 .    The answer is A.

  • This problem is similar to problem 1.
  • 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.

   4 .    The answer is B.

   5 .    The answer is E.

  • Integer.MAX_VALUE is a constant that represents the greatest value that can be stored in an int. In this problem, we need to make sure that a + b is not greater than that value.
  • Solution b seems like the logical way to do this, but if a + b is too big to fit in an int, then we can’t successfully add them together to test if they are too big. a + b will overflow.
  • We need to do some basic algebra and subtract a from both sides giving us:
  • The left and right sides of the expression have been switched, so we need to flip the inequality. Flipping the < gives us >=.

   6 .    The answer is D.

  • When we enter the loop, tabulate = 100 and repeat = 1
  • tabulate = 100 – Math.pow(1, 2) = 99; increment repeat to 2
  • 99 > 20 so we enter the loop again
  • tabulate = 99 – Math.pow(2, 2) = 95; increment repeat to 3
  • 95 > 20
  • tabulate = 95 – Math.pow(3, 2) = 86; increment repeat to 4
  • 86 > 20
  • tabulate = 86 – Math.pow(4, 2) = 70; increment repeat to 5
  • 70 > 20
  • tabulate = 70 – Math.pow(5, 2) = 45; increment repeat to 6
  • 45 > 20
  • tabulate = 45 – Math.pow(6, 2) = 9; increment repeat to 7
  • 9 < 20 so we exit the loop and print 9

   7 .    The answer is B.

  • This problem is like problem 1 only backward. 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.

   8 .    The answer is E.

  • Taking it line by line, val1 = 10, val2 = 7 so:
  • The next statement becomes:
  • We know low = 2 and (high – low + 1) = 17, so high = 18.
  • val3 will contain integers from 2 to 18 inclusive.

   9 .    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.
  • solution a:

NO (but interestingly, this works for -2.9)

  • solution b:

YES, but does it work in the negative case?

NO, keep looking

  • solution c:

YES, but does it work in the negative case?

YES, Found it!

10 .    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 close 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.