Java Final Exam

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/148

flashcard set

Earn XP

Description and Tags

COP 3809 Advanced Topics in Programming: Chapters 16, 19, 32, 33, 34

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

149 Terms

1
New cards

To create a label with the specified text, use __________.

A. new Labelled();

B. new Label();

C. new Labelled(text);

D. new Label(text);

D. new Label(text);

2
New cards

To set a red color for the text in the label lbl, use _________.

A. lbl.setFill(Color.red);

B. lbl.setTextFill(Color.red);

C. lbl.setFill(Color.RED);

D. lbl.setTextFill(Color.RED);

D. lbl.setTextFill(Color.RED);

3
New cards

__________ are properties in Labelled.

A. alignment

B. contentDisplay

C. graphic

D. text

E. underline

A. alignment

B. contentDisplay

C. graphic

D. text

E. underline

4
New cards

To set the node to the right of the text in a label lbl, use _______.

A. lbl.setContentDisplay(ContentDisplay.TOP);

B. lbl.setContentDisplay(ContentDisplay.BOTTOM);

C. lbl.setContentDisplay(ContentDisplay.LEFT);

D. lbl.setContentDisplay(ContentDisplay.RIGHT);

D. lbl.setContentDisplay(ContentDisplay.RIGHT);

5
New cards

__________ is a superclass for Button.

A. Label

B. Labelled

C. ButtonBase

D. Control

E. Node

B. Labelled

C. ButtonBase

D. Control

E. Node

6
New cards

__________ is a superclass for Label.

A. Scene

B. Labelled

C. ButtonBase

D. Control

E. Node

B. Labelled

D. Control

E. Node

7
New cards

The setOnAction method is defined in _________.

A. Label

B. Labelled

C. Node

D. ButtonBase

E. Button

D. ButtonBase

8
New cards

