### Practice Test 1

Every Boolean function can be constructed from only:

a. And function
b. Or function
c. Nand function
d. Not function

What is the decimal value of this 16-bit 2's complement number?

1111111111111100two

a. 2 input pins, 2 output pins.
b. 2 input pins, 1 output pin.
c. 3 input pins, 2 output pins.
d. 3 input pins, 1 output pin.

What is the most basic element of every computer system?

a. CPU
b. Memory
c. Logic Gate
d. ALU

True/False: Adding 011011012 to 101000102 in 8-bit unsigned binary will cause an overflow.

True
False

Whick of the following is NOT a component required to represent a floating point number in binary?

a. Exponent
b. Fraction
c. Sign bit
d. Precision

Match the following gates to their description.

And → If a=b=1 then out=1 else out=0,
Not → If in=0 then out=1 else out=0,
Nand → If a=b=1 then out=0 else out=1,
Or → If a=b=0 then out=0 else out=1

9. What is the decimal value of 54 (base 10) converted to binary and 2's complement?

a. 11001010
b. 00110110
c. 11001001
d. 11110001

10. What is the decimal equivalent of the binary number 10011101? Assume "unsigned" binary for the conversion.

a. 157
b. 99
c. -99
d. -29

11. What is the function of the following logic circuit?

c. And circuit
d. Inverter

True/False: A decoder has a unique output represented for a set of inputs in a truth table?

True
False

12. The ny control bit will:

a. Zero the y input.
b. Negate the x input.
c. Negate the ng output.
d. Negate the y input.

13. A coding approach that recognizes the MSB with a value of 1 to be a negative number is called?

a. Signed Magnitude
b. 1's complement
c. 2's complement
d. Binary Coded Decimal

The boolean expression A+B represents which of the following:

a. A NOR B
b. A NAND B
c. A NOT B
d. A NAND B

2. True/False: According to DeMorgan's Theorem, inverting the output of an AND gate yields the same output as an OR gate with inverted inputs?

True
False

True/ False: In a 16-bit Multiplexor the selector is 16-bit wide.

True
False

True/False: The operation to be performed within the ALU is selected with a multiplexor circuit.

True
False

What circuit does the following truth table belong to?

c. incrementer
d. ALU (Arithmetic Logic Unit)

Given the following logic gate, select the truth table from below that is NOT valid given the format A - B - Output:

a. 0 - 0 - 0
b. 0 - 1 - 1
c. 1 - 1 - 1
d. 1 - 0 - 1

What is the binary pattern that represents 6ten (in a 16-bit binary system)?

Which Two-Input Boolean function will return 0 for every input it receives?

a. Constant 0
b. Not
c. Nor
d. And

Name an unary Boolean function:

If a demultiplexor selector bit is set to 1, and both outputs (a and b) are 0, then the input must have been:

### Silly Sentences

Lab 3: Silly Sentences and Fancy Fractals

In this lab, you will be working with recursion. In the first part of the lab, you will write a program that generates random sentences based on a set of syntax rules. In the second, you will use recursion to create pictures of fractals.

Part 1: Recursive Syntax

The grammar of natural languages such as English exhibits a recursive structure. This structure can be expressed in syntax rules written in the format known as BNF (Bachus-Naur Form, named after the people who invented it). You have probably seen BNF used to specify the syntax of programming languages. While BNF is ordinarily used as a guide for parsing (that is, determining whether and how a given string follows the syntax rules), it can also be used a guide for generating strings that follow the syntax rules. An example of this can be found in the sample program SimpleRandomSentences. In this example, each syntax rule -- except for the most basic ones -- is represented by a method that generates strings that follow that rule. Where one syntax rule refers to another rule, the method that represents the first rule calls the method that represents the second rule.

For the first exercise of the lab, you should write a similar program that implements the following rules:

<sentence> ::= <simple_sentence> [ <conjunction> <sentence> ]

<simple_sentence> ::= <noun_phrase> <verb_phrase>

<noun_phrase> ::= <proper_noun> |
<determiner> [ <adjective> ]. <common_noun> [ who <verb_phrase> ]

