Professional Documents
Culture Documents
2. The terms “literal string” and “string literal” have different meanings in Java programming.
a. True
b. False
ANSWER: False
3. When you compare Strings with the == operator, you are comparing their values, not their memory addresses.
a. True
b. False
ANSWER: False
4. When you must determine whether a String is empty, it is more efficient to compare its length to 0 than it is to use
the equals () method.
a. True
b. False
ANSWER: True
5. If you try to use an index that is greater than 0 or less than the index of the last position in the StringBuilder
object, you cause an error known as an exception and your program terminates.
a. True
b. False
ANSWER: False
7. In a compareTo() method, programmers often do not need specific return values but want to determine if a value is
positive or negative.
a. True
b. False
ANSWER: True
10. The StringBuffer class is more efficient than the StringBuilder class because it can execute multiple threads
during program execution.
a. True
b. False
ANSWER: False
Multiple Choice
12. A ____ is a class for storing and manipulating changeable data that is composed of multiple characters.
a. Character b. String
c. StringVariable d. StringBuilder
ANSWER: d
13. The methods of the Character class that begin with ____ return a character that has been converted to the stated
format.
a. is b. to
c. for d. in
ANSWER: b
16. Strings and other objects that can’t be changed are known as ____.
a. string constants b. accessor methods
c. immutable d. garbage
ANSWER: c
17. When you declare a variable of a basic, primitive type, such as int x = 10;, the memory address where x is
Copyright Cengage Learning. Powered by Cognero. Page 2
Name: Class: Date:
18. The String class ____ method evaluates the contents of two String objects to determine if they are equivalent.
a. equals() b. toString()
c. charAt() d. replace()
ANSWER: a
19. A(n) ____ comparison is based on the integer Unicode values of the characters.
a. integer b. symbol
c. lexicographical d. character
ANSWER: c
20. The method header of the equals() method within the String class is ____.
a. public boolean equals(Strings)
b. private boolean equals(String s)
c. public boolean equals(String s)
d. public boolean equals(Character s)
ANSWER: c
21. When the String class ____ method is used to compare two Strings, it provides additional information to the user
in the form of an integer value.
a. toString() b. compareTo()
c. equals() d. equalsIgnoreCase()
ANSWER: b
23. The ____ method allows you to replace all occurrences of some character within a String.
a. substring() b. toString()
c. replaceCharacter() d. replace()
ANSWER: d
25. To convert a String to an integer, you use the ____ class, which is part of java.lang and is automatically imported
26. The ____ method takes a String argument and returns its double value.
a. parseString() b. parseInt()
c. parseDouble() d. returnDouble()
ANSWER: c
You can tell that parseInt() is a(n) ____ method because you use it with the class name and not with an object.
a. programmer-defined b. instance
c. static d. immutable
ANSWER: c
28. A StringBuilder object contains a memory block called a _____, which might or might not contain a string.
a. capacity b. buffer
c. reference d. thread
ANSWER: b
29. The creators of Java chose ____ characters as the “extra” length for a StringBuilder object.
a. 12 b. 16
c. 36 d. 48
ANSWER: b
30. The ____ method lets you add characters at a specific location within a StringBuilder object.
a. charAt() b. insert()
c. append() d. setCharAt()
ANSWER: b
31. To alter just one character in a StringBuilder, you can use the ____ method, which allows you to change a
character at a specified position within a StringBuilder object.
a. charAt() b. insert()
c. append() d. setCharAt()
ANSWER: d
Given the lines of code above, which of the following regionMatches() expressions will result in a value of true?
a. oneStr.regionMatches(8, twoStr, 8, b. oneStr.regionMatches(0, twoStr, 0,
3) 7)
c. oneStr.regionMatches(8, twoStr, 0, d. oneStr.regionMatches(0, twoStr, 8,
Copyright Cengage Learning. Powered by Cognero. Page 4
Name: Class: Date:
34. Which of the following correctly declares and initializes a String object?
a. new String = Hello b. String greeting == "Hello";
c. String greeting = "Hello"; d. String new = "Hello"
ANSWER: c
36. The ____ class contains standard methods for testing the values of characters.
a. char b. character
c. StringChar d. Character
ANSWER: d
37. The ____ method and the startsWith() method each take a String argument and return true or false if
a String object does or does not end or start with the specified argument, respectively.
a. beginsWith() b. strEnd()
c. endsWith() d. length()
ANSWER: b
38. The String class ____ method is similar to the equals() method. As its name implies, this method does not
consider case when determining if two Strings are equivalent.
a. equalsCase() b. equalsOmitCase()
c. equalsAllCase() d. equalsIgnoreCase()
ANSWER: a
40. The ____ method requires an integer argument that indicates the position of the character at that position, starting at 0.
a. charAt() b. setCharAt()
Copyright Cengage Learning. Powered by Cognero. Page 5
Name: Class: Date:
Matching
55. Takes two integer arguments: a start position and an end position
ANSWER: c
56. Describe how a string is a reference and how a string comparison is done.
ANSWER: As an object, a String variable name is not a simple data type—it is a reference; that is, a variable that holds
a memory address. Therefore, when you compare two Strings using the == operator, you are not comparing
their values, but their computer memory locations.
57.
In the above code, two strings are evaluated using the equivalency operator. Why can this be a problem, and what other
methods are offered by Java for working with characters and strings?
ANSWER: The problem stems from the fact that in Java, String is a class, and each created String is an object. As an
object, a String variable name is not a simple data type. It is a reference; that is, a variable that holds a
StringBuilder and StringBuffer - Classes for storing and manipulating changeable data composed
of multiple characters
58. Describe how a programmer would use the two types of Character class methods (those that begin with “is” and
those that begin with “to”) for testing the values of characters.
ANSWER: The methods that begin with “is”, such as isUpperCase(), return a Boolean value that can be used in
comparison statements; the methods that begin with “to”, such as toUpperCase(), return a character that
has been converted to the stated format.
59. Explain what is needed to declare a String variable and provide an example.
ANSWER: When you declare a String object, the String itself—that is, the series of characters contained in the
String—is distinct from the identifier you use to refer to it. You can create a String object by using the
keyword new and the String constructor, just as you would create an object of any other type. For example,
the following statement defines an object named aGreeting, declares it to be of type String, and assigns
an initial value of “Hello” to the String:
String aGreeting = new String("Hello");.
60. How is the String class equalsIgnoreCase() method like the equals() method and how would you use it?
Give an example.
ANSWER: The String class equalsIgnoreCase() method is similar to the equals() method. As its name
implies, this method ignores case when determining if two Strings are equivalent. Thus, if you declare a
String as String aName = "Carmen";, then aName.equals("caRMen") is false, but
aName.equalsIgnoreCase("caRMen") is true since the equalsIgnoreCase() method allows
you to test entered data without regard to capitalization. This method is useful when users type responses to
prompts in your programs. You cannot predict when a user might use the Shift key or the Caps Lock key
during data entry.
Using the above statements, what value will be returned by the equals() method? What will be the value of the
equalsIgnoreCase() method? Explain how the equalsIgnoreCase() method can be useful when users type
responses to prompts in programs.
ANSWER: The String class equalsIgnoreCase() method is similar to the equals() method. As its name
implies, this method ignores case when determining if two Strings are equivalent. Thus, if you declare a
String as String yourCounty = "perry", then yourCounty.equals("Perry")is false,
Copyright Cengage Learning. Powered by Cognero. Page 8
Name: Class: Date:
There is an important difference between empty Strings and null Strings. Explain the differences and why it is
important when making String comparisons.
ANSWER: The empty String example1 references a memory address where no characters are stored. The null
String example2 uses the Java keyword null so that example2 does not yet hold a memory address.
The unassigned String example3 is also a null String by default. A significant difference between
these declarations is that example1 can be used with the String methods, but example2 and example3
cannot. For example, assuming a String named anotherExample has been assigned a value, then the
comparison string1.equals(anotherExample) is valid, but
example2.equals(anotherExample) causes an error.
63. How can you use String methods to change the case of a string? Provide an example.
ANSWER:
The methods toUpperCase() and toLowerCase() convert any String to its uppercase or
lowercase equivalent. For example, if you declare a String as String aWord = "something";, then
the string “something” is created in memory and its address is assigned to aWord. The statement aWord =
aWord.toUpperCase(); creates “SOMETHING” in memory and assigns its address to aWord. Because
aWord now refers to “SOMETHING,” aWord = aWord.toLowerCase(); alters aWord to refer to
“something”.
Using the above statement, write the length() method that will return the length of the greeting String. Store
the length in an integer named greetingLength.
ANSWER: int greetingLength = greeting.length();
Using the above String, create the String method to convert the greeting String to all uppercase. Likewise,
create the String method to convert the greeting String to all lowercase.
ANSWER: To convert to uppercase:
greeting = greeting.toUpperCase();
To convert to lowercase:
greeting = greeting.toLowerCase();
Using the above statement, write the length() method that will return the length of the aName String. What value
will the length() method return when executed?
ANSWER: int len = aName.length();
Using the above code, what will be the value of the charAt() method once the code executes? Explain how the
charAt() method operates.
ANSWER: The charAt() method requires an integer argument that indicates the position of the character that the
method returns, starting with 0. In the above example, myCounty is a String that is examined by the
charAt() method. The value of myCounty.charAt(6) is “J”.
What value will be returned by the startsWith() method? Explain how the startsWith() method deals with case
sensitivity.
ANSWER: The startsWith() method takes a String argument and returns true or false if the String object
does or does not end or start with the specified argument. In this example, String yourCounty =
"Clark" and yourCounty.startsWith("Cla") is true. These methods are case sensitive, so if
String yourCounty had been "clark", the value returned would have been false.
70. What is the purpose of the substring() method and how do you use it?
ANSWER: You can extract part of a String with the substring() method, and use it alone or concatenate it with
another String. The substring() method takes two integer arguments—a start position and an end
position—that are both based on the fact that a String’s first position is position zero. The length of the
extracted substring is the difference between the second integer and the first integer; if you write the method
without a second integer, the substring extends to the end of the original string.
}
}
Accepting a String from a user is common practice. Using the above code, write the statements to accept a String
response from a user. Prompt the user with “Enter your name”. Then use the charAt() method to extract the first
character of the String.
Copyright Cengage Learning. Powered by Cognero. Page 10
Name: Class: Date:
Using the above code, what will be the Boolean value after execution of the regionMatches statement? Explain
how the Strings are compared using the regionMatches() method.
ANSWER: The regionMatches() method can be used to test whether two String regions are the same. One
version of the regionMatches() method takes four arguments—the position at which to start in the
calling String, the other String being compared, the position to start in the other String, and the length of the
comparison.
The regionMatches() expression is true. The substring of firstString that starts at position 5 and
continues for five characters is “Maple”; the substring of secondString that starts at position 7 and
continues for five characters is also “Maple”.
74. How can you change the length of a String in a StringBuilder object?
ANSWER: You can change the length of a string in a StringBuilder object with the setLength() method. The
length of a StringBuilder object equals the number of characters in the String contained in the
StringBuilder. When you increase a StringBuilder object’s length to be longer than the String it
holds, the extra characters contain ‘\u0000’. If you use the setLength() method to specify a length shorter
than its String, the string is truncated.
75. Why would you use the append() method? Provide an example.
ANSWER: The append() method lets you add characters to the end of a StringBuilder object. For example, the
following two statements together declare phrase to hold “Happy” and alter the phrase to hold “Happy
birthday”:
StringBuilder phrase = new StringBuilder("Happy");
phrase.append(" birthday");
76. Strings and other objects that can't be changed are said to be immutable. What does this mean and how does it
relate to values held in memory addresses?
ANSWER: In Java, the value of a String is fixed after the String is created; Strings are immutable, or unchangeable. When
you write someString = "Hello"; and follow it with someString = "Goodbye";, you have neither changed the
contents of computer memory at the address represented by someString nor eliminated the characters
“Hello”. Instead, you have stored “Goodbye” at a new computer memory location and stored
the new address in the someString variable.
Using the above code and the charAt() method, what value will be assigned to the variable initial?
Copyright Cengage Learning. Powered by Cognero. Page 11
Name: Class: Date:
Using the above code and insert() method, describe how the phrase will appear after the code executes. How does the
insert() method work?
ANSWER: The String will appear as “Welcome home Joe”. The insert() method lets you add characters at a
specific location within a StringBuilder object. The first character in the StringBuilder object
occupies position zero.
Use the append() method to add the characters “home” to the end of the StringBuilder object created above.
ANSWER: greeting.append(" home");
(Be sure that the String in double quotes has a blank space at the start. Otherwise, the Strings
"Welcome" and "home" will be appended without a blank space.)
Using the above StringBuilder, create a setCharAt() method that will change the “1” to a “2” in the String
"Day 1". Explain how the setCharAt() method operates.
ANSWER: greeting.setCharAt(4, '2');
To alter just one character in a StringBuilder, you can use the setCharAt() method, which allows
you to change a character at a specified position within a StringBuilder object. This method requires two
arguments: an integer position and a character. In the phrase “Day 1”, the greeting.setCharAt(4,
'2'); changes the value 1 to 2.
81. Give a code example of using the equivalence operator ("==") to compare the addresses of two strings where the
comparison will result in the value true. The example should produce output indicating the strings have the same value.
ANSWER: string stringA="Hello";
string StringB="Hello";
if(stringA==stringB)
System.out.println("stringA has the same address value as stringB");
82. What happens when you increase a StringBuilder object's length to be longer than the string it holds? What
happens if you set the length of a string to be shorter than the string it contains?
ANSWER: When you increase a StringBuilder object’s length to be longer than the String it holds, the extra
characters contain ‘\u0000’. If you use the
setLength() method to specify a length shorter than its String, the string is truncated.
Language: English
CHEMISTRY,
Mechanics, Acoustics
AND
PYROTECHNICS.
ALSO CONTAINING
New York:
FRANK TOUSEY, Publisher,
24 Union Square.
Entered according to Act of Congress, in the year 1900, by
FRANK TOUSEY,
in the Office of the Librarian of Congress at Washington, D. C.
How to Become a Scientist.
Chemistry, optics, pneumatics, mechanics, and mathematics, all
contribute their share towards furnishing recreation and sport for the
social gathering, or the family fireside. The magical combinations
and effects of chemistry have furnished an almost infinite variety of
pleasant experiments, which may be performed by our youthful
friends with great success if a little care be taken; and the other
branches of natural science are nearly as replete with interest.
The following repertoire of such tricks and illusions will be found
exceedingly complete, although pains have been taken to select only
the best and most startling of them. A large number are entirely new,
but are described with sufficient clearness to enable any person of
ordinary intelligence to become expert in them, with a little practice.
Chemical Amusements.
Chemistry is one of the most attractive sciences. From the beginning
to the end the student is surprised and delighted with the
developments of the exact discrimination, as well as the power and
capacity, which are displayed in various forms of chemical action.
Dissolve two substances in the same fluid, and then, by evaporation
or otherwise, cause them to reassume a solid form, and each
particle will unite with its own kind, to the entire exclusion of all
others. Thus, if sulphate of copper and carbonate of soda are
dissolved in boiling water, and then the water is evaporated, each
salt will be reformed as before. This phenomenon is the result of one
of the first principles of the science, and as such is passed over
without thought; but it is a wonderful phenomenon, and made of no
account, only by the fact that it is so common and so familiar.
It is by the action of this same principle, “chemical affinity,” that we
produce the curious experiments with
Sympathetic Inks.
By means of these, we may carry on a correspondence which is
beyond the discovery of all not in the secret. With one class of these
inks, the writing becomes visible only when moistened with a
particular solution. Thus, if we write to you with a solution of the
sulphate of iron, the letters are invisible. On the receipt of our letter,
you rub over the sheet a feather or sponge, wet with a solution of
nut-galls, and the letters burst forth into sensible being at once, and
are permanent.
2. If we write with a solution of sugar of lead, and you moisten with a
sponge or pencil, dipped in water impregnated with sulphureted
hydrogen, the letters will appear with metallic brilliancy.
3. If we write with a weak solution of sulphate of copper, and you
apply ammonia, the letters assume a beautiful blue. When the
ammonia evaporates, as it does on exposure to the sun, the writing
disappears, but may be revived again as before.
4. If you write with the oil of vitriol very much diluted, so as to prevent
its destroying the paper, the manuscript will be invisible except when
held to the fire, when the letters will appear black.
5. Write with cobalt dissolved in diluted muriatic acid; the letters will
be invisible when cold, but when warmed they will appear a bluish
green.
We are almost sure that our secrets thus written will not be brought
to the knowledge of a stranger, because he does not know the
solution which was used in writing, and, therefore, does not know
what to apply to bring out the letters.
Alum Basket.
Make a small basket, about the size of the hand, of iron wire or split
willow; then take some lamp-cotton, untwist it, and wind it around
every portion of the basket. Then mix alum, in the proportion of one
pound with a quart of water, and boil it until the alum is dissolved.
Pour the solution into a deep pan, and in the liquor suspend the
basket, so that no part of it touch the vessel or be exposed to the air.
Let the whole remain perfectly at rest for twenty-four hours; when, if
you take out the basket, the alum will be found prettily crystallized
over all the limbs of the cottoned frame.
In like manner, a cinder, a piece of coke, the sprig of a plant, or any
other object, suspended in the solution by a thread, will become
covered with beautiful crystals.
If powdered tumeric be added to the hot solution, the crystals will be
of a bright yellow; if litmus be used instead, they will be of a bright
red; logwood will yield them of a purple, and common writing-ink, of
a black tint; or, if sulphate of copper be used instead of alum, the
crystals will be of fine blue.
But the colored alum crystals are much more brittle than those of
pure alum, and the colors fly; the best way of preserving them is to
place them under a glass shade, with a saucer containing water.
This keeps the atmosphere constantly saturated with moisture, the
crystals never become too dry, and their texture and color undergo
but little change.
Optical Amusements.
The science of optics affords an infinite variety of amusements,
which cannot fail to instruct the mind, as well as delight the eye. By
the aid of optical instruments we are enabled to lessen the distance
to our visual organs between the globe we inhabit and “the wonders
of the heavens above us;” to watch “the stars in their courses,” and
survey at leisure the magnificence of “comets importing change of
times and states;” to observe the exquisite finish and propriety of
construction which are to be found in the most minute productions of
the earth;—to trace the path of the planet, in its course around the
magnificent orb of day, and to detect the pulsation of the blood, as it
flows through the veins of an insect. These are but a few of the
powers which this science offers to man; to enumerate them all
would require a space equal to the body of our work; neither do we
propose to notice the various instruments and experiments which are
devoted to purposes merely scientific; it being our desire only to call
the attention of our juvenile readers to such things as combine a vast
deal of amusement with much instruction, to inform them as to the
construction of the various popular instruments; to show the manner
of using them, and to explain some of the most attractive
experiments which the science affords. By doing thus much, we
hope to offer a sufficient inducement to extend inquiry much further
than the information which a work of this nature will enable us to
afford.
The Phantasmagoria.
Between the phantasmagoria and the magic lantern there is this
difference: in common magic lanterns the figures are painted on
transparent glass; consequently the image on the screen is a circle
of light, having figures upon it; but in the phantasmagoria all the
glass is opaque, except the figures, which, being painted in
transparent colors, the light shines through them, and no light can
come upon the screen except that which passes through the figure.
There is no sheet to receive the picture, but the representation is
thrown on a thin screen of silk or muslin, placed between the