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> |
is <adjective> |
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 {
int oneByte = in.read();
while (oneByte >= 0) { // negative value indicates end-of-stream
out.write(oneByte);
oneByte = in.read();
}
}

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
d. Linked 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>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
for (int i = 0; i < list.size(); i++)
     System.out.print(list.remove(i));

Select one:
a. ABCD
b. AB
c. AC
d. AD
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);
        list.add(sample1);
        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 );
 
JMenuItem openCommand = new JMenuItem( 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;

The correct answer is: ResourceBundle.getBundle(resourcefilename);



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.

The correct answer is: a.



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

The correct answer is: ActionListener



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 class TenLinesWithTextReader {

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

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

The correct answer is: URL



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.
d. Typically a button group contains instances of JRadioButton, JRadioButtonMenuItem, or JToggleButton.

The correct answer is: 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., 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., Typically a button group contains instances of JRadioButton, JRadioButtonMenuItem, or JToggleButton.




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
e. LinkedList

The correct answer is: Set



Question 3

Which of the following data types do not have iterators?

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

The correct answer is: Map



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 
d. LinkedList 
e. Map

The correct answer is: Set, List, ArrayList, LinkedList



Question 7

The Map is the base interface for …

Select one or more:

a. TreeMap 
b. HashMap 
c. LinkedHashMap 
d. ArrayList
e. LinkedList

The correct answer is: TreeMap, HashMap, LinkedHashMap



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
b. LinkedHashSet 
c. TreeSet
d. ArrayList
e. LinkedList

The correct answer is: LinkedHashSet



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)


Self Quiz 4

Java’s generic programming does not apply to the primitive types. True or False?

Select one:

True Correct
False

The correct answer is 'True'.



Question 2

Which of the following statements is correct?

Select one or more:

a. Generics can help detect type errors at compile time, thus make programs more robust.
b. Generics can make programs easy to read.
c. Generics can avoid cumbersome castings.
d. Generics can make programs run faster.

The correct answer is: Generics can help detect type errors at compile time, thus make programs more robust., Generics can make programs easy to read., Generics can avoid cumbersome castings.



Question 3

Fill in the code in Comparable______ c = new Date();

a. <String>
b. <?>
c. <Date>
d. <E>

The correct answer is: c.



Question 4

Suppose List list = new ArrayList(). Which of the following operations are correct?

Select one or more:

a. list.add("Red"); 
b. list.add(new Integer(100));
c. list.add(new java.util.Date());
d. list.add(new ArrayList());

The correct answer is: list.add("Red");, list.add(new Integer(100));, list.add(new java.util.Date());, list.add(new ArrayList());



Question 5

Suppose List<String> list = new ArrayList<String>. Which of the following operations are correct?

Select one:

a. list.add("Red"); 
b. list.add(new Integer(100));
c. list.add(new java.util.Date());
d. list.add(new ArrayList());

The correct answer is: list.add("Red");



Question 6

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

Select one:
True 
False

The correct answer is 'True'.



Question 7

To declare a class named A with a generic type, use

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

The correct answer is: a.



Question 8

To declare a class named A with two generic types, use

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

The correct answer is: b.


Question 9

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) { ... }

The correct answer is: b.



Question 10

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>();

The correct answer is: b.