<verb_phrase> ::= <intransitive_verb> |
<transitive_verb> <noun_phrase> |
believes that <simple_sentence>

<conjunction> ::= and | or | but | because

<proper_noun> ::= Fred | Jane | Richard Nixon | Miss America

<common_noun> ::= man | woman | fish | elephant | unicorn

<determiner> ::= a | the | every | some

<adjective> ::= big | tiny | pretty | bald

<intransitive_verb> ::= runs | jumps | talks | sleeps

<transitive_verb> ::= loves | hates | sees | knows | looks for | finds

As in SimpleRandomSentences.java, you can use arrays to implement the last seven rules in this list. (You might improve on that program by writing a single method "void String randomItem(String[] listOfStrings)" for picking a random item from an array of strings.) You are welcome to add to or modify the items in the lists given here.

For each of the first three rules, you should write a subroutine to represent that rule. Note that a choice of alternatives (represented in the rules by "|") can be implemented using a switch or if..else statement; the various choices don't necessarily have to have the same probability. An optional element (represented by brackets, "[ xxx ]") can be implemented by a simple if. And a repeated optional element (represented by brackets with dots, "[ xxx ]...") can be represented by a while loop. You should implement the first four rules exactly as stated here. The main routine should call the <sentence> subroutine to generate random sentences.

You have to be careful in this program to avoid infinite recursion in this program. Since it will use random choices, there is no guarantee that the recursion will ever end. If your probabilities of doing recursion and continuing loops are too high, it is possible for the program to get lost in recursive calls forever -- or to produce some finite but ridiculously long sentences. You should adjust your probabilities to make sure that this doesn't happen, but that you still get some interesting sentences.

## Solution Here

### Exceptions/Sorting

This lab has two parts, with no real connection between them. The first part of the lab asks you to find out how long it takes to sort a large array using both a sorting method that you write and using Java’s built-in sorting method; this part of the lab is part of this course’s introduction to analysis of algorithms. In the second part of the lab, you will write a program that does some simple networking and file I/O. Since these operations can generate checked exceptions, you have to use try..catch in your program to handle the potential exceptions.
You will probably want to start a new Eclipse project for this lab. However, note that a project can contain any number of programs, so you don’t necessarily need a new project for every small program that you write.
For this assignment, you will write two programs for this lab. You will generate some data using the first program — you should include this data in a comment at the beginning of the program file.

## Part 1: Benchmarking Sorting Algorithms

The same task can take vastly different amounts of time, depending on the algorithm that is used to perform the task. You are familiar with simple sorting algorithms such as insertion sort and selection sort. (See Section 7.4 in the textbook.) While these methods work fine for small arrays, for larger arrays they can take an unreasonable amount of time. The question is whether we can do any better.
Java has some built-in sorting methods. They can be found in the class named Arrays in the package java.util. The one that you will use in this lab is Arrays.sort(A), which sorts the entire array A into increasing order. (Actually, there are different methods for different array base types, but all the methods have the same name and are used in the same way. You will be using an array of ints in this lab.)
You should write a program that does the following:
Create two arrays of type int[]. Both arrays should be the same size, and the size should be given by a constant in the program so that you can change it easily.
Fill the arrays with random integers. The arrays should have identical contents, with the same random numbers in both arrays. To generate random integers with a wide range of sizes, you could use (int)(Integer.MAX_VALUE * Math.random()).
Sort the first array using either Selection Sort or Insertion Sort. You should add the sorting method to your program; you can copy it from Section 7.4, if you want. (It is a good idea to check that you got the sorting method correct by using it to sort a short array and printing out the result.)
Time how long it takes to sort the array, and print out the time.
Now, sort the second (identical) array using Arrays.sort(). Again, time how long it takes, and print out the time.
You should run your program using array sizes of 1,000, 10,000, and 100,000. Record the sort times. Add a comment to the top of the program that reports the times. (You might be interested in applying Arrays.sort() to a million-element array, but don’t try that with Selection Sort or Insertion Sort!)
Note: The general method for getting the run time of a code segment is:
long startTime = System.currentTimeMillis();
doSomething();
long runTime = System.currentTimeMillis() – startTime;
This gives the run time in milliseconds. If you want the time in seconds, you can use runTime/1000.0.

