Tải bản đầy đủ (.doc) (25 trang)

Bài tập trắc nghiệm có đáp án

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (138.56 KB, 25 trang )

1. Threads can be in one of four states:
a) New, Running, Sleeping, Dead
b) New, Runnable, Blocked, Dead
c) Start, Running, Sleeping, Stop
d) Start, Blocked, Sleeping, Stop
2. To find out whether a thread is currently alive, use the ____________ method
a) isActive()
b) isAlive()
c) isEnabled()
d) isStillAlive()
3. Turn a thread into a daemon thread by calling
a) t.getDaemon(true);
b) t.setThreadDaemon(true);
c) t.setDaemon(true);
d) t.setThreadPriority
4. With JDK 5, two mechanisms for protecting a code block from concurrent access, there are:
a) Using the synchronized and unsynchrinized keyword
b) Using the EntrantLock and ReentrantLock class
c) Using the synchronized keyword and EntrantLock class
d) Using the synchronized keyword and ReentrantLock class
5. Blocking Queue Operation: poll (removes and returns the head element) returns _________if the queue
was empty
a) false
b) null
c) true
d) None of above
6. Which the following statement is true about Runnable and Callable interfaces
a) A Callable is similar to a Runnable, but it returns a value.
b) Runnable is similar to Callable
c) Runnable is similar to Future
d) Callable is similar to Future


7. Which the following statement is true about HashSet
a) A sorted set
b) An unordered collection that rejects duplicates
c) A set of enumerated type values
d) An ordered sequence that allows efficient insertions and removal at any location
8. Which the following statement is true about PriorityQueue
a) An ordered sequence that allows efficient insertions and removal at any location
b) A data structure that stores key/value associations
c) A collection that allows efficient removal of the smallest element
d) A map that remembers the order in which entries were added
9. See the following code
List<String> staff = new <String>();
staff.add("Amy");
staff.add("Bob");
staff.add("Carl");
Iterator iter = staff.iterator();
String first = iter.next();
String second = iter.next();
iter.remove();
Which the following statement is correct?
a) Adds three elements and and then removes all of them
b) Adds three elements and and then removes the second one
c) Adds three elements and and then removes the first one
d) Adds three elements and and then removes the last one

10. List<String> staff = new LinkedList<String>();
staff.add("Amy");
staff.add("Bob");
staff.add("Carl");
ListIterator<String> iter = staff.listIterator();

iter.next();
iter.add("Juliet");
a) Skips past the two first elements in the linked list and adds "Juliet" before the third element
b) Adds "Juliet" as the first element of the linked list
c) Skips past the third element in the linked list and adds "Juliet" before the fourth element
d) Skips past the first element in the linked list and adds "Juliet" before the second element
11. What is the main different between ArrayList and Vector collection?
a) All methods of the Vector class are synchronized.
b) All methods of the ArrayList class are synchronized.
c) All of a, b are correct.
d) All of a, b aren't correct
12. A hash table is an array of linked lists. Each list is called a _______________
a) set
b) recordset
c) bucket
d) batch
13. If an object has hash code 76268 and there are 128 buckets, then the object is placed in bucket ________
a) 109
b) 110
c) 108
d) 111
14. See the following code
SortedSet<String> sorter = new TreeSet<String>(); // TreeSet implements SortedSet
sorter.add("Bob");
sorter.add("Amy");
sorter.add("Carl");
sorter.add("John");
for (String s : sorter)
System.println(s);
a) Inserts four strings and then visit the first element.

b) Inserts four strings and then visit all elements have added.
c) Inserts four strings and then visit the second element.
d) Inserts three strings and then visit all elements have added.
15. The tree set assumes that you insert elements that implement the Comparable interface.
a) The call a.compareTo(b) must return true if a and b are equal.
b) The call a.compareTo(b) must return false if a and b are equal.
c) The call a.compareTo(b) must return 0 if a and b are equal, a negative integer if a comes
before b in the sort order, and a positive integer if a comes after b.
d) The call a.compareTo(b) must return 0 if a and b are equal, a positive integer if a comes before b
in the sort order, and a negative integer if a comes after b.
16. The Java library supplies two general-purpose implementations for maps: HashMap and TreeMap. Both
classes implement the _______ interface.
a) UnsortedMap
b) SortedMap
c) Map
d) MapInterface
17. putAll(Map<? extends K, ? extends V> entries)
a) Remove all entries from the specified map to this map.
b) Adds all entries from the specified map to this map.
c) None of above are correct
d) All of above are correct
18. Which the following statement is correct?
a) The EnumSet is an efficient set implementation with elements that belong to user-defined type.
b) The EnumSet is an efficient set implementation with elements that belong to an enumerated
type.
c) The EnumSet is an efficient set implementation with elements that belong to a specific type.
d) The EnumSet isn't an efficient set implementation with elements that belong to an enumerated
type.
19. Which the following statements are correct about the collections framework
a) The collection framework defines a number of interfaces and abstract classes for implementors of

