1. Instances of the Random class generate sequences of random numbers by starting with a special 48-bit value that’s known as a seed. This value is subsequently modified by a mathematical algorithm, which is known as a linear congruential generator.
2. The root set of references is a collection of local variables, parameters, class fields, and instance fields that currently exist and that contain (possibly null) references to objects.
3. The answer is false: the garbage collector can collect unreachable objects only.
4. The different levels of reachability are strongly reachable, softly reachable, weakly reachable, and phantom reachable.
5. The difference between a soft reference and a weak reference is that the garbage collector is more eager to collect an object that is reachable only via a weak reference.
6. The classes that comprise the References API are Reference,
ReferenceQueue, SoftReference, WeakReference, and PhantomReference. All of these classes are located in the java.lang.ref package.
7. You would use the SoftReference class to implement caches of objects that are expensive timewise to create.
8. You would use the PhantomReference class as a replacement for the finalize() method.
9. Some of the capabilities offered by the Reflection API are letting applications dynamically load and learn about loaded classes and other reference types;
and letting applications instantiate classes, call methods, access fields, and perform other tasks reflectively.
10. Reflection shouldn’t be used indiscriminately for several reasons. Application performance suffers because it takes longer to perform operations with reflection than without reflection. Also, reflection-oriented code can be harder to read, and the absence of compile-time type checking can result in runtime failures.
11. The class that’s the entry point into the Reflection API is java.lang.Class.
12. The answer is false: not all of the Reflection API is contained in the
java.lang.reflect package. For example, Class is located in the java.lang package.
13. The three ways to obtain a Class object are to invoke Class’s forName() method, to invoke Object’s getClass() method, and to use a class literal.
14. The answer is true: you can use class literals with primitive-types.
15. You instantiate a dynamically loaded class by invoking Class’s newInstance() method.
16. You invoke Constructor’s Class[]<?> getParameterTypes() method to obtain a constructor’s parameter types.
17. Class’s Field getField(String name) method throws NoSuchFieldException when it cannot locate the named field.
18. You determine if a method is declared to receive a variable number of arguments by invoking Method’s isVarArgs() method on the Method object that represents the method.
19. The answer is true: you can reflectively make a private method accessible.
You do this by invoking the setAccessible() method that each of Constructor, Field, and Method inherits from its AccessibleObject superclass.
20. The purpose of Package’s isSealed() method is to indicate whether or not a package is sealed (all classes that are part of the package are archived in the same JAR file). This method returns true when the package is sealed.
21. The answer is true: getPackage() requires at least one classfile to be loaded from the package before it returns a Package object describing that package.
22. You reflectively create and access a Java array by invoking the class methods declared in the java.lang.reflect.Array class.
23. The purpose of the StringTokenizer class is to provide access to a string’s individual components.
24. The java.util package’s Timer and TimerTask classes are the standard class library’s convenient and simpler alternative to the Threads API for scheduling task execution.
25. The answer is false: Timer() creates a new timer whose task-execution thread doesn’t run as a daemon thread.
26. In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. When an execution is delayed for any reason (such as garbage collection), subsequent executions are also delayed.
27. You call the schedule() methods to schedule a task for fixed-delay execution.
28. In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. When an execution is delayed for any reason (such as garbage collection), two or more executions will occur in rapid succession to “catch up.”
29. The difference between Timer’s cancel() method and TimerTask’s cancel() method is as follows: Timer’s cancel() method terminates the timer, discarding any currently scheduled timer tasks. In contrast, TimerTask’s cancel() method cancels the invoking timer task only.
30. Listing A-41 presents the Guess application that was called for in Chapter 8.
Listing A-41. Guessing Game import java.util.Random;
public class Guess {
public static void main(String[] args) throws java.io.IOException {
Random r = new Random();
int hiddenValue = 'a' + r.nextInt(26);
while (true)
{
int guess = 0;
while (guess < 'a' || guess > 'z') {
System.out.print("Guess between a and z inclusive: ");
guess = System.in.read();
System.out.println();
// Flush carriage return or carriage return/newline combination // so that each character isn't automatically read during the // next System.in.read() method call.
int x = 0;
while (x != '\n') x = System.in.read();
}
if (guess < hiddenValue)
System.out.println("too low");
else
if (guess > hiddenValue)
System.out.println("too high");
else {
System.out.println("you got it");
break;
} } } }
31. Listing A-42 presents the Classify application that was called for in Chapter 8.
Listing A-42. Classifying a Command-Line Argument as an Annotation Type, Enum, Interface, or Class public class Classify
{
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Classify pkgAndTypeName");
return;
} try {
Class<?> clazz = Class.forName(args[0]);
if (clazz.isAnnotation())
System.out.println("Annotation");
else
if (clazz.isEnum())
System.out.println("Enum");
else
if (clazz.isInterface())
System.out.println("Interface");
else
System.out.println("Class");
}
catch (ClassNotFoundException cnfe) {
System.err.println("could not locate " + args[0]);
} } }
Specify java Classify java.lang.Override, and you’ll see Annotation as the output.
Also, java.Classify java.math.RoundingMode outputs Enum, java Classify java.lang.
Runnable outputs Interface, and java Classify java.lang.Class outputs Class. 32. Listing A-43 presents the Tokenize application that was called for in Chapter 8.
Listing A-43. Extracting the Month, Day, Year, Hour, Minute, and Second Tokens from a Date String import java.util.StringTokenizer;
public class Tokenize {
public static void main(String[] args) {
String date = "03-12-2014 03:05:20";
StringTokenizer st = new StringTokenizer(date, "- :");
System.out.println("Month = " + st.nextToken());
System.out.println("Day = " + st.nextToken());
System.out.println("Year = " + st.nextToken());
System.out.println("Hour = " + st.nextToken());
System.out.println("Minute = " + st.nextToken());
System.out.println("Second = " + st.nextToken());
} }
33. Listing A-44 presents the BackAndForth application that was called for in Chapter 8.
Listing A-44. Repeatedly Moving an Asterisk Back and Forth via a Timer import java.util.Timer;
import java.util.TimerTask;
public class BackAndForth {
static enum Direction { FORWARDS, BACKWARDS } public static void main(String[] args) {
TimerTask task = new TimerTask() {
final static int MAXSTEPS = 20;
Direction direction = Direction.FORWARDS;
int steps = 0;
@Override
public void run() {
switch (direction) {
case FORWARDS : System.out.print("\b ");
System.out.print("*");
break;
case BACKWARDS: System.out.print("\b ");
System.out.print("\b\b*");
}
if (++steps == MAXSTEPS) {
direction = (direction == Direction.FORWARDS) ? Direction.BACKWARDS
: Direction.FORWARDS;
steps = 0;
} } };
Timer timer = new Timer();
timer.schedule(task, 0, 100);
} }