## Part 2: Programming with Exceptions

In this part of the lab, you will write a program that fetches the information stored at a give URL on the web and saves that data to a file. This will also include networking and file operations and partly an exercise in using exceptions.
For doing I/O, Java has a pair of nice abstractions: InputStream and OutputStream. These are abstract classes in the package java.io. An InputStream is a place from which you can read data; an OutputStream is a place to which you can write data. For this lab, you will use an InputStream to represent the data read from the Web URL, and you will use an OutputStream to represent the file where you want to save a copy of the data. Once you have the streams, the data can be copied just by calling the following method, which you can copy into your program:
private static void copyStream(InputStream in, OutputStream out)
throws IOException {
while (oneByte >= 0) { // negative value indicates end-of-stream
out.write(oneByte);
}
}

Aside from this method, you should have a main routine that does the following:
Declare variables to represent the InputStream and the OutputStream. It would be a good idea to initialize them to null to avoid uninitialized variable errors.
Read the URL and the file name as strings from the user.
To connect to the web, you need a variable — say url — of type URL (from package java.io). You can create the URL object with the constructor call url = new URL(urlString), where urlString is the string provided by the user. This constructor will throw a MalformedURLException if the string is not a legal URL. (Note: the string must be a complete URL, beginning with “http://”.)
To get the input stream, you can simply call url.openStream(), which returns a value of type InputStream. This can throw an IOException, for example, if the web address that you are asking for does not exist.
To get the output stream, you can use the constructor new FileOutputStream(fileName), where fileName is the file name that was input by the user. This can throw a FileNotFoundException if it is not possible to open the specified file for reading (for example, if the user is trying to create a new file in a directory where they don’t have write permission). Warning: If a file of the same name already exists, the old file will be erased and replaced by the new one, without giving the user any notice!
Now, copy the data from the web into the file by calling the above method. Note that this can throw an IOException.
Finally, use a finally to clause to make sure that both streams are closed (if they were successfully opened). Both InputStream and OutputStream have a close() method for closing the stream. Note that you can test whether the stream was opened by testing whether the value of the variable is still null.
Note that an exception should not crash your program. You should catch the exception and print out a reasonable error message before ending the program. It would be nice if the error message depends on the type of error that occurred (which means using several catch clauses).

## Solution is found here

### Practice

To create a list to store integers, use

a. ArrayList<Object> list = new ArrayList<Integer>();
b. ArrayList<Integer> list = new ArrayList<Integer>();
c. ArrayList<int> list = new ArrayList<int>();
d. ArrayList<Number> list = new ArrayList<Integer>();

Question 2

If the characters 'D', 'C', 'B', 'A' are placed in a queue (in that order), and then removed one at a time, in what order will they be removed?

Select one:
a. ABCD
b. ABDC
c. DCAB
d. DCBA

Question 3

What code is missing to complete the following method for sorting a list?

public static void sort(double[] list) {
___________________________;
}

public static void sort(double[] list, int high) {
if (high > 1) {
// Find the largest number and its index
int indexOfMax = 0;
double max = list[0];
for (int i = 1; i <= high; i++) {
if (list[i] > max) {
max = list[i];
indexOfMax = i;
}
}

// Swap the largest with the last number in the list
list[indexOfMax] = list[high];
list[high] = max;

// Sort the remaining list
sort(list, high - 1);
}
}

Select one:
a. sort(list)
b. sort(list, list.length)
c. sort(list, list.length - 1)
d. sort(list, list.length - 2)

Question 4

In what way can a Set be distinguished from other types of Collections?
“A Set cannot contain duplicate elements.”

Select one:
True
False

Question 5

Which of the following statements are true?

Select one or more:

a. Recursive methods usually takes more memory space than non-recursive methods.
b. A recursive method can always be replaced by a non-recursive method.
c. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.
d. Recursive methods run faster than non-recursive methods.

Question 6

Which of the following are true?

Select one or more:

a. A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack.
b. A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue.
c. Since the insertion and deletion operations on a stack are made only at the end of the stack, using an array list to implement a stack is more efficient than a linked list.
d. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a linked list than an array list.

Question 7

Suppose the rule at the office is that the workers who arrive later will leave earlier. Which data structure is appropriate to store the workers?

Select one:
a. Stack
b. Queue
c. Array List

Question 8

To declare an interface named A with two generic types, use

a. public interface A<E> { ... }
b. public interface A<E, F> { ... }
c. public interface A(E) { ... }
d. public interface A(E, F) { ... }

Question 9

To create a list to store integers, use

a. ArrayList<Object> list = new ArrayList<Integer>();
b. ArrayList<Integer> list = new ArrayList<Integer>();
c. ArrayList<int> list = new ArrayList<int>();
d. ArrayList<Number> list = new ArrayList<Integer>();

Question 10

What is the printout of the following code?

List<String> list = new ArrayList<String>();
for (int i = 0; i < list.size(); i++)
System.out.print(list.remove(i));

Select one:
a. ABCD
b. AB
c. AC
e. ABC

Question 11

The server listens for a connection request from a client using the following statement:

Select one:
a. Socket s = new Socket(ServerName, port);
b. Socket s = serverSocket.getSocket()
c. Socket s = new Socket(ServerName);
d. Socket s = serverSocket.accept()

Question 12

Which of the following code is correct to obtain hour from a Calendar object cal?

Select one:
a. cal.get(Calendar.HOUR);
b. cal.getHour();
c. cal.hour();
d. cal.get(Hour);

The next two questions refer to this method:

public void switchMethod(String input){
switch(input){
case "apple":
System.out.println("sauce");
break;
case "orange":
System.out.println("julius");
case "banana":
System.out.println("split");
break;
case "pear":
System.out.println("juice");
default:
System.out.println(input);
}

Question 13

What is the output to System out after the following method call: switchMethod("orange");

Select one:
a. sauce
b. julius
c. split
d. juice
e. None of the Above

Question 14

What is the output to System out after the following method call: switchMethod("strawberry");

Select one:
a. sauce
b. julius
c. juice
d. strawberry
e. None of the Above

The next two questions refer to the following:

1 public int factorial(int number){
2    if(number==1) {
3        return 1;
4    } else {
5        return number*(factorial(number-1));
6    }
7 }

Question 15

On which line is the base case for this recursive function?

Select one:
a. 1
b. 2
c. 4
d. 5
e. None of the Above

Question 16

On which line is the recursive call for this recursive function?

Select one:
a. 1
b. 2
c. 4
d. 5
e. None of the Above

The next two questions refer to the following:

Cell class reference:

public class Cell {
public Cell(){
}
public char content;  // The character in this cell.
public Cell next;     // Pointer to the cell to the right of this one.
public Cell prev;     // Pointer to the cell to the left of this one.
}

The following method is supposed to move one node to the right in a doubly linked list of Cells but it contains a flaw.

The global variable 'currentCell' is a pointer to a Cell in the list.

1    public void moveRight() {
2           if (currentCell.next == null) {
3                Cell newCell = new Cell();
4                newCell.content = ' ';
5                newCell.next = null;
6                newCell.prev = currentCell;
7                currentCell.next = newCell;
8                currentCell = currentCell.next;
9                }
10        }

Question 17

True or False: If 'currentCell' is at the head of the list this moveRight() method will perform its duties correctly.

Select one:
True
False

Question 18

True or False: If 'currentCell' is in the middle of the list this moveRight() method will perform its duties correctly.

Select one:
True
False

Question 19

Sample class reference:

public class Sample {

private int number;
private String color;

public Sample(int number) {
this.number = number;
this.color = "blue";
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Sample other = (Sample) obj;
if ((this.color == null) ? (other.color != null) : !this.color.equals(other.color)) {
return false;
}
return true;
}
}

Given the above code for the Sample class what is the output of the following program:

public static void main(String args[]){
List<Sample> list = new ArrayList();
Sample sample1 = new Sample(1);
Sample sample2 = new Sample(2);
Boolean contains;
contains = list.contains(sample2);
System.out.println("Contains: " + contains);
}

Select one:
a. Contains: true
b. Contains: false
c. Contains: null

Question 20

True or False: A Set is used to store objects in a particular order.

Select one:
True
False

Question 21

True or False: The following two statements will always yield the same value when a and b are Strings:

1) a.equals(b);
2) a==b;