collections
b) A framework is a set of classes that form the basis for building advanced functionality. A
framework contains superclasses with useful functionality, policies, and mechanisms.
c) A framework is an interface using for predefining methods
d) None of above
20. The _____________ method is declared to have a variable number of arguments. Instead of passing an
array, you can also pass individual elements
a) asAlist( )
b) list( )
c) asList( )
d) addList( )
21. The static __________ method in the Collections class can turn any map into a Map with synchronized
access methods.
a) setSynchronizedMap( )
b) getsynchronizedMap( )
c) setSynchronized( )
d) synchronizedMap( )
22. See the following code
if (a.length == 0) throw new NoSuchElementException();
T largest = a[0];
for (int i = 1; i < a.length; i++)
if (largest.compareTo(a[i]) < 0)
largest = a[i];
a) These lines used to find the smallest element of an array.
b) These lines used to find the specify element of an array.
c) These lines used to find the largest element of an array.
d) These lines used to replace the largest element of an array.
23. The Collections class has an algorithm _______ that does the opposite of sortingit randomly permutes the
order of the elements in a list. You supply the list to be shuffled and a random number generator.
a) Collections.shuffle( )

b) Collections.short( )
c) Collections.shuffleAll( )
d) Collections.binarySearch( )
24. A property set is a map structure of a very special type.
a) The keys and values are numbers. The table can be saved to a file and loaded from a file. A
secondary table for defaults is used.
b) The keys are strings and values are numbers. The table can be saved to a file and loaded from a file.
A secondary table for defaults is used.
c) The keys and values are strings. The table can be saved to a file and loaded from a file. A
secondary table for defaults is used.
d) The keys and values are strings. The table cannot be saved to a file and loaded from a file. A
secondary table for defaults is used.
25. The __________ class gives you a convenient interface for reading, setting, or resetting individual bits.
a) ByteSet
b) BitSetCollections
c) BitSet
d) ByteCollections
26. The following statement is using for what?
ServerSocket s = new ServerSocket(1609);
a) Establishes a server that monitors port 1609.
b) Establishes a client that monitors port 1609.
c) Establishes a server that monitors port 8180.
d) Establishes a client that monitors port 8180.
27. See the following commands:
ServerSocket s = new ServerSocket(8189);
Socket incoming = s.accept();
a) The second line tells the program to accept all connections from clients.
b) The second line tells the program to deny all client connects to 8180 port.
c) The second line tells the program to wait indefinitely until a client connects to 8189 port
d) The second line tells the program not to wait indefinitely until a client connects to 8189 port.

28. Open a socket to your host.
Socket s = new Socket("mail.yourserver.com", 25);
PrintWriter out = new PrintWriter(s.getOutputStream());
a) Port 25 is served Simple Mail Transfer Protocol
b) Port 25 is served FTP
c) Port 25 is served HTTP
d) Port 25 is served SSH
29. The URL and _____________ classes encapsulate much of the complexity of retrieving information
from a remote site.
a) URLDataConnection
b) URLConnection
c) URLConnectionData
d) URLCollections
30. With URLConnection, the method getRequestProperties() returns a map of request properties. All values
for the same key are placed in a list. Which the following statement is correct?
a) Map<String,List<String>> getRequestProperties()
b) Map<Integer,List<String>> getRequestProperties()
c) Map<Integer,List<Integer>> getRequestProperties()
d) Map<Double,List<String>> getRequestProperties()
31. See the following commands:
Socket s = new Socket(. . .);
s.setSoTimeout(10000);
a) The second line set time out after 100 seconds
b) The second line set time out after 1 second
c) The second line set time out after 10 seconds
d) The second line set time out after 1000 seconds
32. To interrupt a socket operation, you use a __________, a feature of the java.nio package.
a) SocketChannel
b) SocketOperation
c) SocketInterrupted