Analyze the following code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Test extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    HBox pane = new HBox(5);
    Image usIcon = new
      Image("http://www.cs.armstrong.edu/liang/image/usIcon.gif");
    Button bt1 = new Button("Button1", new ImageView(usIcon));
    Button bt2 = new Button("Button2", new ImageView(usIcon));
    pane.getChildren().addAll(bt1, bt2);
    
    Scene scene = new Scene(pane, 200, 250);
    primaryStage.setTitle("Test"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }

  /**
   * The main method is only needed for the IDE with limited JavaFX
   * support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}

A. Two buttons displayed with the same icon.

B. Only bt2 displays the icon and bt1 does not display the icon.

C. Only bt1 displays the icon and bt2 does not display the icon.

D. Two buttons displayed with different icons.

A. Two buttons displayed with the same icon.

9
New cards

Analyze the following code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Test extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    StackPane pane = new StackPane();
    Button bt1 = new Button("Java");
    Button bt2 = new Button("Java");
    Button bt3 = new Button("Java");
    Button bt4 = new Button("Java");
    pane.getChildren().addAll(bt1, bt2, bt3, bt4);
    
    Scene scene = new Scene(pane, 200, 250);
    primaryStage.setTitle("Test"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }

  /**
   * The main method is only needed for the IDE with limited JavaFX
   * support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}

A. One button is displayed with the text "Java".

B. Two buttons are displayed with the same text "Java".

C. Three buttons are displayed with the same text "Java".

D. Four buttons are displayed with the same text "Java".

A. One button is displayed with the text "Java".

10
New cards

Analyze the following code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Test extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    Pane pane = new FlowPane();
    Button bt1 = new Button("Java");
    Button bt2 = new Button("Java");
    Button bt3 = new Button("Java");
    Button bt4 = new Button("Java");
    pane.getChildren().addAll(bt1, bt2, bt3, bt4);
    
    Scene scene = new Scene(pane, 200, 250);
    primaryStage.setTitle("Test"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }

  /**
   * The main method is only needed for the IDE with limited JavaFX
   * support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}

A. One button is displayed with the text "Java".

B. Two buttons are displayed with the same text "Java".

C. Three buttons are displayed with the same text "Java".

D. Four buttons are displayed with the same text "Java".

D. Four buttons are displayed with the same text "Java".

11
New cards

_________ checks whether the CheckBox chk is selected.

A. chk.getSelected()

B. chk.selected()

C. chk.isSelected().

D. chk.select()

C. chk.isSelected().

12
New cards

Which of the following statements are true?

A. CheckBox inherits from ButtonBase.

B. CheckBox inherits from Button.

C. CheckBox inherits from Labelled.

D. CheckBox inherits from Control.

E. CheckBox inherits from Node.

A. CheckBox inherits from ButtonBase.

C. CheckBox inherits from Labelled.

D. CheckBox inherits from Control.

E. CheckBox inherits from Node

13
New cards

Which of the following statements are true?

A. RadioButton inherits from ButtonBase.

B. RadioButton inherits from Button.

C. RadioButton inherits from Labelled.

D. RadioButton inherits from Control.

E. RadioButton inherits from Node.

A. RadioButton inherits from ButtonBase.

C. RadioButton inherits from Labelled.

D. RadioButton inherits from Control.

E. RadioButton inherits from Node.

14
New cards

_________ checks whether the RadioButton rb is selected.

A. rb.getSelected()

B. rb.selected()

C. rb.isSelected().

D. rb.select()

C. rb.isSelected().

15
New cards

Analyze the following code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Test extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    Pane pane = new FlowPane();
    
    ToggleGroup group = new ToggleGroup();
    RadioButton rb1 = new RadioButton("Java");
    RadioButton rb2 = new RadioButton("C++");
    pane.getChildren().addAll(rb1, rb2);
    
    Scene scene = new Scene(pane, 200, 250);
    primaryStage.setTitle("Test"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }

  /**
   * The main method is only needed for the IDE with limited JavaFX
   * support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}

A. The program displays two radio buttons. The two radio buttons are grouped.

B. The program displays one radio button with text Java.

C. The program displays two radio buttons. The two radio buttons are not grouped.

D. The program displays one radio button with text C++.

C. The program displays two radio buttons. The two radio buttons are not grouped.

16
New cards

Which of the following statements are true?

A. TextField inherits from TextInputControl.

B. TextField inherits from ButtonBase.

C. TextField inherits from Labelled.

D. TextField inherits from Control.

E. TextField inherits from Node.

A. TextField inherits from TextInputControl.

D. TextField inherits from Control.

E. TextField inherits from Node.

17
New cards

The properties ___________ can be used in a TextField.

A. text

B. editable

C. alignment

D. prefColumnCount

E. onAction

A. text

B. editable

C. alignment

D. prefColumnCount

E. onAction

18
New cards

Which of the following statements are true?

A. You can specify a horizontal text alignment in a text field.

B. You can specify the number of columns in a text field.

C. You can disable editing on a text field.

D. You can create a text field with a specified text.

A. You can specify a horizontal text alignment in a text field.

B. You can specify the number of columns in a text field.

C. You can disable editing on a text field.

D. You can create a text field with a specified text.

19
New cards

The method __________ gets the contents of the text field tf.

A. tf.getText(s)

B. tf.getText()

C. tf.getString()

D. tf.findString()

B. tf.getText()

20
New cards

Which of the following statements are true?

A. PasswordField inherits from TextInputControl.

B. PasswordField inherits from TextField.

C. PasswordField inherits from Labelled.

D. PasswordField inherits from Control.

E. PasswordField inherits from Node.

A. PasswordField inherits from TextInputControl.

B. PasswordField inherits from TextField.

D. PasswordField inherits from Control.

E. PasswordField inherits from Node.

21
New cards

The method __________ appends a string s into the text area ta.

A. ta.setText(s)

B. ta.appendText(s)

C. ta.append(s)

D. ta.insertText(s)

B. ta.appendText(s)

22
New cards

Which of the following statements are true?

A. You can specify a horizontal text alignment in a text area.

B. You can specify the number of columns in a text area.

C. You can disable editing on a text area.

D. You can create a text field with a specified text area.

E. You can specify the number of rows in a text area.

B. You can specify the number of columns in a text area.

C. You can disable editing on a text area.

D. You can create a text field with a specified text area.

E. You can specify the number of rows in a text area.

23
New cards

To wrap a line in a text area ta, invoke ____________.

A. ta.setLineWrap(false)

B. ta.setLineWrap(true)

C. ta.WrapLine()

D. ta.wrapText()

E. ta.setWrapText(true)

E. ta.setWrapText(true)

24
New cards

To wrap a line in a text area jta on words, invoke ____________.

A. jta.setWrapStyleWord(false)

B. jta.setWrapStyleWord(true)

C. jta.wrapStyleWord()

D. jta.wrapWord()

B. jta.setWrapStyleWord(true)

25
New cards

Which of the following statements are true?

A. TextArea inherits from TextInputControl.

B. TextArea inherits from TextField.

C. TextArea inherits from Labelled.

D. TextArea inherits from Control.

E. TextArea inherits from Node.

A. TextArea inherits from TextInputControl.

D. TextArea inherits from Control.

E. TextArea inherits from Node.

26
New cards

How many items can be added into a ComboBox object?

A. 0

B. 1

C. 2

D. Unlimited

D. Unlimited

27
New cards

How many items can be selected from a ComboBox at a time?

A. 0

B. 1

C. 2

D. Unlimited

B. 1

28
New cards

_______________ returns the selected item on a ComboBox cbo.

A. cbo.getSelectedIndex()

B. cbo.getSelectedItem()

C. cbo.getSelectedIndices()

D. cbo.getSelectedItems()

E. cbo.getValue()

E. cbo.getValue()

29
New cards

The method __________ adds an item s into a ComboBox cbo.

A. cbo.add(s)

B. cbo.addChoice(s)

C. cbo.addItem(s)

D. cbo.addObject(s)

E. cbo.getItems().add(s)

E. cbo.getItems().add(s)

30
New cards

Which of the following statements are true?

A. ComboBox inherits from ComboBoxBase.

B. ComboBox inherits from ButtonBase.

C. ComboBox inherits from Labelled.

D. ComboBox inherits from Control.

E. ComboBox inherits from Node.

A. ComboBox inherits from ComboBoxBase.

D. ComboBox inherits from Control.

E. ComboBox inherits from Node.

31
New cards

You can use the _________ properties in a ComboBox.

A. value

B. editable

C. onAction

D. items

E. visibleRowCount

A. value

B. editable

C. onAction

D. items

E. visibleRowCount

32
New cards

____________ are properties for a ListView.

A. items

B. orientation

C. selectionModel

D. visibleRowCount

E. onAction

A. items

B. orientation

C. selectionModel

33
New cards

Which of the following statements are true?

A. ListView inherits from ComboBoxBase.

B. ListView inherits from ButtonBase.

C. ListView inherits from Labelled.

D. ListView inherits from Control.

E. ListView inherits from Node.

D. ListView inherits from Control.

E. ListView inherits from Node.

34
New cards

The statement for registering a listener for processing list view item change is ___________.

A. lv.getItems().addListener(e -> {processStatements});

B. lv.addListener(e -> {processStatements});

C. lv.getSelectionModel().selectedItemProperty().addListener(e -> {processStatements});

D. lv.getSelectionModel().addListener(e -> {processStatements});

C. lv.getSelectionModel().selectedItemProperty().addListener(e -> {processStatements});

35
New cards

__________ are properties of ScrollBar.

A. value

B. min

C. max

D. orientation

E. visibleAmount

A. value

B. min

C. max

D. orientation

E. visibleAmount

36
New cards

The statement for registering a listener for processing scroll bar value change is ___________.

A. sb.addListener(e -> {processStatements});

B. sb.getValue().addListener(e -> {processStatements});

C. sb.valueProperty().addListener(e -> {processStatements});

D. sb.getItems().addListener(e -> {processStatements});

C. sb.valueProperty().addListener(e -> {processStatements});

37
New cards

__________ are properties of ScrollSlider.

A. value

B. min

C. max

D. orientation

E. visibleAmount

A. value

B. min

C. max

D. orientation

E. visibleAmount

38
New cards

The statement for registering a listener for processing slider change is ___________.

A. sl.addListener(e -> {processStatements});

B. sl.getValue().addListener(e -> {processStatements});

C. sl.valueProperty().addListener(e -> {processStatements});

D. sl.getItems().addListener(e -> {processStatements});

C. sl.valueProperty().addListener(e -> {processStatements});

39
New cards

Which of the following statements are true?

A. A Media can be shared by multiple MediaPlayer.

B. A MediaPlayer can be shared by multiple MediaView.

C. A MediaView can be placed into multiple Pane.

D. A Media can be downloaded from a URL.

A. A Media can be shared by multiple MediaPlayer.

B. A MediaPlayer can be shared by multiple MediaView.

D. A Media can be downloaded from a URL.

40
New cards

You can use the methods _________ to control a MediaPlayer.

A. start().

B. stop().

C. pause().

D. play().

C. pause().

D. play().

41
New cards

You can use the properties _________ to control a MediaPlayer.

A. autoPlay

B. currentCount

C. cycleCount

D. mute

E. volume

A. autoPlay

B. currentCount

C. cycleCount

D. mute

E. volume

42
New cards

You can use the properties _________ in a MediaView.

A. x

B. y

C. mediaPlayer

D. fitWidth

E. fitHeight

A. x

B. y

C. mediaPlayer

D. fitWidth

E. fitHeight

43
New cards

Which of the following statements is correct?

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.

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.

44
New cards

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

A. <String>

B. <?>

C. <Date>

D. <E>

C. <Date>

45
New cards

Suppose ArrayList<Double> list = new ArrayList<>(). Which of the following statements are correct?

A. list.add(5.5); // 5.5 is automatically converted to Double.valueOf(5.5)

B. list.add(3.0); // 3.0 is automatically converted to Double.vauleOf(3.0)

C. Double doubleObject = list.get(0); // No casting is needed

D. double d = list.get(1); // Automatically converted to double

A. list.add(5.5); // 5.5 is automatically converted to Double.valueOf(5.5)

B. list.add(3.0); // 3.0 is automatically converted to Double.vauleOf(3.0)

C. Double doubleObject = list.get(0); // No casting is needed

D. double d = list.get(1); // Automatically converted to double

46
New cards

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

A. list.add("Red");

B. list.add(Integer.valueOf(100));

C. list.add(new java.util.Date());

D. list.add(new ArrayList());

A. list.add("Red");

B. list.add(Integer.valueOf(100));

C. list.add(new java.util.Date());

D. list.add(new ArrayList());

47
New cards

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

A. list.add("Red");

B. list.add(Integer.valueOf(100));

C. list.add(new java.util.Date());

D. list.add(new ArrayList());

A. list.add("Red");

48
New cards

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

A. public class A<E> { ... }

49
New cards

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

B. public class A<E, F> { ... }

50
New cards

To declare an interface named A with a generic type, use

A. public interface A<E> { ... }

B. public interface A<E, F> { ... }

C. public interface A(E) { ... }

D. public interface A(E, F) { ... }

A. public interface A<E> { ... }

51
New cards

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

B. public interface A<E, F> { ... }

52
New cards

To create a list to store integers, use

A. ArrayList<Object> list = new ArrayList<>();

B. ArrayList<Integer> list = new ArrayList<>();

C. ArrayList<int> list = new ArrayList<int>();

D. ArrayList<Number> list = new ArrayList<>();

B. ArrayList<Integer> list = new ArrayList<>();

53
New cards

The method header is left blank in the following code. Fill in the header.

public class GenericMethodDemo {
  public static void main(String[] args ) {
    Integer[] integers = {1, 2, 3, 4, 5};
    String[] strings = {"London", "Paris", "New York", "Austin"};

    print(integers);
    print(strings);
  }

  __________________________________________ {
    for (int i = 0; i < list.length; i++)
      System.out.print(list[i] + " ");
    System.out.println();
  }
}

A. public static void print(Integer[] list)

B. public static void print(String[] list)

C. public static void print(int[] list)

D. public static void print(Object[] list)

E. public static <E> void print(E[] list)

D. public static void print(Object[] list)

E. public static <E> void print(E[] list)

54
New cards

To create a generic type bounded by Number, use

A. <E extends Number>

B. <E extends Object>

C. <E>

D. <E extends Integer>

A. <E extends Number>

55
New cards

Which of the following statements are correct?

A. Comparable<String> c = new String("abc");

B. Comparable<String> c = "abc";

C. Comparable<Integer> c = 23;

D. Comparable<Double> c = 3.4;

A. Comparable<String> c = new String("abc");

B. Comparable<String> c = "abc";

C. Comparable<Integer> c = 23;

D. Comparable<Double> c = 3.4;

56
New cards

Fill in the most appropriate code in the two blanks in the following class.

public class MyInt implements _______ {
  int id;

  public MyInt(int id) {
    this.id = id;
  }

  public String toString() {
    return String.valueOf(id);
  }

  public int compareTo(_______ arg0) {
    if (id > arg0.id)
      return 1;
    else if (id < arg0.id)
      return -1;
    else
      return 0;
  }
}

A. Comparable / Object

B. Comparable<MyInt> / MyInt

C. Comparable<MyInt> / Object

D. Comparable / MyInt

B. Comparable<MyInt> / MyInt

57
New cards

Which of the following declarations use raw type?

A. ArrayList<Object> list = new ArrayList<>();

B. ArrayList<String> list = new ArrayList<>();

C. ArrayList<Integer> list = new ArrayList<>();

D. ArrayList list = new ArrayList();

D. ArrayList list = new ArrayList();

58
New cards

If you use the javac -Xlint:unchecked command to compile a program that contains raw type, what would the compiler do?

A. report compile error

B. report warning and generate a class file

C. report warning without generating a class file

D. no error and generate a class file

B. report warning and generate a class file

59
New cards

Is ArrayList<Integer> a subclass of ArrayList<Object>?

A. Yes

B. No

B. No

60
New cards

Which of the following can be used to replace YYYYYYYY in the following code?

public class WildCardDemo3 {
  public static void main(String[] args) {
    GenericStack<String> stack1 = new GenericStack<>();
    GenericStack<Object> stack2 = new GenericStack<>();
    stack2.push("Java");
    stack2.push(2);
    stack1.push("Sun");
    add(stack1, stack2);
    WildCardDemo2.print(stack2);
  }

  public static <T> void add(GenericStack<T> stack1,
      GenericStack<YYYYYYYY> stack2) {
    while (!stack1.isEmpty())
      stack2.push(stack1.pop());
  }
}

A. ? super Object

B. ? super T

C. ? extends T

D. ? extends Object

B. ? super T

61
New cards

Which of the following can be used to replace YYYYYYYY in the following code?

public class WildCardDemo3 {
  public static void main(String[] args) {
    GenericStack<String> stack1 = new GenericStack<>();
    GenericStack<Object> stack2 = new GenericStack<>();
    stack2.push("Java");
    stack2.push(2);
    stack1.push("Sun");
    add(stack1, stack2);
    WildCardDemo2.print(stack2);
  }

  public static <T> void YYYYYYYY {
    while (!stack1.isEmpty())
      stack2.push(stack1.pop());
  }
}

A. add(GenericStack<T> stack1, GenericStack<T> stack2)

B. add(GenericStack<? extends T> stack1, GenericStack<T> stack2)

C. add(GenericStack<T> stack1, GenericStack<? super T> stack2)

D. add(GenericStack<T> stack1, GenericStack<Object> stack2)

B. add(GenericStack<? extends T> stack1, GenericStack<T> stack2)

C. add(GenericStack<T> stack1, GenericStack<? super T> stack2)

D. add(GenericStack<T> stack1, GenericStack<Object> stack2)

62
New cards

Is ArrayList<Integer> a subclass of ArrayList<?>?

A. Yes

B. No

A. Yes

63
New cards

Is ArrayList<Integer> a subclass of ArrayList<? extends Number>?

A. Yes

B. No

A. Yes

64
New cards

Is ArrayList<Number> a subclass of ArrayList<? extends Number>?

A. Yes

B. No

A. Yes

65
New cards

Is ArrayList<?> same as ArrayList<? extends Object>?

A. Yes

B. No

A. Yes

66
New cards

Does <? super Number> represent a superclass of Number?

A. Yes

B. No

A. Yes

67
New cards

ArrayList<String> and ArrayList<Integer> are two types. Does the JVM load two classes ArrayList<String> and ArrayList<Integer>?

A. Yes

B. No

B. No

68
New cards

Which of the following statements are true?

A. Generic type information is present at compile time.

B. Generic type information is not present at runtime.

C. You cannot create an instance using a generic class type parameter.

D. You cannot create an array using a generic class type parameter.

E. You cannot create an array using a generic class.

A. Generic type information is present at compile time.

B. Generic type information is not present at runtime.

C. You cannot create an instance using a generic class type parameter.

D. You cannot create an array using a generic class type parameter.

E. You cannot create an array using a generic class.

69
New cards

If E is a generic type for a class, can E be referenced from a static method?

A. Yes

B. No

B. No

70
New cards

Analyze the following code:

public class Test implements Runnable {
  public static void main(String[] args) {
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    System.out.println("test");
  }
}

A. The program does not compile because this cannot be referenced in a static method.

B. The program compiles fine, but it does not print anything because t does not invoke the run() method.

C. The program compiles and runs fine and displays test on the console.

D. None of the above.

A. The program does not compile because this cannot be referenced in a static method.

71
New cards

What is the output of the following code?

// Test.java: Define threads using the Thread class
public class Test {
  /** Main method */
  public static void main(String[] args) {
    new Test();
  }

  public Test() {
    // Create threads
    PrintChar printA = new PrintChar('a', 4);
    PrintChar printB = new PrintChar('b', 4);

    // Start threads
    printA.run();
    printB.run();
  }

  class PrintChar implements Runnable {
    private char charToPrint; // The character to print
    private int times; // The times to repeat

    /** Construct a thread with specified character and number of
       times to print the character
     */
    public PrintChar(char c, int t) {
      charToPrint = c;
      times = t;
    }

    /** Override the run() method to tell the system
       what the thread will do
     */
    public void run() {
      for (int i = 0; i < times; i++)
        System.out.print(charToPrint);
    }
  }
}

