Java 2 Self Quiz 1

Question 1

A switch statement, most often has the form:
switch (expression) {
case constant-1:
statements-1
break;
}

The value of the expression can be:
i. int
ii. short
iii. byte
iv. Primitive char
v. Enum
vi. String
vii. Real number

Select one:
a. iii , iv and v
b. i , ii, iii and iv
c. All, except vi and vii Correct
d. vi and vii
e. All of the types listed

The correct answer is: All, except vi and vii


Question 2

The following code writes out the name of a day of the week depending on the value of day. True or False?

String dayName = null;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
}
System.out.println(dayName);

Select one:

True 
False

The correct answer is 'True'.

Question 3

Given the following piece of code:

class CostCalculationException extends Exception{}
class Item {
       public void calculateCost() throws CostCalculationException {
                //...
                throw new CostCalculationException();
                //...
       }
}
class Company {
        public void payCost(){
                new Item().calculateCost();
      }
}

Which of the following statements is correct?

Select one or more:
a. This code will compile without any problems.
b. This code will compile if in method payCost()you return a boolean instead of void.
c. This code will compile if you add a try-catch block in payCost() 
d. This code will compile if you add throws CostCalculationException in the signature of method payCost(). 

The correct answer is: This code will compile if you add a try-catch block in payCost(), This code will compile if you add throws CostCalculationException in the signature of method payCost().

Question 4

Given the following piece of code:

class Student { public void talk(){} }
public class Test{
          public static void main(String args[]){
                    Student t = null;
                    try {
                           t.talk();
                           } catch(NullPointerException e){
                                   System.out.print("There is a NullPointerException. ");
                           } catch(Exception e){
                                   System.out.print("There is an Exception. ");
                           }
                           System.out.print("Everything ran fine. ");
          }
}

what will be the result?

a. If you run this program, the following is printed:
There is a NullPointerException. Everything ran fine.

b. If you run this program, the following is printed:
There is a NullPointerException.

c. If you run this program, the following is printed:
There is a NullPointerException. There is an Exception.

d. This code will not compile, because in Java there are no pointers.

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

The correct answer is: a.

Question 5

Consider the following code (assume that comments are replaced with real code that works as specified):

public class TestExceptions {

    static void e() {
      // Might cause any of the following unchecked exceptions to be
      // thrown:
      // Ex1, Ex2, Ex3, Ex4
    }
   
    static void April() {
      try {
          e();
      } catch (Ex1 ex) {
          System.out.println("April caught Ex1");
      }
    }
   
    static void March() {
      try {
          April();
      } catch (Ex2 ex) {
          System.out.println("March caught Ex2");
          // now cause exception Ex1 to be thrown
      }
    }
   
    static void February() {
      try {
          March();
      } catch (Ex1 ex) {
          System.out.println("February caught Ex1");
      } catch (Ex3 ex) {
          System.out.println("February caught Ex3");
      }
    }
   
    static void January() {
      try {
          February();
      } catch (Ex4 ex) {
          System.out.println("January caught Ex4");
          // now cause exception Ex1 to be thrown
      } catch (Ex1 ex) {
          System.out.println("January caught Ex1");
      }
    }
   
    public static void main(String[] args) {
        January();
    }
}
Assume now that this program is run four times. The first time, method e throws exception Ex1, the second time, it throws exception Ex2, etc.

What are the results of the four runs (a or b)?

a.

The program prints:
April caught Ex1
The program prints:
March caught Ex2
February caught Ex1
The program prints:
February caught Ex3
The program prints:
January caught Ex4
And execution stops due to an uncaught exception Ex1 thrown in main()
b.

The program prints:
April caught Ex3
The program prints:
March caught Ex2
February caught Ex2
The program prints:
March caught Ex3
The program prints:
January caught Ex4
And execution stops due to an uncaught exception Ex1 thrown in main()


Select one:
a. Correct
b.

The correct answer is: a.

Question 6

Which statements are correct regarding Java’s predefined class called Throwable?

Select one or more:

a. The class Throwable represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try…catch statement. 
b. The thrown object must belong to the class Throwable or to one of its (many) subclasses such as Exception and RuntimeException. 
c. The object carries information about an exception from the point where the exception occurs to the point where it is caught and handled. 
d. A Throwable contains a snapshot of the execution stack of its thread at the time it was called.

The correct answer is: The class Throwable represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try…catch statement., The thrown object must belong to the class Throwable or to one of its (many) subclasses such as Exception and RuntimeException., The object carries information about an exception from the point where the exception occurs to the point where it is caught and handled.