d) SocketGetInterrupted
33. You can close the output stream of a socket, thereby indicating to the server the end of the request data,
but keep the input stream open so that you can read the response. The _______ overcomes this problem.
a) half-stop
b) half-connection
c) half-close
d) half-diconnection
34. See the folowing statements
import java.net.*;
public class InetAddressTest {
public static void main(String[] args) {
try {
if (args.length > 0) {
String host = args[0];
InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress a : addresses)
System.out.println(a);
} else {
InetAddress localHostAddress = InetAddress.getLocalHost();
System.out.println(localHostAddress);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
a) Supply a host name as command-line argument, or run without command-line arguments to see the
address of the local host.
b) Supply a host name as command-line argument to see the address of the local host.

c) Supply a host name as command-line argument to see the address of the 192.168.1.1 host.
d) Supply the address of the local host.
35.JDBC drivers are classified into the __________ types
a) 1
b) 2
c) 3
d) 4
36. The general syntax of database URL is
a) jdbc:odbc:subprotocol:other stuff
b) jdbc:subprotocol:odbc:other stuff
c) jdbc:subprotocol:odbc
d) jdbc:subprotocol:other stuff
37. The ____________ class selects database drivers and creates a new database connection.
a) DriverManager
b) DriverConnectionManager
c) Connection Manager
d) ManagementConnection
38. Prepare a query with a host variable and use it many times, each time filling in a different string for the
variable. That technique benefits performance. Using __________ class for this purpose.
a) Statement
b) PreparedStatement
c) RequiredStatement
d) PrepareQueryStatement
39. Method clearParameters() of PreparedStatement is using for
a) Clears all current parameters in the prepared statement.
b) Clears current parameters in the prepared statement.
c) Fill all current parameters in the prepared statement.
d) Fill current parameters in the prepared statement.
40.To obtain scrollable result sets from your queries, you must obtain a different Statement object with the
method

Statement stat = conn.createStatement(type, concurrency);
if type=yTYPE_SCROLL_INSENSITIVE,
a) The result set is not scrollable.
b) The result set is scrollable but not sensitive to database changes.
c) The result set is scrollable and sensitive to database changes.
d) None of above.
41.To obtain scrollable result sets from your queries, you must obtain a different Statement object with the
method
Statement stat = conn.createStatement(type, concurrency);
if concurrency=CONCUR_UPDATABLE
a) The result set can be used to delete the database.
b) The result set can be used to update the database.
c) The result set cannot be used to update the database.
d) The result set cannot be used to execute the database.
42. JDBC can give you additional information about the structure of a database and its tables. To find out
more about the database, you request an object of type ______________ from the database connection.
a) ResultSetMetaData
b) RowSetMetaData
c) DatabaseMetaData
d) TableSetMetaData
43. The method __________ of java.sql.ResultSetMetaData returns the number of columns in the current
ResultSet object.
a) getColumnLabel(int column)
b) getColumnDisplaySize(int column)
c) getColumnCount()
d) getColumnName(int column)
44. A __________ is a cached row set that can be saved to an XML file.
a) WebRowSet
b) CachedRowSet
c) FilteredRowSet

d) JoinRowSet
45. The method ___________ of javax.sql.rowset.CachedRowSet populates this cached row set with the data
from the given result set.
a) setCommand(String command)
b) populate(ResultSet result)
c) setURL(String url)
d) acceptChanges()
46. When a JDBC application is deployed in an enterprise environment, the management of database
connections is integrated with the _______________.
a) Java 2 Enterprise Edition (J2EE)
b) Java Naming and Directory Interface (JNDI)
c) Remote Methods Invocation (RMI)
d) None of above
47. A database connection is in autocommit mode, and each SQL command is committed to the database as
soon as it is executed. Once a command is committed, you cannot roll it back. To turn off autocommit mode
with the command
a) Connection conn =
conn.setAutoCommit(false);
b) Connection conn =
conn.setAutoCommit(true);
c) Connection conn =
conn.setAutoCommit();
d) Connection conn =
conn.setAutoCommit(on);
48. To create statement objects, use the Connection object (conn) that you obtained from the call to
DriverManager.getConnection.
a) Statement stat = conn.preparedStatement();
b) Statement stat = conn.requiredStatement();
c) Statement stat = conn.createStatement();
d) Statement stat = conn.getStatement();