A. aaaaabbbbb

B. bbbbbaaaaa

C. character a and b are randomly printed

D. ababababab

A. aaaaabbbbb

72
New cards

Analyze the following code:

public abstract class Test implements Runnable {
  public void doSomething() {
  };
}

A. The program will not compile because it does not implement the run() method.

B. The program will not compile because it does not contain abstract methods.

C. The program compiles fine.

D. None of the above.

C. The program compiles fine.

73
New cards

Analyze the following code:

public class Test implements Runnable {
  public static void main(String[] args) {
    Test t = new Test();
    t.start();
  }

  public void run() {
  }
}

A. The program does not compile because the start() method is not defined in the Test class.

B. The program compiles, but it does not run because the start() method is not defined.

C. The program compiles, but it does not run because the run() method is not implemented.

D. The program compiles and runs fine.

A. The program does not compile because the start() method is not defined in the Test class.

74
New cards

Analyze the following code:

public class Test implements Runnable {
  public static void main(String[] args) {
    Test t = new Test();
  }

  public Test() {
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    System.out.println("test");
  }
}

A. The program has a compilation error because t is defined in both the main() method and the constructor Test().

B. The program compiles fine, but it does not run because you cannot use the keyword this in the constructor.

C. The program compiles and runs and displays nothing.