Question 7

“Subclasses of the class Exception which are not subclasses of RuntimeException require mandatory exception handling.” What are the practical implications of this statement?

Select one or more:

a. If a method can throw such an exception, then it must declare this fact by adding a throws clause to the method heading. 
b. If a routine includes any code that can generate such an exception, then the routine must deal with the exception. 
c. The routine cannot handle the exception by adding a throws clause to the method definition.
d. The routine can handle the exception by including the code in a try statement that has a catch clause to handle the exception. 


The correct answer is: If a method can throw such an exception, then it must declare this fact by adding a throws clause to the method heading., If a routine includes any code that can generate such an exception, then the routine must deal with the exception., The routine can handle the exception by including the code in a try statement that has a catch clause to handle the exception.

Java 2

Which of the following statements is correct?

A. Comparable<String> c = new String("abc");
B. Comparable<String> c = "abc";
C. Comparable<String> c = new Date();
D. Comparable<Object> c = new Date();





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

A. list.add(5.5); // 5.5 is automatically converted to new Double(5.5)
B. list.add(3.0); // 3.0 is automatically converted to new Double(3.0)
C. Double doubleObject = list.get(0); // No casting is needed
D. double d = list.get(1); // Automatically converted to double



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)


To create a generic type bounded by Number, use
A. <E extends Number>
B. <E extends Object>
C. <E>
D. <E extends Integer>



Which of the following declarations use raw type?

A. ArrayList<Object> list = new ArrayList<Object>(); 
B. ArrayList<String> list = new ArrayList<String>(); 
C. ArrayList<Integer> list = new ArrayList<Integer>(); 
D. ArrayList list = new ArrayList(); 



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

A. report syntax 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
E. report warning and generate a class file if no other errors in the program.


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





Network Essentials

Which layer is responsible for determining the best path a packet should travel across an internetwork?
A - Network
B - Transport
C - Session
D - Data Link

ANSWER - Network



Which layer is responsible for the encoding of signals?
A - 3
B - 1
C - 5
D - 7

ANSWER - 1



Bus Ethics Quiz


Workers in a culture of low power distance may be more willing to question the boss’s authority or even blow the whistle on an unethical manager.

A
True
B

False


ANSWER = A - True. 



The additional costs of corruption to international projects is less than 5 percent on average making it practical to include corruption as a cost of doing business.


A
True
B

False

ANSWER = B - False





Weak organizational cultures are

A
Desirable if an organization has many subcultures
B
Desirable if an organization wants diversity of thought and action
C
Desirable if an organization wants behavioral consistency
D
Undesirable in all situations

ANSWER = A and B




The ___________ experiment demonstrated the power of legitimate authority. Teachers were unwilling to question the experimenter’s authority for fear of personal embarrassment or upsetting the status quo.

A
Milgram
B
Manville
C
Zimbardo
D
My Lai

ANSWER = A - Milgram



Which of the following is false?

A
Employee engagement is how committed employees are to their work
B
Actively disengaged employees have lower turnover and absenteeism
C
Actively disengaged employees cost the U.S. economy billions each year
D
Engaged employees are more productive

ANSWER = B - Actively disengaged employees have lower turnover and absenteeism.



A statement such as “integrity is important here” is enough for subordinates to understand expected behavior.

A
True
B

False

ANSWER = B - False



Group norms can cause an "everyone is doing it mentality." This means

A
People are more likely to recognize issues as ethical issues
B
Many individuals will go along with unethical behavior because of a strong need for peer acceptance
C
Managers cannot blame individual employees for unethical behavior
D
Employees are actively disengaged in groups

ANSWER = B - Many individuals will go along with unethical behavior because of a strong need for peer acceptance




Continuous performance evaluation is categorized under which of the four drivers of employee engagement?

A
Line of sight
B
Involvement
C
Information sharing
D
Rewards and recognition

ANSWER = D - Rewards and recognition



Corporate social responsibility (CSR) consists of which four kinds of responsibilities

A
Economic, ethical, societal, and altruistic
B
Economic, legal, ethical, and altruistic
C
Fiscal, legal, societal, and philanthropic
D
Economic, legal, ethical, and philanthropic

ANSWER = D - Economic, legal, ethical, and philanthropic




Java 2 Test

Question 1

How can you drink an entire keg of root beer?

Select one:

a. (1) take one swallow, then (2) take another swallow.
b. (1) If the keg is empty do nothing, otherwise (2) take one swallow, then drink the rest of the keg. 
c. (1) take one enormous gulp, and (2) wish you hadn't.
d. (1) drink one keg, and (2) drink another keg.

The correct answer is: (1) If the keg is empty do nothing, otherwise (2) take one swallow, then drink the rest of the keg.


Question 3

Suppose cursor refers to a node in a linked list (using the IntNode class with instance variables called data and link). What statement changes cursor so that it refers to the next node?

Select one:

a. cursor++;
b. cursor = link;
c. cursor += link;
d. cursor = cursor.link;

The correct answer is: cursor = cursor.link;


Question 4

In the linked list implementation of the queue class, where does the insert method place the new entry on the linked list?

Select one:

a. At the head.
b. At the tail.
c. After all other entries that are greater than the new entry.
d. After all other entries that are smaller than the new entry.

The correct answer is: At the tail.


Question 5

How do you study a text book?

Select one:
a. (1) Read the book on day 1, and (2) read it again each day of the semester.
b. (1) If you have reached the end of the book you are done, else (2) study one page, then study the rest of the book.
c. (1) Divide the book in two, and (2) study each half.
d. (1) Cram all the pages in one horrible session, and (2) forget everything the next night.

The correct answer is: (1) If you have reached the end of the book you are done, else (2) study one page, then study the rest of the book.


Question 6

How many leaves does the tree below have?
      14
       / \
      2 11
     / \ / \
    1 3 10 30
            / /
          7 40

Select one:

a. 2
b. 4
c. 6
d. 8
e. 9

The correct answer is: 4


Question 7

Consider the tree below. What is the order of nodes visited using a pre-order traversal?

        14
        / \
       2 11
       / \ / \
      1 3 10 30
              / /
           7 40


Select one:

a. 1 2 3 7 10 11 14 30 40
b. 1 2 3 14 7 10 11 40 30
c. 1 3 2 7 10 40 30 11 14
d. 14 2 1 3 11 10 7 30 40 Correct

The correct answer is: 14 2 1 3 11 10 7 30 40


Question 8

The following code writes out the name of a day of the week depending on the value of day.

True or False?

String dayName = null;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
}
System.out.println(dayName);

Select one:

True Correct
False

The correct answer is 'True'.


Question 9

Which of the following statements are true?

Select one:

a. The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series. 
b. The Fibonacci series begins with 1 and 1, and each subsequent number is the sum of the preceding two numbers in the series.
c. The Fibonacci series begins with 1 and 2, and each subsequent number is the sum of the preceding two numbers in the series.
d. The Fibonacci series begins with 2 and 3, and each subsequent number is the sum of the preceding two numbers in the series.

The correct answer is: The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.


Question 10

Which statements are correct regarding Java’s predefined class called Throwable?

Select one or more:

a. The class Throwable represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try…catch statement. 
b. The thrown object must belong to the class Throwable or to one of its (many) subclasses such as Exception and RuntimeException.
c. The object carries information about an exception from the point where the exception occurs to the point where it is caught and handled.
d. A Throwable contains a snapshot of the execution stack of its thread at the time it was called.

The correct answer is: The class Throwable represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try…catch statement., The thrown object must belong to the class Throwable or to one of its (many) subclasses such as Exception and RuntimeException., The object carries information about an exception from the point where the exception occurs to the point where it is caught and handled.


Question 11

Consider the tree in the previous question. What is the order of nodes visited using an in-order traversal?

Select one:

a. 1 2 3 7 10 11 14 30 40
b. 1 2 3 14 7 10 11 40 30
c. 1 3 2 7 10 40 30 11 14
d. 14 2 1 3 11 10 7 30 40

The correct answer is: 1 2 3 14 7 10 11 40 30


Question 12

What are two parts to recursion?

Select one:

a. (1) If the problem is easy, solve it immediately, and (2) If the problem can't be solved immediately, divide it into smaller problems.
b. (1) Divide the problem into smaller problems, and (2) give immediate solutions for the hard problems.
c. (1) Discard the hard cases , and (2) solve the easy easy cases.
d. (1) Solve the problem by asking it to solve itself, (2) Solve the easy cases in one step.

The correct answer is: (1) If the problem is easy, solve it immediately, and (2) If the problem can't be solved immediately, divide it into smaller problems.


Question 13

In the following method, what is the base case?