49. The process of encoding the parameters is called _____________. The purpose of ____________ is to
convert the parameters into a format suitable for transport from one virtual machine to another.
a) parameter encoding
b) parameter marshalling
c) parameter decoding
d) parameter analyzing
50. RMI URLs start with _________ and are followed by a server, an optional port number, another slash,
and the name of the remote object.
a) http://
b) ftp://
c) smtp://
d) rmi://
51. The RMISecurityManager __________ all code in the program from establishing network connections.
a) restricts
b) gets
c) receives
d) accesses
52. RMI uses the _________ mechanism to send objects across a network connection.
a) non-serialization
b) serialization
c) comparation
d) non-comparation
53. The __________ mechanism lets you delay the object construction so that a server object is only
constructed when at least one client invokes a remote method on it.
a) deactivation
b) start
c) activation
d) stop
54. The java.rmi.activation.Activatable has exportObject method. The prototype od this method is
a) Remote exportObject(Remote obj, ActivationID id, int port)

b) RemoteObject exportObject(Remote obj, ActivationID id, int port)
c) static Remote exportObject(Remote obj, ActivationID id, int port)
d) static RemoteObject exportObject(Remote obj, ActivationID id, int port)
55. A bean is a _________________ based on Sun's JavaBeans specification that can be manipulated
visually in a builder tool.
a) recompile software component
b) reusable tool
c) reusable software component
d) reusable object
56. To make the JAR file, follow these steps:
1. Edit the manifest file.
2. Gather all needed class files in a directory.
3. Run the jar tool as follows:
a) jar cvfm JarFile ManifestFile ClassFiles
b) jar cvfm ManifestFile ClassFiles JarFile
c) jar cvfm ManifestFile JarFile ClassFiles
d) jar cvfm ClassFiles JarFile ManifestFile
57. Bean Property Types include:
a) Simple, Indexed, Constrained Properties
b) Simple, Bound, Constrained Properties
c) Simple, Indexed, Bound, Constrained Properties
d) Indexed, Bound, Constrained Properties
58. A ____________ is constrained by the fact that any listener can "veto" proposed changes, forcing it to
revert to the old setting.
a) constrained property
b) indexed property
c) bound property
d) simple property
59. __________ tell interested listeners that their value has changed.
a) Indexed properties

b) Simple properties
c) Bound properties
d) Constrained properties
60. You can define an object that implements the ____________ interface to describe your bean.
a) BeanInfo
b) BeanInfomation
c) BeanMetaData
d) BeanMetaInfo
61. For a system consisting of exclusively Java objects, which distributed technology would be most
appropriate for communication?
a) CORBA
b) JavaBean
c) JNDI
d) RMI
62. All exceptions fall into either of two categories:
a) checked and unchecked
b) RunTime and CompileTime
c) good and badunchecked
d) Exception and Errored
63. An object of the Hashtable class can store and retrieve object references based on associated "key"
objects. Which interface does Hashtable implement?
a) SortedMap
b) SortedSet
c) Map
d) List
64. How are computers on the Internet located?
a) By their registration number
b) By their Internet ID number
c) By their IP address
d) By their locator chip

65. How can the priority of a thread be set?
Select the one correct answer
a) By using the setPriority() method in the class Thread.
b) None of the other answers
c) By passing the priority as a parameter to the constructor of the thread.
d) Both of the other answers
66. How can you determine which component has the focus?
a) You poll through all components in a loop until this is true: getFocus(componentName).
b) You use getFocus() from the top window.
c) You poll through all components in a loop with isActive.
d) You poll through all windows in a loop until you get the component with focus with
getFocusOwner().
67. How do Swing menus differ from AWT menus?
a) Swing menus are round.
b) Swing menus are components
c) Swing menus are implemented in separate windows.
d) None of the other answers
68. How do you create a multiple selection mode JComboBox?
a) Use a JList for multiple selection because JComboBox is only single selection.
b) With: setMode(MULTIPLE_SELECTION).
c) With: setSelectionMode(true)
d) With: setMode(true)
69. How do you group a set of option buttons with a border and title?
a) You add all the buttons to a JWindow.
b) You add the buttons in various ways, but you group them programmaticall
c) You add each button to its own JFrame and then add all those JFrames to a window
d) You place the option buttons you want to group in a JPanel, and then you add a border to the
JPanel.
70. How do you properly size a component immediately after creating it?
a) How do you properly size a component immediately after creating it?

