Chapter 3

¡Supera tus tareas y exámenes ahora con Quizwiz!

Consider the following two lines of code. What can you say about s1 and s2? String s1 = "testing" + "123"; String s2 = new String("testing 123"); A) s1 and s2 are both references to the same String object B) the line declaring s2 is legal Java; the line declaring s1 will produce a syntax error C) s1 and s2 are both references to different String objects D) s1 and s2 will compare "equal" E) none of the above

C) Both declarations are legal Java. s1 is a String reference, and it is initialized to the String "testing123". s2 is a String reference, and it is initialized to the String "testing 123". Note the space between the "testing" and the "123". So the two Strings are not equal.

In the StringMutation program shown in Listing 3.1, if phrase is initialized to "Einstein" what will Mutation #3 yield if Mutation #1: mutation1 = phrase.concat(".")? A) Einstein. B) EINSTEIN. C) XINSTXIN. D) einstein. E) xinstxin.

C) Mutation #2 changes every letter to upper case. Then Mutation #3 replaces Es with Xs.

An API is A) an Abstract Programming Interface B) an Application Programmer's Interface C) an Application Programming Interface D) an Abstract Programmer's Interface E) an Absolute Programming Interface

C) an API is an application Programming Interface a collection of related classes that have been built for specific purposes. They usually reside in a class library.

The String class' compareTo method A) compares two string in a case-independent manner B) yields true or false C) yields 0 if the two strings are identical D) returns 1 if the first string comes lexically before the second string E) none of the above

C) compareTo yields 0 if the two strings are identical, -1 if the first string comes lexically before the second, +1 if the first string comes lexically after the second.

What is a wrapper class? Why are they useful?

A wrapper class is a class that allows you to embed one piece of primitive data within an Object. There are methods for extracting the data from the Object. Wrapper classes are useful where you have methods (or constructors) that only accept Objec By wrapping the primitive data within an Object the functionality of the method (and its class) may be accessed.

An "alias" is when A) two different reference variables refer to the same physical object B) two different numeric variables refer to the same physical object C) two different numeric variables contain identical values D) two variables have the same names E) none of the above

A) An "alias" occurs when there are two or more references to the same physical object so that by following either reference, one can read/write/modify the object

Autoboxing is A) the automatic conversion of a wrapper object to/from its corresponding primitive type B) the automatic enclosure of a graphics object within a bounding box C) the automatic widening of ints into floats or doubles, as required D) the automatic conversion of an enumeration into its numeric representation E) none of the above

A) Boxing is the enclosure of a primitive type by a wrapper object. Autoboxing occurs when the data within wrapped object is automatically extracted or when primitive data is automatically wrapped.

In Java a variable may contain A) a value or a reference B) a package C) a method D) a class E) any of the above

A) Java variables contain values or references to instances of classes (which contain values and/or additional references).

What will be displayed by this command: System.out.println(Math.pow(3, 3-1)); A) 9 B) 8 C) 6 D) 4 E) 27

A) This evaluates to Math.pow(3, 2) which is 32 which is 9.

If two variables contain aliases of the same object then A) the object may be modified using either alias B) the object cannot be modified unless there's but a single reference to it C) a third alias is created if/when the object is modified D) the object will become an "orphan" if both variables are set to null E) answers A and D are correct

E) By definition, a alias provides a means by which an object can be modified (an alias is like a pointer). If both variables are set to null, then the object is not referenced by any variable (via any alias) and it does, indeed, become an "orphan" at some point in the future.

What happens if you attempt to use a variable before it has been initialized? A) A syntax error may be generated by the compiler B) A runtime error may occur during execution C) A "garbage" or "uninitialized" value will be used in the computation D) A value of zero is used if a variable has not been initialized E) Answers A and B are correct

E) Many times the compiler is able to detect the attempted use of an uninitialized compiler then a runtime error occurs upon usage. Java is a very "safe" language, so it does not allow "garbage" or zero to be used if an uninitialized variable is used in a computation.

Java.text's NumberFormat class includes methods that A) allow you to format currency B) allow you to format percentages C) round their display during the formatting process D) truncate their display during the formatting process E) A, B, C, but not D

E) NumberFormat always rounds; it never truncates. And, it does provide methods for both currency and percentages.

For the program to get a name interactively a Scanner object must be instantiated. Write the Java statement to do this.

Scanner scan = new Scanner(System.in);

These two ways of setting up a String yield identical results: a) String string = new String("123.45"); b) String string = "" + 123.45;

TRUE Explanation: Java understands the + operator when used to combine Strings with numbers means that the number should be converted into a numeric String, and then concatenation should occur.

All the methods in the Math class are declared to be static.