static int xMethod(int n) {
    if (n == 1)
       return 1;
    else
       return n + xMethod(n - 1);
}

Select one:

a. n is 1 
b. n is greater than 1.
c. n is less than 1.
d. no base case.

The correct answer is: n is 1


Question 14

“Subclasses of the class Exception which are not subclasses of RuntimeException require mandatory exception handling.” What are the practical implications of this statement?

Select one or more:

a. If a method can throw such an exception, then it must declare this fact by adding a throws clause to the method heading.
b. If a routine includes any code that can generate such an exception, then the routine must deal with the exception. 
c. The routine cannot handle the exception by adding a throws clause to the method definition.
d. The routine can handle the exception by including the code in a try statement that has a catch clause to handle the exception.

The correct answer is: If a method can throw such an exception, then it must declare this fact by adding a throws clause to the method heading., If a routine includes any code that can generate such an exception, then the routine must deal with the exception., The routine can handle the exception by including the code in a try statement that has a catch clause to handle the exception.


Question 15

For a linked list to be used in a program, that program needs:

i. A variable that refers to the first node in the list.
ii. A pointer to the first node.
iii. A null pointer in the last node.

Select one:

a. i and ii 
b. i
c. ii and iii
d. i, ii and iii

The correct answer is: i and ii


Question 16

Consider the tree in the previous question. What is the value stored in the parent node of the node containing 30?

Select one:

a. 10
b. 11
c. 14
d. 40
e. None of the above

The correct answer is: 11


Question 17

Given the following piece of code:

class Student { public void talk(){} }
public class Test{
           public static void main(String args[]){
                      Student t = null;
                      try {
                            t.talk();
                           } catch(NullPointerException e){
                           System.out.print("There is a NullPointerException. ");
                           } catch(Exception e){
                           System.out.print("There is an Exception. ");
                           }
                           System.out.print("Everything ran fine. ");
          }
}

what will be the result?

a. If you run this program, the following is printed:
There is a NullPointerException. Everything ran fine.

b. If you run this program, the following is printed:
There is a NullPointerException.

c. If you run this program, the following is printed:
There is a NullPointerException. There is an Exception.

d. This code will not compile, because in Java there are no pointers.


The correct answer is: a.


Question 2

Study the following three pieces of code. Comments have been removed intentionally.
Can you guess what each does?

(i)
public class ProcForInts {

  private int[] items = new int[10];

  private int top = 0;

 /**
 * Procedure
 */
public void push( int N ) {
   if (top == items.length) {
     int[] newArray = new int[ 2*items.length ];
     System.arraycopy(items, 0, newArray, 0, items.length);
     items = newArray;
   }
   items[top] = N;
   top++;
}

 /**
 * Procedure
 */
public int pop() {
   if ( top == 0 )
       throw new IllegalStateException("Can't…");
   int topItem = items[top - 1]
   top--;
   return topItem;
}

 /**
 * Procedure
 */
public boolean isEmpty() {
    return (top == 0);
   }

}


(ii)
public class ProcForInts {

  /**
  * Procedure
  */
  private static class Node {
      int item;
      Node next;
}

  private Node head = null;

  private Node tail = null;

  /**
  * Procedure
  */
public void enqueue( int N ) {
       Node newTail = new Node();
       newTail.item = N;
       if (head == null) {
           head = newTail;
           tail = newTail;
}
      else {
         tail.next = newTail;
         tail = newTail;
   }
}

  /**
  * Procedure
  */
public int dequeue() {
     if ( head == null)
         throw new IllegalStateException("Can't…");
     int firstItem = head.item;
     head = head.next;
     if (head == null) {
          tail = null;
   }
     return firstItem;
}

  /**
  * Procedure
  */
   boolean isEmpty() {
      return (head == null);
}

}


(iii)
public class ProcForInts {

  private static class Node {
     int item;
     Node next;
}

   private Node top;

  /**
  * Procedure
  */
public void push( int N ) {
   Node newTop;
   newTop = new Node();
   newTop.item = N;
   newTop.next = top;
   top = newTop;
}

  /**
  * Procedure
  */
public int pop() {
   if ( top == null )
      throw new IllegalStateException("Cannot…");
   int topItem = top.item;
   top = top.next;
   return topItem;
}

  /**
  * Procedure
  */
public boolean isEmpty() {
    return (top == null);
   }

}