b) With: doLayout().
c) With: addNotify().
d) With: setComponentOrientation().
71. How does a *.java file differ from a *.class file?
a) A *.java file is bytecode.
b) A *.class file is source code.
c) A *. class file is a compiled *.java file
d) A *.java file is a compiled *.class file.

72. How does the set collection deal with duplicate elements?
a) An exception is thrown if you attempt to add an element with a duplicate value
b) The add method returns false if you attempt to add an element with a duplicate value
c) Duplicate values will cause an error at compile time Question Help.
d) A set may contain elements that return duplicate values from a call to the equals method
73. How is the forName() method of the Class class used with JDBC?
a) To establish a database connection
b) To load a JDBC driver
c) To execute a SQL statementresses
d) To load a result set
74. In Java, which statement will establish a new TCP/IP connection to a server, java.sun.com?
a) Socket s = new Socket("java.sun.com", 80);
b) ServerSocket server = new ServerSocket(8000);
c) Connection s = new Connection("java.sun.com", 80);
d) connect("java.sun.com",80);
75. In Java, you use ____ methods for object locking.
a) synchronized
b) Unlock
c) asynchronized
d) Lock
76. InputStream and OutputSteam are __________.

a) The top-level abstract classes defined in the java.io package, from which all other stream
classes inherit.
b) The top-level abstract classes defined in the java.io package, from which all other byte stream classes
inherit.
c) Interfaces that define methods that can be used to read and write bytes.
d) Classes that you can instantiate to read and write bytes.
77. Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
a) After thread A is notified, or after two seconds.
b) After the lock on B is released, or after two
c) Two seconds after lock B is released.
d) Two seconds after thread A is notified.
78. Distinguish Between Session and Entity Beans
Which statement is not true when contrasting the use of entity beans and JDBC for database operations?
a) Entity beans represent real data in a database.
b) When using JDBC, you must explicitly handle the database transaction and the database connection
pooling.
c) The bean managed entity bean functionally replaces the JDBC API.
d) The container-managed entity bean automatically retrieves the data from the persistent storage
(database).
79. 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.*;
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(InterruptedException e) { }
d) try { Thread.sleep(1000); }
catch(RuntimeException e) { }
80. Given the following,
11. x = 0;
12. if (x1.hashCode() != x2.hashCode() ) x = x + 1;
13. if (x3.equals(x4) ) x = x + 10;
14. if (!x5.equals(x6) ) x = x + 100;
15. if (x7.hashCode() == x8.hashCode() ) x = x + 1000;
16. System.out.println("x = " + x);
and assuming that the equals () and hashCode() methods are property implemented, if the
output is “x = 1111”, which of the following statements will always be true?“
a) x2.equals(x1)
b) x3.hashCode()
c) x8.equals(x7)
d) x5.hashCode()
81. Given the following,

public class MyOuter {
public static class MyInner {
public static void foo() { }
}
}
which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested
class?
a) MyOuter.MyInner m = new MyOuter.MyInner();
b) MyOuter.MyInner mi = new MyInner();
c) MyInner mi = new MyOuter.MyInner();
d) MyOuter m = new MyOuter();
MyOuter.MyInner mi = m.new MyOuter.MyInner();
82. Given:
11. public class Test{
12. public void foo(){
13. assert false;
14. assert false;
15. }
16. public void bar(){
17. while(true){
18. assert false;
19. }
20. assert false;
21. }
22. }
What causes compilation to fail?
a) Line 13
b) Line 14
c) Line 20
d) Line 18

83. Given:
11. try{
12. int x=0;
13. int y=5/x;
14. }catch(Exception c){
15. System.out.println("Exception");
16. }catch(ArithmeticException ac){
17. System.out.println("Arithmetic Exception");
18. }
19. System.out.println("finished");
What is the result?
a) finished
b) Exception
c) Compilation fails.
d) Arithmetic Exception
84. Given:
20. public float getSalary(Employee c){
21. assert validEmployee(c);
22. float sal=lookupSalary(c);
23. assert (sal>0);
24. return sal;
25. }
26. private int getAge(Employee c){
27. assert validEmployee(c);
28. int age=lookupAge(c);
29. assert (age>0);
30. return age;
31. }
Which line is a violation of appropriate use of the assertion mechanism?
a) Line 21