D. The program compiles and runs and displays test.

D. The program compiles and runs and displays test.

75
New cards

Why does the following class have a syntax error?

import java.applet.*;

public class Test extends Applet implements Runnable {
   public void init() throws InterruptedException {
     Thread t = new Thread(this);
      t.sleep(1000);
   }

   public synchronized void run() {
   }
}

A. The sleep() method is not invoked correctly; it should be invoked as Thread.sleep(1000).

B. You cannot put the keyword synchronized in the run() method.

C. The init() method is defined in the Applet class, and it is overridden incorrectly because it cannot claim exceptions in the subclass.

D. The sleep() method should be put in the try-catch block. This is the only reason for the compilation failure.

C. The init() method is defined in the Applet class, and it is overridden incorrectly because it cannot claim exceptions in the subclass.

76
New cards

Which of the following expressions must be true if you create a thread using Thread = new Thread(object)?

A. object instanceof Thread

B. object instanceof Frame

C. object instanceof Applet

D. object instanceof Runnable

D. object instanceof Runnable

77
New cards

Which of the following methods in the Thread class are deprecated?

A. yield()

B. stop();

C. resume();

D. suspend();

B. stop();

C. resume();

D. suspend();

78
New cards

You can use the _________ method to temporarily release time for other threads.

A. sleep(long milliseconds)