TRUE Explanation: The Math class methods are designed to be generally useful in arithmetic expressions, so no instances of anything are required to make use of them. This is achieved by ensuring that all the Math methods are static.

The Random class' setSeed( ) method allows you to restart the pseudo-random number sequence.

TRUE Explanation: You can specify the initial seed for a Random instance either by using the Random(long seed) constructor, or once you have an instance, say Random random = new Random( );, then you may re-initialize the seed by using random.setSeed(long seed);

Write a statement using a method to guarantee that the initial will be a capital letter.

firstInitial = firstInitial.toUpperCase( );

Write a method to extract the initial from the first name.

firstInitial = firstName.substring(0,1);

Write a statement using a Scanner method to get the first name interactively

firstName = scan.nextLine( );

Rewrite the following five assignment statements into a single statement using prefix and postfix increment and decrement operators as necessary. Assume all variables are int variables. x = y + 1; y = y + 1; z = z - 1; x = x - z; x = x + 1;

x = (y++ + 1) - (--z) + 1;

In Java, "instantiation" means A) noticing the first time something is used B) creating a new object of the class C) creating a new alias to an existing object D) launching a method E) none of the above

B) "Instantiation" means creating a new instance of an object. This usually is accomplished by using the new operator. In the case of Strings, new instances (instantiation) may be created just by using quotes in an expression. For example: String s; s = "A new string (instance)";

Say you write a program that makes use of the Random class, but you fail to include an import statement for java.util.Random (or java.util.*). What will happen when you attempt to compile and run your program. A) The program won't run, but it will compile with a warning about the missing class. B) The program won't compile-you'll receive a syntax error about the missing class. C) The program will compile, but you'll receive a warning about the missing class. D) The program will encounter a runtime error when it attempts to access any member of the Random class E) none of the above

B) The missing class means that there will be undefined variables and/or methods. The compiler will detect these and will issue error messages. Your program won't be executable.

In addition to their usage providing a mechanism to convert (to box) primitive data into objects, what else do the wrapper classes provide? A) enumerations B) static constants C) arrays to contain the data D) exceptions E) none of the above

B) The wrapper classes also provide static constants, like MIN_VALUE and MAX_VALUE (the smallest and largest ints).

Which of the following will yield a pseudorandom number in the range [ -5, +5 ) given the following: Random gen = new Random( ); A) gen.nextFloat( ) * 5 B) gen.nextFloat( ) * 10 - 5 C) gen.nextFloat( ) * 5 - 10 D) gen.nextInt( ) * 10 - 5 E) gen.nextInt(10) - 5

B) nextFloat yields a pseudorandom number in the range [ 0, 1 ); multiplying by 10 yields numbers in the range [ 0, 10 ); subtracting 5 yields numbers in the range [ -5, 5 ).

Given the following code fragment String strA = "aBcDeFg"; String strB = strA.toLowerCase( ); strB = strB.toUpperCase( ); String strC = strA.toUpperCase( ); A) strB.equals(strC) would be true B) strB.compareTo(strC) would yield 0 C) strA.compareTo(strC) would yield 0 D) strA.equals(strC) would be true E) none of the above

B) strB contains the uppercase forms of all the letters in strA; so does strC. So compareTo would yield 0, indicating equality.

The printf method within System.out is designed to ease the conversion of legacy C code into Java.

TRUE Explanation: C programs use the C printf function for output. Java's printf method is modeled closely after the C printf function, so C output statements can be translated into Java extremely easily.

These two ways of setting up a string yield identical results: a) String string = new String("string"); b) String string = "string";

TRUE Explanation: Java has a very strong notion about what Strings are and how they function. The second declaration is merely "shorthand" for the first. The string reference will be initialized identically by both declarations.

What is autoboxing?

Autoboxing provides automatic conversions between primitive values and corresponding wrapper objects. It makes your code shorter by relieving you of the need to provide explicit wrapping of primitive values and explicit extraction of primitive values.

Which properties are true of String objects? A) Their lengths never change B) The shortest string has zero length C) Individual characters within a String may be changed using the replace method D) The index of the first character in a string is one E) Only A and B are true

E) Strings are immutable. That means that once a string object is created it cannot be changed. Therefore the length of a string never changes once it has been created. The shortest length string is ""there are no characters between the quotes, so the length is zero. The replace method allows you to create a new string from an original one, replacing some of the characters. The index of the first location in a string is zero not one. Also, the last byte of every string contains the end-of-string character which is a byte of low-values, or binary zeros

What is the function of the dot operator? A) It serves to separate the integer portion from the fractional portion of a floating point number B) It allows one to access the data within an object when given a reference to the object C) It allows one to invoke a method within an object when given a reference to the object D) It is used to terminate commands (much as a period terminates a sentence in English) E) Both B and C are correct