b) Line 23
c) Line 29
d) Line 27
85. How can you force an object to be garbage collected?
a) Invoke its finalize() method.
b) Remove all references to the object.
c) You cannot force an object to be garbage collected.
d) Use all memory that is available to the program.
86. Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame's font is set to 12-
point TimesRoman, the Panel's font is set to 10-point TimesRoman, and the Button's font is not set, what
font will be used to display the Button's label?
a) 12-point TimesRoman
b) 11-point TimesRoman
c) 9-point TimesRoman
d) 10-point TimesRoman
87. Suppose that a database server does not support a pure JDBC driver, but it does support an ODBC driver.
How can you access the database server using JDBC?
a) Use SQL.
b) Use JNDI.
c) Use the JDBC-ODBC bridge driver.
d) Use Java RMI.
88. The ____ method temporarily releases an object
lock and deactivtes the current thread.
a) wait
b) sleeping
c) sleep
d) waitting
89. The bean implementation class for an entity bean must implement the
a) EntityBean interface
b) EntityBean interface and the bean's remote interface

c) EntityBean interface and the methods of the bean's remote interface
d) EntityBean interface and the bean's remote and home interfaces
90. The Id attribute in the useBean tag must match
a) the name attribute in the getProperty tag
b) the name of the bean class
c) the value attribute in the setProperty tag
d) the property attribute in the getProperty tag
91. The methods of what type of object can be used to move the cursor through a result set?
a) Statement
b) ResultSet
c) URL
d) Connection
92. The RMI compiler rmic runs on which of the following files to produce the stub and skeleton classes?
a) On the remote interface class file
b) On the remote interface Java file
c) On the remote service implementation class file
d) On the remote service implementation Java file
93. To begin execution of a thread call its ____ method.
a) start
b) do
c) begin
d) run
94. To empty a Collection or a Map, you use the __________ method.
a) empty
b) clear
c) setEmpty
d) zero
95. Under what circumstances might you use the yield method of the Thread classport?
a) To call from the currently running thread to allow another thread of the same priority to run
b) To call on a waiting thread to allow it to run

c) To allow a thread of higher priority to run
d) To call from the currently running thread with a parameter designating which thread should be
allowed to run.
96. What can you write at the comment?
//A in the code below so that this program writes the word 'running' to the standard output?
class RunTest implements Runnable {
public static void main(String[] args) {
RunTest rt = new RunTest();
Thread t =new Thread(rt);
//A
}
public void run() {
System.out.println("running");
}
void go() {
start(1);
}
void start(int i) {
}
}
a) System.out.println("running");
b) rt.start();
c) rt.start(1);
d) rt.go();
97. What is the main disadvantage of Java garbage collection?
a) It cannot run in parallel with other threads.
b) It is slow.
c) It uses a heap.
d) It uses the system's memory allocation
98. What is the output of the following program?