B. yield()

C. stop()

D. suspend()

A. sleep(long milliseconds)

B. yield()

79
New cards

Which of the following statements are defined in the Object class?

A. sleep(long milliseconds)

B. wait()

C. notify()

D. notifyAll()

E. toString()

B. wait()

C. notify()

D. notifyAll()

E. toString()

80
New cards

You can use the ________ method to force one thread to wait for another thread to finish.

A. sleep(long milliseconds)

B. yield()

C. stop()

D. suspend()

E. join()

E. join()

81
New cards

When you run the following program, what will happen?

public class Test extends Thread {
  public static void main(String[] args) {
    Test t = new Test();
    t.start();
    t.start();
  }

  public void run() {
    System.out.println("test");
  }
}

A. Nothing is displayed.

B. The program displays test twice.

C. The program displays test once.

D. An illegal java.lang.IllegalThreadStateException may be thrown because you just started thread and thread might have not yet finished before you start it again.

D. An illegal java.lang.IllegalThreadStateException may be thrown because you just started thread and thread might have not yet finished before you start it again.

82
New cards

Which of the following method is a static in java.lang.Thread?

A. run()

B. sleep(long)

C. start()

D. join()

E. setPriority(int)

B. sleep(long)

83
New cards

Which of the following methods in Thread throws InterruptedException?