Select one:
True
False

Question 22

Overloaded methods must be differentiated by:

Select one:
a. method name
b. data type of arguments
c. method signature
d. None of the above

Question 23

True or False: An Interface contains method declarations as well as implementations.

Select one:
True
False

Question 24

True or False: A class that implements an interface may only implement a few of that interface's method declarations.

Select one:
True
False

Question 25

For the following list:

int[] list = { 4, 8, 10, 6, 2, 8, 5 };

What would the list look like after one pass of the outer loop of the bubble sort algorithm?

Select one:
a. { 2, 4, 5, 6, 8, 8, 10 }
b. { 4, 8, 8, 6, 2, 10, 5 }
c. { 4, 8, 6, 2, 8, 5, 10 }
d. None of the above

Question 26

True or False: Every 'try' block must end with a 'finally' block.

Select one:
True
False

Question 27

If A and B are logical expressions: !(A && B) is equivalent to:

Select one:
a. (A || B)
b. (!A || !B)
c. (!A && !B)
d. None of the above

### Self Quiz 7

Given the following code:

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.translate( getWidth()/2, getHeight()/2 );
g2.rotate( 30 * Math.PI / 180 );
g2.fillRect(0,0,200,200);
}

Which of the following describes the output?

Select one or more:

a. A filled black square that is 100-by-100 pixels in size.
b. The corner of the square is at the center of the component that is being painted, and the top side of the square descends at a 30 degree angle from that point.
c. The rotate command rotates the picture by 30 degrees in a clockwise direction about the origin.
d. The top of the square is rotated from the horizontal position onto a line that is 30 degrees clockwise of the horizontal. That line descends at a 30 degree angle.