33. import java.util.*;
34. class Question {
35. public static void main(String args[]) {
36. HashSet set = new HashSet();
37. String s1 = "abc";
38. String s2 = "def";
39. String s3 = "";
40. set.add(s1);
41. set.add(s2);
42. set.add(s1);
43. set.add(s2);
44. Iterator i = set.iterator();
45. while(i.hasNext()){
46. s3 += (String) i.next();
47. }
48. System.out.println(s3);
49. }
}
a) abcdef
b) defabcdefabc
c) defabc
d) fedcbafedcba
99. What is the output of the following program?
51. import java.util.*;
52. class Question {
53. public static void main(String args[]) {
54. TreeMap map = new TreeMap();
55. map.put("one","1");
56. map.put("two","2");
57. map.put("three","3");

58. displayMap(map);
59. }
60. static void displayMap(TreeMap map) {
61. Collection c = map.entrySet();
62. Iterator i = c.iterator();
63. while(i.hasNext()){
64. Object o = i.next();
65. System.out.print(o.toString());
66. }
67. }
}
a) onetwothree
b) 123
c) one=1three=3two=2
d) onethreetwo
100. What is the preferred way to handle an object's events in Java 2?
a) Override the object's handleEvent() method.
b) Add one or more event listeners to handle the events.
c) Have the object override its processEvent() methods.
d) Have the object override its dispatchEvent() methods.
101. What of the following has all of the visible components in the window’s GUI?
a) The internal viewport.
b) Intermediate-containers.
c) The content pane.
d) Internally, Java keeps all visible components in a collection.
102. What output does the following program display?
14. import java.util.*;
15. class Question {
16. public static void main(String args[]) {
17. String s1 = "abc";

18. String s2 = "def";
19. Stack stack = new Stack();
20. stack.push(s1);
21. stack.push(s2);
22. try {
23. String s3 = (String) stack.pop() + (String) stack.pop();
24. System.out.println(s3);
25. }catch(EmptyStackException ex){
26. }
27. }
}
a) abcdef
b) defabc
c) defdef
d) abcabc
103. What type of diagram does a Java Architect frequently produce?
a) Attribute diagram
b) Property diagram
c) Package dependency diagram
d) Constraint diagram
104. What will be the result of an attempt to compile and run the following program?
class Test
{
public static void main(String args[])
{
String s1 = "abc";
String s2 = "abc";
s1 += "xyz";
s2.concat("pqr");
s1.toUpperCase();

System.out.println(s1 + s2);
}
}
Choices:
a) "abcxyzabc"
b) "abcxyzabcpqr"
c) "ABCXYZabc"
d) "ABCXYZabcpqr"
105. What will be the result of invoking the wait() method on an object without ensuring that the current
thread holds the lock of the object?
Select the one correct answer.
a) The code will fail to compile.
b) The thread will be blocked until it gains the lock of the object.
c) Nothing special will happen.
d) An IllegalMonitorStateException will be thrown if the wait() method is called while the current
thread does not hold the lock of the object.
106. What will happen when you attempt to compile and run this code?
//Demonstration of event handling
import java.awt.event.*;
import java.awt.*;
public class MyWc extends Frame implements WindowListener{
public static void main(String argv[]){
MyWc mwc = new MyWc();
}
public void windowClosing(WindowEvent we){
System.exit(0);
}//End of windowClosing
public void MyWc(){
setSize(300,300);
setVisible(true);

}
}//End of class
a) Error at compile time
b) Visible Frame created that that can be closed
c) Compilation but no output at run time
d) Error at compile time because of comment before import statements
107. What will happen when you attempt to compile and run this code?
public class Mod{
public static void main(String argv[]){
}
public static native void amethod();
}
a) Error at compilation: native method cannot be static
b) Error at compilation native method must return value
c) Compilation and execution without errorš
d) Compilation but error at run time unless you have made code containing native amethod available
108. When a thread blocks on I/O, which of the following are true?
a) The thread enters the ready state.
b) The thread enters the dead state.
c) The thread enters the waiting state.
d) No other thread may perform I/O.
109. When a thread blocks on I/O, which of the following is true?
a) The thread enters the ready state.
b) The thread enters the dead state.
c) The thread enters the waiting state.
d) No other thread can perform I/O.
110. When a thread is interrupted the most common response is
a) to terminate the thread
b) to throw the exception up to the caller.
c) to ignore the interruption.

d) to generate an InterruptedException.
111. When two or more objects are added as listeners for the same event, which listener is first invoked to
handle the event?
a) The first object that was added as a listener.
b) The last object that was added as a listener.
c) There is no way to determine which listener will be invoked first.
d) It is impossible to have more than one listener for a given event.
112. Where is the notify() method defined?
Select the one correct answer.
a) Thread
b) Runnable
c) Object
d) Applet
113. Which class or interface defines the wait(), notify(), and notifyAll() methods?
a) Object
b) Thread
c) Class
d) Runnable
114. Which Component method is used to access a component's immediate Container?
a) getVisible()
b) getImmediate()
c) getContainer()
d) getParent()
115. Which constructor creates a TextArea with 10 rows and 20 columns?
a) new TextArea(10,20)
b) new TextArea(20,10)
c) new TextArea(200)
d) new TextArea(new Rows(10), new Colums(20))
116. Which Design Pattern does the JTextComponent use?
a) Session Façade.

b) Aggregate Entity.
c) Value Object.
d) Model-View-Controller.
117. Which distributed object technology is most appropriate for systems that consist of objects written in
different languages and that execute on different operating system platforms?
a) RMI
b) DCE
c) CORBA
d) DCOM
118. Analyze the following code:
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 test.
d) The program compiles and runs and displays nothing.

119. Which JDK 1.1 interface is the Iterator interface intended to replace?