A. run()

B. sleep(long)

C. start()

D. yield()

E. setPriority(int)

B. sleep(long)

84
New cards

Given the following code, which set of code can be used to replace the comment so that the program displays time to the console every second?

import java.applet.*;
import java.util.*;

public class Test extends Applet implements Runnable {
  public void init() {
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    for(; ;) {
      //display time every second
      System.out.println(new Date().toString());
    }
  }
}

A. try { sleep(1000); } catch(InterruptedException e) { }

B. try { t.sleep(1000); } catch(InterruptedException e) { }

C. try { Thread.sleep(1000); } catch(RuntimeException e) { }

D. try { Thread.sleep(1000); } catch(InterruptedException e) { }

D. try { Thread.sleep(1000); } catch(InterruptedException e) { }

85
New cards

Which of the following statements are true?

A. You can use a timer or a thread to control animation.

B. A timer is a source component that fires an ActionEvent at a 'fixed rate.'

C. The timer and event-handling run on the same event dispatcher thread. If it takes a long time to handle the event, the actual delay time between two events will be longer than the requested delay time.

D. In general, threads are more reliable and responsive than timers.

A. You can use a timer or a thread to control animation.

B. A timer is a source component that fires an ActionEvent at a 'fixed rate.'

C. The timer and event-handling run on the same event dispatcher thread. If it takes a long time to handle the event, the actual delay time between two events will be longer than the requested delay time.