E) The dot operator is appended directly after the object reference, followed by the data or method to which access is desired. In the case of data, the access may be for reading or writing. In the case of a method, the access is to allow one to invoke the method. The dot within a floating point number is a decimal point not a dot operator

The advantage(s) of the Random class' pseudo-random number generators, compared to the Math.random method, is that A) you may create several random number generators B) the generators in Random are more efficient than the one in Math.random C) you can generate random ints, floats, and ints within a range D) you can initialize and reinitialize Random generators E) all but answer B

E) The efficiency of all the random number generators are the same. The advantages of Random generators over Math.random include all the other properties.

System.out.println("123" + 4) will display the value 127.

FALSE Explanation: "123" is a String. So, the + will cause String concatenation to occur. The int 4 will be converted into the String "4", and the String 1234 will be created and displayed.

In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably).

FALSE Explanation: "=" is used for assignment statements while "==" is used to test equality in conditional statements.

These two ways of setting up a String yield identical results: a) String string = new String(12345); b) String string = new String("12345");

FALSE Explanation: In fact, the first statement won't even compile! There is no overloaded version of the String constructor that accepts a numeric argument.

These two ways of setting up a String yield identical results: a) String string = "12345" b) String string = 12345;

FALSE Explanation: In fact, the second statement won't even compile! The second statement will receive a syntax error about incompatible types. There is no automatic conversion from a number to a String

Only difficult programming problems require a pseudocode solution before the programmer creates the implementation (program) itself.

FALSE Explanation: Some form of design should be created for all problems before the program is written, with the possible exception of only the most trivial of problems. The form of the design may vary. For instance, programmers in the 1960s and 1970s often used flow charts instead of pseudocode.

If you need to import not only the top-level of a package, but all its secondary levels as well, you should write: import package.*.*;

FALSE Explanation: The import statement can only be used with a single * (wild card). If you need to import all the secondary levels of a package as well, you must write them out explicitly: import package.A.*; import package.B.*;

You may use the String replace( ) method to remove characters from a String.

FALSE Explanation: The replace( ) method only replaces single characters with other single characters. The replace( ) method will not add or delete characters to a String; the String length will remain the same.

You may apply the prefix and postfix increment and decrement operators to instances of the Integer class.

FALSE Explanation: These operators may only be applied to numeric data. An instance of a class is an object not a piece of primitive data

The names of the wrapper classes are just the names of the primitive data types, but with an initial capital letter.

FALSE Explanation: This is true for most of the wrapper classes, but it is false for int (Integer) and char (Character).

When comparing any primitive type of variable, == should always be used to test to see if two values are equal.

FALSE Explanation: This is true of int, short, byte, long, char and boolean, but not of double or float variables. If two double variables, x and y, are being tested, (x == y) is true only if they are exactly equal to the last decimal point. It is common instead to compare these two values but allow for a small difference in value. For instance, if THETA = 0.000001, we might test x and y by (x - y <= THETA) instead of (x == y) to get a better idea of if they are close enough to be considered equal.

Consider the condition (x == y). How is this handled if x and y are primitive types? How is this handled if x and y are objects?

If x and y are primitive types, then the values stored in x and y are compared and true is returned if the two values are equal. If x and y are objects, then the object that x and y reference are compared. If they are the same object, it returns true, otherwise it returns false.

Given two String variables, s1 and s2, is it possible for (s1 != s2) to be true while (s1.equals(s2)) is also true? Why or why not?

The condition (s1 != s2) means that s1 and s2 are references to two distinct Objects. It says nothing about the contents of the referenced Objects. So, the contents of s1 may well be identical or different from the contents of s2. Therefore it is quite possible that (s1.equals(s2)) is true while (s1 != s2) is also true.

The advantages of the DecimalFormat class compared with the NumberFormat class include A) precise control over the number of digits to be displayed B) control over the presence of a leading zero C) the ability to truncate values rather than to round them D) the ability to display a % automatically at the beginning of the display E) only A and B

While DecimalFormat does provide far more control than NumberFormat, truncation remains in the hands of the programmer via one or more of the Math Methods. The % symbol would appear at the end of the display not the beginning


Conjuntos de estudio relacionados

Human Resource Management chapters 2 & 3

View Set

Chapter 15: Postpartum Adaptations

View Set

Chapter 7 The Skeletal System: The Axial Skeleton

View Set

EMBEDDED SYSTEMS MIDTERM QUIZZES REVIEW (except for ESSAY)

View Set

Medical Terminology Chapter 17 Abbreviations: The Eye

View Set

Ch 3 The Chemistry of Organic Molecules

View Set