The correct answer is: The corner of the square is at the center of the component that is being painted, and the top side of the square descends at a 30 degree angle from that point., The rotate command rotates the picture by 30 degrees in a clockwise direction about the origin., The top of the square is rotated from the horizontal position onto a line that is 30 degrees clockwise of the horizontal. That line descends at a 30 degree angle.

Question 2

What does the following code do?

Action openAction = new AbstractAction( "Open..." ) {
public void actionPerformed( ActionEvent e ) {
doOpen();
}
};

JButton openButton = new JButton( openAction );

Select one or more:

a. This code creates an Action that represents the opening of a file in the doOpen() instance method.
b. This code creates a button from the Action.
c. This code creates a menu item from the Action.
d. This code reads a text file.

The correct answer is: This code creates an Action that represents the opening of a file in the doOpen() instance method., This code creates a button from the Action., This code creates a menu item from the Action.

Question 3

Which of the following code is correct to create an instance of ResourceBundle?

Select one:

a. ResourceBundle.getBundle();
b. ResourceBundle.getBundle(locale);
c. ResourceBundle.getBundle(resourcefilename);
d. None of the above;

Question 4

Which of the following code displays the numbers with at least two digits before and after the decimal point?

a.
NumberFormat numberForm = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)numberForm;
df.applyPattern("00.00");

b.
NumberFormat numberForm = NumberFormat.getNumberInstance();
numberForm.setMaximumFractionDigits(2);
numberForm.setMinimumFractionDigits(2);

c.
NumberFormat numberForm = NumberFormat.getNumberInstance();
numberForm.setMaximumFractionDigits(2);

d.
a and b.

Select one:
a. Correct
b.
c.
d.

Question 5

How do you create a locale for the United States?