D. In general, threads are more reliable and responsive than timers.

86
New cards

Which of the following statements are true?

A. The javax.swing.SwingUtilities.invokeLater method creates a thread.

B. The javax.swing.SwingUtilities.invokeAndWait method runs the code in the event dispatcher thread.

C. The javax.swing.SwingUtilities.invokeLater method runs the code in the event dispatcher thread and doesn't return until the event-dispatching thread has executed the specified code.

D. GUI event handling is executed in the event dispatcher thread.

B. The javax.swing.SwingUtilities.invokeAndWait method runs the code in the event dispatcher thread.

C. The javax.swing.SwingUtilities.invokeLater method runs the code in the event dispatcher thread and doesn't return until the event-dispatching thread has executed the specified code.

D. GUI event handling is executed in the event dispatcher thread.

87
New cards

Suppose there are three Runnable tasks, task1, task2, task3. How do you run them in a thread pool with 2 fixed threads?

A. new Thread(task1).start(); new Thread(task2).start(); new Thread(task3).start();

B. ExecutorService executor = Executors.newFixedThreadPool(3); executor.execute(task1); executor.execute(task2); executor.execute(task3);

C. ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(task1); executor.execute(task2); executor.execute(task3);

D. ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(task1); executor.execute(task2); executor.execute(task3);

C. ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(task1); executor.execute(task2); executor.execute(task3);

88
New cards

How do you create a cached thread pool?

A. ExecutorService executor = Executors.newCachedThreadPool();

B. ExecutorService executor = Executors.newCachedThreadPool(1);

C. ExecutorService executor = Executors.newCachedThreadPool(2);

D. ExecutorService executor = Executors.newCachedThreadPool(3);

A. ExecutorService executor = Executors.newCachedThreadPool();

89
New cards

The keyword to synchronize methods in Java is __________.

A. synchronize

B. synchronizing

C. synchronized

D. Synchronized

C. synchronized

90
New cards

Which of the following statements are true?

A. A synchronized instance method acquires a lock on the object for which the method was invoked.

B. A synchronized instance method acquires a lock on the class of the object for which the method was invoked.

C. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method.

D. A synchronized statement is placed inside a synchronized block.

A. A synchronized instance method acquires a lock on the object for which the method was invoked.

B. A synchronized instance method acquires a lock on the class of the object for which the method was invoked.

C. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method.

D. A synchronized statement is placed inside a synchronized block.

91
New cards

Which of the following are correct statements to create a Lock?

A. Lock lock = new Lock();

B. Lock lock = new ReentrantLock();

C. Lock lock = new ReentrantLock(true);

D. Lock lock = new ReentrantLock(false);

B. Lock lock = new ReentrantLock();

C. Lock lock = new ReentrantLock(true);

D. Lock lock = new ReentrantLock(false);

92
New cards

Which of the following are correct statements to create a Lock so the longest-wait thread will obtain the lock first?

A. Lock lock = new Lock();

B. Lock lock = new ReentrantLock();

C. Lock lock = new ReentrantLock(true);

D. Lock lock = new ReentrantLock(false);

C. Lock lock = new ReentrantLock(true);

93
New cards

You should always invoke the unlock method in the finally clause.

A. true

B. false

A. true

94
New cards

How do you create a condition on a lock?

A. Condition condition = lock.getCondition();

B. Condition condition = lock.newCondition();

C. Condition condition = Lock.newCondition();

D. Condition condition = Lock.getCondition();

B. Condition condition = lock.newCondition();

95
New cards

Which method on a condition should you invoke to causes the current thread to wait until the condition is signaled?

A. condition.await();

B. condition.wait();

C. condition.waiting();

D. condition.waited();

A. condition.await();

96
New cards

Which method on a condition should you invoke to wake all waiting threads?

A. condition.wake();

B. condition.signal();

C. condition.wakeAll();

D. condition.signalAll();

D. condition.signalAll();

97
New cards

Which of the following statements are true?

A. A condition is associated with a lock.

B. To invoke methods on a condition, the lock must be obtained first.

C. Once you invoke the await method on a condition, the lock is automatically released. Once the condition is right, the thread re-acquires the lock and continues executing.

D. The signal method on a condition causes the lock for the condition to be released.

A. A condition is associated with a lock.

B. To invoke methods on a condition, the lock must be obtained first.

C. Once you invoke the await method on a condition, the lock is automatically released. Once the condition is right, the thread re-acquires the lock and continues executing.

98
New cards

Which of the following statements are true?

A. The wait(), notify(), and notifyAll() methods must be invoked from a synchronized method or a synchronized block.

B. When wait() is invoked, it pauses the thread and releases the lock on the object simultaneously. When the thread is restarted after being notified, the lock is automatically reacquired.

C. The notify() method can wake only one waiting thread.

D. An exception would occur if no thread is waiting on the object when the notify() method is invoked on the object.

D. An exception would occur if no thread is waiting on the object when the notify() method is invoked on the object.

99
New cards

Analyze the following code.

// Test.java: Define threads using the Thread class
import java.util.*;

public class Test {
  private Stack stack = new Stack();
  private int i = 0;

  /** Main method */
  public static void main(String[] args) {
    new Test();
  }

  public Test() {
    // Start threads
    new Producer().start();
    new Consumer().start();
  }

  class Producer extends Thread {
    public void run() {
      while (true) {
          System.out.println("Producer: put " + i);
          stack.push(new Integer(i++));
          synchronized (stack) {
            notifyAll();
          }
      }
    }
  }

  class Consumer extends Thread {
    public void run() {
      while (true) {
        synchronized (stack) {
          try {
            while (stack.isEmpty())
              stack.wait();
            System.out.println("Consumer: get " + stack.pop());
          }
          catch (InterruptedException ex) {
            ex.printStackTrace();
          }
        }
      }
    }
  }
}

A. The program creates two threads: one to add data to the stack and the other to get data from the stack.

B. The program has a compilation error on the notifyAll() method in the Producer class because it is not invoked from the stack object.

C. The program will throw an exception because the notifyAll() method in the Producer class is not invoked from the stack object.

D. The program has a logic error because the lock obtained by the synchronized block for notifyAll in the Producer class is stack and it should be this (i.e., synchronized (this) { notifyAll(); }).

C. The program will throw an exception because the notifyAll() method in the Producer class is not invoked from the stack object.

100
New cards

You can create a blocking queue using _____________.

A. ArrayBlockingQueue

B. LinkedBlockingQueue

C. PriorityBlockingQueue

D. PriorityQueue

A. ArrayBlockingQueue

B. LinkedBlockingQueue

C. PriorityBlockingQueue