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
.
Key Ideas
Java is an object-oriented programming language whose foundation is built on classes and objects.
A class describes the characteristics of any object that is created from it.
An object is a virtual entity that is created using a class as a blueprint.
Objects are created to store and manipulate information in your program.
A method is an action that an object can perform.
The keyword new
is used to create an object.
A reference variable stores the address of the object, not the object itself.
The Java API contains a library of thousands of classes.
Strings are used to store letters, words, and other special characters.
To concatenate strings means to join them together.
The String
class has many methods that are useful for manipulating String
objects.
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 intent of an object-oriented programming language is to provide a framework that allows a programmer to manipulate information after storing it in an object. The following paragraphs describe the relationship between many different vocabulary terms that are necessary to understand Java as an object-oriented programming language. The terms are so related that I wanted to describe them all together rather than in separate pieces.
Warning: Proceed with Caution
The next set of paragraphs includes many new terms. You may want to reread this section many times. If you expect to earn a 5 on the exam, you must master everything that follows. Challenge yourself to learn it so well that you can explain this entire chapter to someone else.
Java classes represent things that are nouns (people, places, or things). A class is the blueprint for constructing all objects that come from it. The attributes of the objects from the class are represented using instance variables. The values of all of the instance variables determine the state of the object. The state of an object changes whenever any of the values of the instance variables change. Methods are the virtual actions that the objects can perform. They may either return an answer or provide a service.
Objects are created using the class that holds the blueprint of the object. The class contains a piece of code called a constructor, which tells the computer how to build (construct) an object from that class. The keyword new is used whenever the programmer wants to create an object from a class. When new
is followed by the name of a constructor of a class, a new object is created. The action of constructing an object is also referred to as instantiating an object and the object is referred to as an instance of the class. In addition to creating the new object, a reference to the object is created. The object reference variable holds the memory address of the newly created object and is used to call methods that are contained in the object’s class.
Writing classes will be discussed thoroughly in Unit 5. This unit introduces the use of the String
, Math
, Integer
, and Double
classes that are available.
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.
String
VariableHow 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? What we need is 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.
Examples
Make some String
variables and assign them values:
String
ObjectString
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.
Example 1
Make a String
object and assign it a value:
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.
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.
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.
String
ObjectThis 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.
String
ConcatenationNow 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 +:
Example 2
Concatenate two strings using +=:
Example 3
Concatenate a number and a string using +:
Example 4
Incorrectly concatenate a string and the sum of two numbers using +. Notice that the sum is not computed.
Example 5
Correctly concatenate a string and the sum of two numbers using +:
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.
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.
String
ObjectsEveryone 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.
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.
String
Methodsequals
MethodThe 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:
Example 2
Determine if two strings are not equal:
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!
compareTo
MethodThe 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.
The compareTo
Method
The compareTo
method returns an integer that describes how the two strings compare.
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:
Example 2
The answer is negative when the first string comes before the second string (lexicographically):
Example 3
The answer is positive when the first string comes after the second string (lexicographically):
Example 4
Uppercase letters come before their lowercase counterparts. "Hello" comes before "hello" when comparing them using lexicographical order:
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).
length
MethodThe length method returns the number of characters in the specified string (including spaces).
Example 1
Find the length of a string:
Example 2
Find the length of a string that is empty, but not null (it has "" as its value):
Example 3
Attempt to find the length of a string that is null:
The NullPointerException
Attempting to use a method on a string that has not been initialized will result in a runtime 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?
indexOf
MethodTo 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. 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:
Example 2
Find the index of a character in a string when it appears more than once:
Example 3
Attempt to find the index when the character is not in the string:
Example 4
Find the index of a string inside a string:
substring
MethodThe 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.
Example 1
Extract every character starting at a specified index from a string:
Example 2
Extract one character from a string:
Example 3
Extract two characters from a string:
Example 4
Extract the word “force” from a string:
Example 5
Use numbers that don’t make any sense:
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:
Helpful Hint for the substring
Method
To find out how many characters to extract, subtract the first number from the second number.
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 "".
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.
String
Is ImmutableString
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:
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 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 exam but is useful for displaying output in columns).
Math
ClassThe 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 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
Class MethodsThe 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).
Math.random()
to Generate a Random IntegerThe 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.
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.
double
Values Are EqualIt 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.
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.
Integer
ClassThe 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 a later unit. 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 an 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.
Integer
ClassMAX_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 value of the largest integer:
Example 2
Obtain the value of the smallest integer:
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.
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.
Double
ClassThe 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.
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
Example 2
Integer
and Double
ClassesYou 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.
• A class contains the blueprint, or design, from which individual objects are created.
• Classes tend to represent things that are nouns.
• The methods of a class describe the actions that an object can perform.
• A method declaration describes pertinent information for the method such as the access modifier, the return type, the name of the method, and the parameter list.
• An object from a class is a virtual realization of the class.
• Objects store their own data.
• An instance of a class is the same thing as an object of a class.
• The word “instantiate” is used to describe the action of creating an object. Instantiating is the act of constructing a new object.
• The keyword new is used whenever you want to create an object.
• An object reference variable stores the memory address of where the actual object is stored. It can only reference one object.
• The reference variable does not store the object itself.
• Two reference variables are equal only if they refer to the exact same object.
• The word null means no value.
• A null reference describes a reference variable that does not contain an address of any object.
• You can create as many objects as you want from one class. Each is a different object that is stored in a different location in the computer’s memory.
• 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.
• Only 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.
• 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 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.
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.
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?
(A) 7878Hello7878
(B) 7815Hello7815
(C) 30Hello30
(D) 30Hello7815
(E) 7815Hello30
4. Consider the following code segment.
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.
Which of these could be the result of executing the code segment?
(A) 0 0
(B) -1 -1
(C) -1 1
(D) 1 -1
(E) 1 1
6. Which of the following returns the last character of the string str
?
(A) str.substring(0);
(B) str.substring(0, str.length());
(C) str.substring(length(str));
(D) str.substring(str.length() - 1);
(E) str.substring(str.length());
7. 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;
8. 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.
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.
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.
11. Consider the following code segment.
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?
(A) System.out.print("/\\what\ttime\n\"is it?\"//\\\\");
(B) System.out.print("//\\what\ttime\n\"is it?\"////\\\\");
(C) System.out.print("/\\what\time\n\"is it?\"//\\\\");
(D) System.out.print("/\\what\ttime\n"is it?"//\\\\");
(E) System.out.print("//\\what\time + \"is it?\"////\\\\");
13. 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
14. 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
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?
(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;
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:
(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)
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).
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:
• Now do the addition left to right. That’s easy until we hit the string:
• When you add a number and a string in any order, Java turns the number into a string and then concatenates the string:
• Now every operation we do will have a string and a number, so they all become string concatenations, not number additions.
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:
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:
• 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 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 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 1.
• Fill in (high − low + 1) = (8 − (-23)) + 1 = 32 and low = -23 and the answer becomes
• Notice that this time the parentheses were placed around the whole expression, not just the multiplication.
10. The answer is B.
•
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 is 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:
• Add the last few slashes, remembering to double the "\" and we’ve got our final result.
13. The answer is B.
• This problem is like problem 1 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:
• 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.
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.
• 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!
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.