a) Runnable
b) Throwable
c) List
d) Enumeration
120. Which most closely matches a description of a Java Map?
a) A vector of arrays for a 2D geographic representation
b) A class for containing unique array elements
c) An interface that ensures that implementing classes cannot contain duplicates
d) A class for containing unique vector elements
121. Which of the following are contained in a Java security policy file?
a) grant entries
b) trusted code
c) digital certificates
d) aliases and their public keys
122. Which of the following Java technologies support transaction processing?
a) RMI
b) JTA
c) JTS
d) JMAPI
123. Which of the following is true about Swing icons?
a) They can be added to Swing labels, buttons, and menu items.
b) They are limited to JPEG images.
c) They are limited to 16 colors?
d) None of the other answers
124. Which of the following is not true about RMI?
a) RMI uses the Proxy design pattern.
b) The RMI client can communicate with the server without knowing the server’s physical location.
c) RMI uses object serialization to send objects between JVMs.
d) The RMI Registry is used to generate stubs and skeletons.
125. Which of the following is not a top-level container?

a) JTabbedPane
b) JDialog
c) JFrame
d) JApplet
126. Which of the following is a Java API for managing enterprise services, systems, and networks.
a) JTA
b) Java Server Pages
c) JMAPI
d) JDBC
127. Which of the following describes a JDBC type 4 driver?
a) Native-protocol pure Java driver
b) JDBC-Net pure Java driver
c) JDBC-ODBC bridge plus ODBC driver
d) Native-API partly Java driver
128.Which of the following creates a List with 5 visible items and multiple selection enabled?
a) new List(true, 5)
b) new List(5, true)
c) new List(5, false)
d) new List(false, 5)
129. Which of the following is not a role of the Java architect?
a) Evaluating the advantages and disadvantages of using Java technology for enterprise applications
b) Designing distributed object architectures to a given set of business requirements
c) Training users on how to operate a Java-based application
d) Evaluating proposed Java technology architectures and making recommendations to increase
performance and security
130. Which of the following are true about a dead thread?
a) The thread's object is discarded.
b) The thread must wait until all other threads execute before it is restarted.
c) The thread is synchronized.
d) The thread cannot be restarted.

131. Which of the following statements are true? [Check all correct answers.]
a) The HashMap class implements the Collection interface
b) The HashSetMap class ensures unique elements stored as key/value pairs.
c) The LinkedHashSet class ensures elements are unique and ordered.
d) The iterator method returns elements in the order they were added.
132. Which statement is true? Select the one correct answer.
a) No two threads can concurrently execute synchronized methods on the same object.
b) Inside a synchronized method, one can assume that no other threads are currently executing any other
methods in the same class.
c) Methods declared synchronized should not be recursive, since the object lock will not allow new
invocations of the method.
d) Synchronized methods can only call other synchronized methods directly.
133. You wish to store a small amount of data and make it available for rapid access. You do not have a need
for the data to be sorted, uniqueness is not an issue and the data will remain fairly static. Which data
structure might be most suitable for this requirement?
a) TreeSet
b) HashMap
c) an array
d) LinkedList
134. You have written an application that can accept orders from multiple sources, each one of which runs in
a separate thread. One object in the application is allowed to record orders in a file. This object uses the
recordOrder method, which is synchronized to prevent conflict between threads.
While Thread A is executing recordOrder, Threads B, C, and D, in that order, attempts to execute the
recordOrder method. What happens when Thread A exits the synchronized method?

a) Thread B, as the first waiting thread, is allowed to execute the method.
b) One of the waiting threads will be allowed to execute the method, but you can't be sure which
one it will be.
c) Thread D, as the last waiting thread, is allowed to execute the method.
d) Either A or D, but never C, will be allowed to execute.


135. You need to create a class that will store a unique object element. You do not need to sort these
elements but they must be unique.
What interface might be most suitable to meet this need?
a) Set
b) List
c) Map
d) Vector
136. You want to lay out a set of buttons horizontally but with more space between the first button and the
rest.
You are going to use the GridBagLayout manager to control the way the buttons are set out. How will you
modify the way the GridBagLayout acts in order to change the spacing around the first button?
a) Create an instance of the GridBagConstraints class, call the weightx() method and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout
class.
b) Create an instance of the GridBagConstraints class, set the weightx field and then pass the
GridBagConstraints instance with the component to the setConstraints method of the
GridBagLayout class.
c) Create an instance of the GridBagLayout class, set the weightx field and then call the setConstraints
method of the GridBagLayoutClass with the component as a parameter.
d) Create an instance of the GridBagLayout class, call the setWeightx() method and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout
class.

×