Select one:
a. new Locale("en", "US");
b. new Locale("US", "en");
c. Locale.US;
d. a and c;

The correct answer is: a and c;

Question 6

Which statements about Preferences are true?

Select one or more:

a. Preferences are best saved in a file in the user’s home directory.
b. Preferences represent a snapshot of a program saved between sessions.
c. To handle preferences, Java provides a class Preferences in the java.util.prefs package.
d. Every time the program starts up, it reads the preferences, if any are available. Every time the program terminates, it saves the preferences.

The correct answer is: Preferences represent a snapshot of a program saved between sessions., To handle preferences, Java provides a class Preferences in the java.util.prefs package., Every time the program starts up, it reads the preferences, if any are available. Every time the program terminates, it saves the preferences.

Question 7

To be a listener for ActionEvent, an object must be an instance of …

Select one:

a. ActionEvent
b. ActionListener
c. EventObject
d. WindowListener
e. WindowEvent

Question 8

Which of the following statements are true?

Select one or more:

a. Dialog boxes are defined by subclasses of the class JDialog.
b. The main difference between JDialogs and JFrames is that a dialog box has a parent, which if closed, causes the dialog box to closes, too.
c. When a modeless dialog is put up on the screen, the rest of the application is blocked until the dialog box is dismissed.
d. Modal dialog boxes are like independent windows, since they can stay on the screen while the user interacts with other windows.

The correct answer is: Dialog boxes are defined by subclasses of the class JDialog., The main difference between JDialogs and JFrames is that a dialog box has a parent, which if closed, causes the dialog box to closes, too.

### Self Quiz 6

Which of the following statements are true?

Select one or more:

a. A socket is a kind of opening.
b. A socket represents one endpoint of a network connection.
c. A program uses a socket to communicate with another program over the network.
d. Data written by a program to the socket at one end of the connection is transmitted to the socket on the other end of the connection, where it can be read by the program at that end.

The correct answer is: A socket is a kind of opening., A socket represents one endpoint of a network connection., A program uses a socket to communicate with another program over the network., Data written by a program to the socket at one end of the connection is transmitted to the socket on the other end of the connection, where it can be read by the program at that end.

Question 2

What does this code do?

import java.io.*;
// (TextReader.class must be available to this program.)

public static void main(String[] args) {
try {
for (int lineCt = 0; lineCt < 10; lineCt++)) {
String line = in.getln();
System.out.println(line);
}
}
catch (Exception e) {
System.out.println("Error: " + e);
}
}

Select one:
a. This code accesses a remote computer and requests 10 HTML pages.
b. This code displays the first ten lines from a text file. The lines are written to standard output.
c. This code reads a file name, 10 characters long from a graphic file chooser dialog box.

The correct answer is: This code displays the first ten lines from a text file. The lines are written to standard output.

Question 3

The class named URL resides in the java.io package. Which of the following statements describe URL?

Select one or more:

a. A URL is an address for a web page (or other information) on the Internet.
b. A URL constructor creates an Address field in a Web browser.
c. A URL object represents a Universal Resource Locator.
d. Once you have a URL object, you can call its openConnection() method to access the information at the url address that it represents.

The correct answer is: A URL is an address for a web page (or other information) on the Internet., A URL object represents a Universal Resource Locator., Once you have a URL object, you can call its openConnection() method to access the information at the url address that it represents.

Question 4

The server listens for a connection request from a client using the following statement:

Select one:

a. Socket s = new Socket(ServerName, port);
b. Socket s = serverSocket.accept()
c. Socket s = serverSocket.getSocket()
d. Socket s = new Socket(ServerName);

The correct answer is: Socket s = serverSocket.accept()

Question 5

Which of the following statements describe a client/server model ?

Select one or more:

a. Computer transactions using the client/server model are very common.
b. Client/server describes the relationship between two computer programs in which one program, the server, makes a service request from another program, the client, which fulfills the request.
c. Although the client/server idea can be used by programs within a single computer, it is a more important idea in a network.
d. In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across different locations.
e. Client/server computing or networking is a distributed application architecture that partitions tasks or work loads between service providers (servers) and service requesters, called clients.