Select one:
a. (i) is a linked list implementation of a stack; (ii) is an array implementation of a stack; (iii) is a queue
b. (i) is an array implementation of a stack; (ii) is a linked list implementation of a stack; (iii) is a queue
c. (i) is a queue; (ii) is a linked list implementation of a stack; (iii) is an array implementation of a stack
d. (i) is an array implementation of a queue; (ii) is a linked list implementation of a queue; (iii) is a stack
e. (i) is an array implementation of a stack; (ii) is a queue; (iii) is a linked list implementation of a stack 

The correct answer is: (i) is an array implementation of a stack; (ii) is a queue; (iii) is a linked list implementation of a stack

Java 2 Self Quiz 4

Question 1

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

Select one:
True 
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 list = new ArrayList. 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 { ... }
b. public class A { ... }
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 { ... }
b. public class A { ... }
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 { ... }
b. public interface A { ... }
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>();



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


Java 2 Quiz E

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 Correct
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)

Java 2 Quiz 6

Which of the following statements are true?

Select one or more:

a. A socket is a kind of opening. Correct
b. A socket represents one endpoint of a network connection. Correct
c. A program uses a socket to communicate with another program over the network. Correct
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. Correct

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.



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. Correct
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. Correct
b. A URL constructor creates an Address field in a Web browser.
c. A URL object represents a Universal Resource Locator. Correct
d. Once you have a URL object, you can call its openConnection() method to access the information at the url address that it represents. Correct


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() Correct
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. Correct

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. Correct

d. In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across different locations. Correct

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. Correct


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 Correct
b. Server Incorrect
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. Correct

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. Correct

c. The picture in a BufferedImage can easily be copied into a graphics context g by calling one of the g.drawImage methods. Correct

d. The image drawn here is so small, it seems likely that is going to be used to define an ImageIcon. Correct


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. Correct

c. The font is specified when the FontMetrics object is created. Correct

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. 
Correct


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 Correct

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. Correct

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. Correct

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. Correct

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. Correct


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.


Python - Test Yourself4

What does function subroutine do?

def subroutine(n):
  while n > 0:
      print (n,)
      n -= 1

Select one:
 a. Counts from 10
down to 0 and displays each number
 b. Counts from n down
to 1 and displays each number
 
 c. Calculates the sum
of n numbers greater than 0

 d. Calculates the
mean of n

What output will the following code produce?

def area(l, w):
    temp = l * w;
    return temp

l = 4.0
w = 3.25
x = area(l, w)
if ( x ):
  print (x)


Select one:
 a. 13.0 
 b. 0
 c. Expression does
not evaluate to boolean true
 d. 13


Repeated execution of a set of programming statements is
called repetitive execution.

Select one:
 True
 False  

A stack diagram shows the value of each variable and the
function to which each variable belongs.

Select one:
 True 
 False

The following code is an example of what principle?

bruce = 5
print (bruce,)
bruce = 7
print (bruce)

Select one:
 a. Multiple
assignment 
 b. An Iteration or
loop structure
 c. A logical operator
 d. A conditional
expression

What does function subroutine do?

def subroutine(n):
  while n > 0:
      print (n,)
      n -= 1

Select one:
 a. Counts from 10
down to 0 and displays each number
 b. Counts from n down
to 1 and displays each number 
 c. Calculates the sum
of n numbers greater than 0
 d. Calculates the
mean of n

Expressions evaluate to either true or false.  What will the output of the following code be
when the  expression (Ni!) is evaluated?

if "Ni!":
    print ('We are the
Knights who say, "Ni!"')
else:
    print ("Stop
it! No more of this!")

Select one:
 a. Stop it!
 b. We are the Knights
who say, "Ni! 
 c. Stop it! No more
of this!"
 d. No output will be
produced

What will the output of the following code be?

def recursive( depth ):
    depth+=1
    while (depth <
5):
        ret =
recursive(depth)
    return depth

ret = recursive( 0 )
print ("the recursive depth is ", ret)

Select one:
 a. the recursive
depth is 5
 b. the recursive
depth is 4
 c. Error due to depth
of recursive calls
 d. None  

Encapsulation is the process of wrapping a piece of code in
a function

Select one:
 True 
 False



What output will the following python commands produce:

x=1
y=2
if x == y:
    print (x,
"and", y, "are equal")
else:
    if x < y:
        print (x,
"is less than", y)
    else:
        print (x,
"is greater than", y)


Select one:
 a. 1 and 2 are equal
 b. 1 is less than
 c. 1 is greater than
2
 d. 2 is greater than
1