The correct answer is: Computer transactions using the client/server model are very common., Although the client/server idea can be used by programs within a single computer, it is a more important idea in a network., In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across different locations., Client/server computing or networking is a distributed application architecture that partitions tasks or work loads between service providers (servers) and service requesters, called clients.

Question 6

To create an InputStream to read from a file on a Web server, you use the class __________.

Select one:
a. URL
b. Server
c. ServerSocket
d. ServerStream

Question 7

Consider the following code:

BufferedImage OSC = new BufferedImage(32,32,BufferedImage.TYPE_INT_RGB);

Select one or more:

a. A BufferedImage is a region in memory that can be used as a drawing surface.
b. In this statement, the image that is created is 32 pixels wide and 32 pixels high, and the color of each pixel is an RGB color that has red, green, and blue components in the range 0 to 255.
c. The picture in a BufferedImage can easily be copied into a graphics context g by calling one of the g.drawImage methods.
d. The image drawn here is so small, it seems likely that is going to be used to define an ImageIcon.

The correct answer is: A BufferedImage is a region in memory that can be used as a drawing surface., In this statement, the image that is created is 32 pixels wide and 32 pixels high, and the color of each pixel is an RGB color that has red, green, and blue components in the range 0 to 255., The picture in a BufferedImage can easily be copied into a graphics context g by calling one of the g.drawImage methods., The image drawn here is so small, it seems likely that is going to be used to define an ImageIcon.

Question 8

Which of these statements describe the FontMetrics class?

Select one or more:

a. FontMetrics resides in the java.io package.
b. The FontMetrics(Font font)constructor creates a new FontMetrics object for finding out sizes of characters and strings that are drawn in a specific font.
c. The font is specified when the FontMetrics object is created.
d. If fm is a variable of type FontMetrics, then, for example, fm.stringWidth(str) gives the width of the string str and fm.getHeight() is the usual amount of vertical space allowed for one line of text.

The correct answer is: The FontMetrics(Font font)constructor creates a new FontMetrics object for finding out sizes of characters and strings that are drawn in a specific font., The font is specified when the FontMetrics object is created., If fm is a variable of type FontMetrics, then, for example, fm.stringWidth(str) gives the width of the string str and fm.getHeight() is the usual amount of vertical space allowed for one line of text.

Question 9

Interaliasing ….

Select one or more:

a. Is intended to make an image look fuzzier.
b. Is the smoothing of the image roughness caused by aliasing
c. Is achieved by adjusting pixel positions or setting pixel intensities so that there is a more gradual transition between the color of a line and the background color.
d. Makes images look perfect.

The correct answer is: Is the smoothing of the image roughness caused by aliasing, Is achieved by adjusting pixel positions or setting pixel intensities so that there is a more gradual transition between the color of a line and the background color.

Question 10

How is the ButtonGroup class used?

Select one or more:

a. A ButtonGroup object is used with a set of radio buttons (or radio button menu items), to make sure that at most one of the radio buttons in the group can be selected at any given time.
b. To use the ButtonGroup class, you have to create a ButtonGroup object, grp. Then each radio button, rb, that is supposed to be part of the group is added to the group by calling grp.add(rb). Nothing further needs to be done with the ButtonGroup object.
c. Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those buttons turns on all other buttons in the group.

### Self Quiz 5

Which of these statements is true?

a. The hash code of an object is an integer that tells where that object should be stored in a hash table.

b. A hash table is an array of linked lists. When an object is stored in a hash table, it is added to one of these linked lists.

c. The object's hash code is the index of the position in the array where the object is stored.

d. All objects with the same hash code go into the same linked list.

e. In Java, every object obj has a method obj.hashCode() that is used to compute hash codes for the object.

f. If the object is to be stored in a hash table of size N, then the hash code that is used for the object is Math.abs(obj.hashCode())%N.

Select one or more:
a. Correct
b. Correct
c. Correct
d. Correct
e. Correct
f. Correct

The correct answer is: a., b., c., d., e., f.

Question 2

Which of the data types below does not allow duplicates?

Select one:
a. List
b. Vector
c. Stack
d. Set

Question 3

Which of the following data types do not have iterators?

Select one:
a. HashSet
b. TreeSet
c. Map
d. ArrayList

Question 4

Given the following code:

public class Test {
public static void main(String[] args) {
Map map = new HashMap();
map.put("123", "John Smith");
map.put("111", "George Smith");
map.put("123", "Steve Yao");
map.put("222", "Steve Yao");
}
}
Which statement is correct?

Select one:

a. After all the four entries are added to the map, "123" is a key that corresponds to the value "John Smith".
b. After all the four entries are added to the map, "123" is a key that corresponds to the value "Steve Yao".
c. After all the four entries are added to the map, "Steve Yao" is a key that corresponds to the value "222".
d. After all the four entries are added to the map, "John Smith" is a key that corresponds to the value "123".
e. A runtime error occurs because two entries with the same key "123" are added to the map.

The correct answer is: After all the four entries are added to the map, "123" is a key that corresponds to the value "Steve Yao".

Question 5

You can use the methods in the Collections class to:

Select one or more:

a. find the maximum object in a collection based on the compareTo method.
b. find the maximum object in a collection using a Comparator object.
c. sort a collection.
d. shuffle a collection.
e. do a binary search on a collection.

The correct answer is: find the maximum object in a collection based on the compareTo method., find the maximum object in a collection using a Comparator object.

Question 6

The Collection interface is the base interface for …

Select one or more:

a. Set
b. List
c. ArrayList
e. Map

Question 7

The Map is the base interface for …

Select one or more:

a. TreeMap
b. HashMap
d. ArrayList

Question 8

Which of the following statements are true?

Select one or more:

a. The Collection interface is the root interface for manipulating a collection of objects.
b. The Collection interface provides the basic operations for adding and removing elements in a collection.
c. The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface.
d. Some of the methods in the Collection interface cannot be implemented in the concrete subclass. In this case, the method would throw java.lang.UnsupportedOperationException, a subclass of RuntimeException.
e. All interfaces and classes in the Collections framework are declared using generic type in JDK 1.5.

The correct answer is: The Collection interface is the root interface for manipulating a collection of objects., The Collection interface provides the basic operations for adding and removing elements in a collection., The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface., Some of the methods in the Collection interface cannot be implemented in the concrete subclass. In this case, the method would throw java.lang.UnsupportedOperationException, a subclass of RuntimeException., All interfaces and classes in the Collections framework are declared using generic type in JDK 1.5.

Question 9

To store non-duplicated objects in the order in which they are inserted, use ….

Select one:

a. HashSet
c. TreeSet
d. ArrayList

Question 10

Which of the following statements are true?

Select one or more:

a. The Comparable interface contains the compareTo method with the signature "public int compareTo(Object)".
b. The Comparator interface contains the compare method with the signature "public int compare(Object, Object)".
c. A Comparable object can compare this object with the other object.
d. A Comparator object contains the compare method that compares two objects.

The correct answer is: The Comparable interface contains the compareTo method with the signature "public int compareTo(Object)"., The Comparator interface contains the compare method with the signature "public int compare(Object, Object)"., A Comparable object can compare this object with the other object., A Comparator object contains the compare method that compares two objects.

Question 11

Which of the following statements are true?

Select one or more:

a. An ArrayList can grow automatically.
b. An ArrayList can shrink automatically.
c. You can reduce the capacity of an ArrayList by invoking the trimToSize() method on the list.
d. You can reduce the capacity of a LinkedList by invoking the trimToSize() method on the list.

The correct answer is: An ArrayList can grow automatically., You can reduce the capacity of an ArrayList by invoking the trimToSize() method on the list.

Question 12

Which of the following are correct methods in Map?

Select one or more:

a. put(Object key, Object value)
b. put(Object value, Object key)
c. get(Object key)
d. get(int index)

The correct answer is: put(Object key, Object value), get(Object key)