Вы находитесь на странице: 1из 218

You can determine all the keys in a Map in which of the following ways?

| By ge
tting a Set object from the Map and iterating through it.
What keyword is used to prevent an object from being serialized? | transient
An abstract class can contain methods with declared bodies. | True
Select the order of access modifiers from least restrictive to most restrictive
| public, protected, default, private
Which access modifier allows you to access method calls in libraries not create
d in Java? | native
Which of the following statements are true? (Select all that apply.) | D.
A final object cannot be reassigned a new address in memory.
The keyword extends refers to what type of relationship? | A. is a
Which of the following keywords is used to invoke a method in the parent clas
s? | B. super
public static void main(String [] a) { Funcs f = new Funcs(); System.out.pri
ntln("" + f.add(1, 2)); | C. The code does not compile.
public static void main(String [] a) { int [] b = [1,2,3,4,5,6,7,8,9,0]; Syst
em.out.println("a[2]=" + a[2]); | D. The code does not compile.
What is the value of x after the following operation is performed? x = 23 %
4; | D. 3
Given the following code, what keyword must be used at line 4 in order to stop
execution of the for loop? boolean b = true; for (;;) { if (b) { | C. break
What method call is used to tell a thread that it has the opportunity to run?
| B. notify()
Given the following code, which of the results that follow would you expect? p
ackage mail; interface Box { protected void open(); void close(); public void
empty(); | A. The code will not compile because of line 4.
Assertions are used to enforce all but which of the following? | C. Exceptio
ns
The developer can force garbage collection by calling System.gc(). | B. False
Select the valid primitive data types. (Select all that apply.) | boolean char f
loat
How many bits does a float contain? | 32
What is the value of x after the following line is executed? x = 32 * (31 -
10 * 3); | 32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
| A. True
Select the list of primitives ordered in smallest to largest bit size represent
ation. | D. char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion? | D. java.text.DateFormat
The following line of code is valid. int x = 9; byte b = x; | B. False
Which of the following code snippets compile? | A. Integer i = 7; B.
Integer i = new Integer(5); int j = i; C. byte b = 7;
What will be the output of the following code? public class StringTest { public
static void main(String [] a) { String s1 = "test string"; String s2 = "tes
t string"; if (s1 == s2) { System.out.println("same"); } else { System.out.pr
intln("different"); | D. same will be printed out to the console.
Java arrays always start at index 1. | False
Which of the following statements accurately describes how variables are passe
d to methods? | C. Arguments that are primitive type are passed by value.
How do you change the value that is encapsulated by a wrapper class after you
have instan- tiated it? | D. None of the above.
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method s
hould imple- ment the custom deserialization, and what is its access mode? | A.
private readObject
A signed data type has an equal number of non-zero positive and negative value
s available. | B. False
Choose the valid identifiers from those listed here. (Choose all that apply.) |
A. BigOlLongStringWithMeaninglessName B. $int C. bytes D. $1 E.
finalist
Which of the following signatures are valid for the main() method entry point of
an application? (Choose all that apply.) | B. public static void main(String
arg[]) D. public static void main(String[] args)
If all three top-level elements occur in a source file, they must appear in whi
ch order? | D. Package declaration, imports, class/interface/enum definitions.
Consider the following line of code: int[] x = new int[25]; After execution,
which statements are true? (Choose all that apply.) | A. x[24] is 0 E.
x.length is 25
Consider the following application: class Q6 { public static void main(String
args[]) { Holder h = new Holder(); h.held = 100; h.bump(h); System.out.println
(h.held); } } class Holder { public int held; public void bump(Holder theHolde
r) { theHolder.held++; }
Consider the following application: class Q7 { public static void main(String
args[]) { double d = 12.3; Decrementer dec = new Decrementer(); dec.decrement
(d); System.out.println(d); } } class Decrementer { public void decrement(doub
le decMe) { decMe = decMe - 1.0; | C. 12.3
How can you force garbage collection of an object? | A. Garbage collection cann
ot be forced.
What is the range of values that can be assigned to a variable of type short? |
D. -215 through 215 - 1
What is the range of values that can be assigned to a variable of type byte? | D
. -27 through 27 - 1
Suppose a source file contains a large number of import statements. How do the
imports affect the time required to compile the source file? | B. Compilat
ion takes slightly more time
Suppose a source file contains a large number of import statements and one cl
ass definition. How do the imports affect the time required to load the class?
| A. Class loading takes no additional time.
Which of the following are legal import statements? | A. import java.uti
l.Vector; C. import static java.util.Vector.*;
Which of the following may be statically imported? (Choose all that apply.) | B.
Static method names C. Static field names
What happens when you try to compile and run the following code? public class Q
15 { static String s; public static void main(String[] args) { System.out.pr
intln( >> + s + << ); | C. The code compiles, and prints out >>null<<
Which of the following are legal? (Choose all that apply.) | C. int c = 0xabcd
; D. int d = 0XABCD;
Which of the following are legal? (Choose all that apply.) | A. double d = 1.2
d; B. double d = 1.2D;
Which of the following are legal? | C. char c = \u1234 ;
Consider the following code: StringBuffer sbuf = new StringBuffer(); sbuf = nu
ll System.gc(); | C. After line 2 executes, the StringBuffer object is eligib
le for garbage collection.
Which of the following are true? (Choose all that apply.) | B. Primitives are p
assed by value. D. References are passed by value.
After execution of the following code fragment, what are the values of the var
iables x, a, and b? int x, a = 6, b = 7; x = a++ + b++; | C. x = 13,
a = 7, b = 8
Which of the following expressions are legal? (Choose all that apply.) | B.
int x = 6; if (!(x > 3)) {} C. int x = 6; x = ~x;
Which of the following expressions results in a positive value in x? | A.
int x = 1; x = x >>> 5;
Which of the following expressions are legal? (Choose all that apply.) | A.
String x = "Hello"; int y = 9; x += y; C. String x = "Hello"; int y =
9; x = x + y;
What is -8 % 5? | A. -3
What is 7 % -4? | B. 3
What results from running the following code? public class Xor { public static
void main(String args[]) { byte b = 10; // 00001010 binary byte c = 15; /
/ 00001111 binary b = (byte)(b ^ c); System.out.println("b contains " + b);
| B. The output: b contains 5
What results from attempting to compile and run the following code? public class
Conditional { public static void main(String args[]) { int x = 4; System.ou
t.println("value is " + ((x > 4) ? 99.99 : 9)); | C. The output: value is 9.
0
What does the following code do? Integer i = null; if (i != null & i.int
Value() == 5) System.out.println( Value is 5 ); | B. Throws an exception.
Is it possible to define a class called Thing so that the following method can
return true under certain circumstances? boolean weird(Thing s) { Integer x
= new Integer(5); return s.equals(x); | A. Yes
Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 =
= ob2) is false, can ob1.equals(ob2) ever be true? | B. No
When a byte is added to a char, what is the type of the result? | C. int
When a short is added to a float, what is the type of the result? | C. float
Which statement is true about the following method? int selfXor(int i) { retur
n i ^ i; | A. It always returns 0.
Which of the following operations might throw an ArithmeticException? | D.
/
What is the return type of the instanceof operator? | D. A boolean
Which of the following may appear on the left-hand side of an instance of oper
ator? | A. A reference
Which of the following may appear on the right-hand side of an instance of opera
tor? (Choose all that apply.) | B. A class C. An interface
What is -50 >> 1? | D. -25
Which of the following declarations are illegal? (Choose all that apply.) | A. d
efault String s; D. abstract double d; E. abstract final double hyperbolicCos
ine();
Which of the following statements is true? | B. A final class may not have any
abstract methods.
What is the minimal modification that will make this code compile correctly? fin
al class Aaa { int xxx; void yyy() { xxx = 1; } } class Bbb extends Aaa { fin
al Aaa finalref = new Aaa(); final void yyy() { System.out.println("In metho
d yyy()"); finalref.xxx = 12345; } } | A. On line 1, remove the final modifier.
4. Which of the following statements is true? | E. Transient variables are
not serialized
5. Which statement is true about this application? class StaticStuff { sta
tic int x = 10; static { x += 5; } public static void main(String args[]) {
System.out.println("x = " + x); } static {x /= 5; } } | E. The code compiles an
d execution produces the output x = 3.
6. Which statement is true about this code? class HasStatic { private stat
ic int x = 100; public static void main(String args[]) { HasStatic hs1 = new
HasStatic(); hs1.x++; HasStatic hs2 = new HasStatic(); hs2.x++; hs1 = new HasS
tatic(); hs1.x++; HasStatic.x++; System.out.println("x = " + x); } } | E. The pr
ogram compiles and the output is x = 104.
7. Given the following code, and making no other changes, which combination
of access modifiers (public, protected, or private) can legally be placed befor
e aMethod() on line 3 and be placed before aMethod() on line 8? class SuperDuper
{ void aMethod() { } } class Sub extends SuperDuper { void aMethod() { } }
| D. line 3: private; line 8: protected
8. Which modifier or modifiers should be used to denote a variable that sho
uld not be written out as part of its class s persistent state? (Choose the short
est possible answer.) | D. transient
11. Suppose class Supe, in package packagea, has a method called doSomething
(). Suppose class Subby, in package packageb, overrides doSomething(). What ac
cess modes may Subby s version of the method have? (Choose all that apply.) | A.
public B. protected
12. Which of the following statements are true? | F. None of the above.
13. Suppose interface Inty defines five methods. Suppose class Classy decla
res that it implements Inty but does not provide implementations for any of the
five interface methods. Which is/are true? | C. The class will compile if it is
declared abstract. D. The class may not be instantiated.
14. Which of the following may be declared final? (Choose all that apply.) |
A. Classes B. Data C. Methods
15. Which of the following may follow the static keyword? (Choose all that
apply.) | B. Data C. Methods D. Code blocks enclosed in curly brackets
16. Suppose class A has a method called doSomething(), with default access.
Suppose class B extends A and overrides doSomething(). Which access modes may
apply to B s version of doSomething()? (Choose all that apply.) | A. public C. pro
tected D. Default
17. True or false: If class Y extends class X, the two classes are in differ
ent packages, and class X has a protected method called abby(), then any insta
nce of Y may call the abby() method of any other instance of Y. | B. False
18. Which of the following statements are true? | D. A final class may not
be extended.
1. Which of the following statements is correct? (Choose one.) | D.
Both primitives and object references can be both converted and cast.
5. float f = 555.5f; 6. b = s; 7. i = c; | F. Line 6
4. In the following code, what are the possible types for variable result?
(Choose the most complete true answer.) 1. byte b = 11; 2. short s
= 13; 3. result = b * ++s; | E. int, long, float, double
6. Which of the following statements is true? (Choose one.) | D. Object r
eferences can be converted in both method calls and assignments, and the rule
s governing these conversions are identical.
is a set of java API for executing SQL statements. | JDBC
method is used to wait for a client to initiate communications. | accept()
drivers that are written partly in the Java programming language and partly in
native code. These drivers use a native client library specific to the data sour
ce to which they connect. Again, because of the native code, their portability i
s limited. | Type 2
drivers that are pure Java and implement the network protocol for a specific da
ta source. The client connects directly to the data source. | Type 4
drivers that use a pure Java client and communicate with a middleware server us
ing a database-independent protocol. The middleware server then communicates the
client's requests to the data source. | Type 3
drivers that implement the JDBC API as a mapping to another data access API, su
ch as ODBC. Drivers of this type are generally dependent on a native library, wh
ich limits their portability. | Type 1
26. System.out.println(a.doit(4, 5)); | Line 26 prints a to System.out.
Which two are true if a NullPointerException is thrown on line 3 of class C? (Ch
oose two.) | b. The code on line 29 will be executed. e. The exception wi
ll be propagated back to line 27.
dialog prevents user input to other windows in the application unitl the dialog
is closed. | Modal
A Java monitor must either extend Thread or implement Runnable. | False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.) |
You cannot specify which thread will get notified.
A signed data type has an equal number of non-zero positive and negative values
available. | False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread. | False
An object is used to submit a query to a database | Statement
An object is uses to obtain a Connection to a Database | Driver Manager
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? (Choose one.) | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? (Choose one.) | java.util.Ar
rays.equals(a1, a2);
A programmer wants to create an interface called B that has A as its parent. Whi
ch interface declaration is correct? | public interface B extends A { }
How can you force garbage collection of an object? (Choose one.) | Garbage colle
ction cannot be forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? (Choose one.) | Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory? (Choose one.)
| String[] contents = myFile.list();
How many locks does an object have? (Choose one.) | 1
If all three top-level elements occur in a source file, they must appear in whic
h order? (Choose one.) | Package declaration, imports, class/interface/enum defi
nitions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any other instance of Y. | False
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use? (Choose one.) | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? (Choose one.) | Comparable interface and its compareTo me
thod.
Interface ... helps manage the connection between a Java program and a databas
e. | Connection
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks? | Yes
DBC supports ... and ... models. | Two-tier and three-tier
MVC is short call of | Model-View-Controller
Select correct statement about RMI. (choose 1) | All the above
Select correct statement(s) about remote class.(choose one) | All the others cho
ices
Select correct statements about remote interface. (choose 1) | All the others ch
oices
Select INCORRECT statement about serialization. (choose 1) | When an Object Out
put Stream serializes an object that contains references to another object, ever
y referenced object is not serialized along with the original object.
Select INCORRECT statement about deserialize. (choose 1) | We use readObject() m
ethod of ObjectOutputStream class to deserialize.
Select incorrect statement about RMI server.(choose 1) | A client accesses a rem
ote object by specifying only the server name.
Select incorrect statement about ServerSocket class. (choose 1) | To make the ne
w object available for client connections, call its accept() method, which retur
ns an instance of ServerSocket
Select incorrect statement about Socket class. (choose 1) | The java.net.Socket
class contains code that knows how to find and communicate with a server through
UDP.
Select the correct statement about JDBC two-tier processing model. | A user's co
mmands are delivered to the database or other data source, and the results of th
ose statements are sent back to the user.
SQL keyword ... is followed by the selection criteria that specify the
rows to select in a query | WHERE
Statement objects return SQL query results as ... objects | ResultSetSupp
ose a source file contains a large number of import statements and one class def
inition. How do the imports affect the time required to load the class? (Choose
one.) | Class loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? (Choose one.) | Comp
ilation takes slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? (Choose one.) | C must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? (Choose one) | private
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.) | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? (Choose one.)
| for (float f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? (Choose one.) | When the type of x i
s Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? (Choose one.) | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.) | if (x
== y)
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access mo
de should the readObject() method have? (Choose one.) | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? (Choose one.) | Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one statement is true abou
t this strategy? | The strategy fails because you cannot add static methods to a
subclass.
Swing components cannot be combined with AWT components. | true
The ... class is the primary class that has the driver information. | D
river Manager
The ... class is used to implement a pull-down menu that provides a num
ber of items to select from. | Menu
The element method alters the contents of a Queue. | False
The Swing component classes can be found in the package. | javax.swing
There are two classes in Java to enable communication using datagrams namely. |
DataPacket and DataSocket
URL referring to databases use the form: | protocol:subprotocol:datasoursename
What is -50 >> 2 | -13
What is 7 % -4? | 3
What is -8 % 5? | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? (Choose one.) | There is no difference; the rules a
re the same.
What is the range of values that can be assigned to a variable of type byte? | -
2^7 through 2^7 - 1
What is the return type of the instanceof operator? | A boolean
What method of the java.io.File class can create a file on the hard drive? | cre
ateNewFile()
When a byte is added to a char, what is the type of the result? | int
When a negative byte is cast to a long, what are the possible values of the resu
lt? | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? | All the above
When a short is added to a float, what is the type of the result? | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? | writing a line separator to the strea
m
When does an exception's stack trace get recorded in the exception object? | Whe
n the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? | When the
exception is being thrown in response to catching of a different exception type
When is it appropriate to write code that constructs and throws an error? | neve
r
When is x & y an int? | sometimes
When the user attempts to close the frame window, ... event in generated. | w
indow closing
When the user selects a menu item, ... event is generated. | Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform- independent code that a
Java Virtual Machine can understand. What is this platform-independent code cal
led? | bytecode
Whenever a method does not want to handle exceptions using the try block, the ..
. is used. | throws
Which class and static method can you use to convert an array to a List? | Array
s.asList
Which is four-step approach to help you organize your GUI thinking. | Identify n
eeded components. Isolate regions of behavior. Sketch the GUI. Choose layout man
agers.
Which is the four steps are used in working with JDBC? | Connect to the database
Create a statement and execute the query Look at the result set Close connectio
n
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed? | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? | sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? | class Man { private Dog bestFriend; }
Which methods return an enum constant s name? | name() toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? | transient
Which of the following are legal argument types for a switch statement? | byte i
nt char
Which of the following are legal loop definitions? | None of the above.
Which of the following are methods of the java.util.SortedSet interface? | All t
he above
Which of the following are true? | The JVM runs until there are no non-daemon t
hreads.
Which of the following are true? | An enum may contain public method definition
s. An enum may contain private data.
Which of the following are true? | Primitives are passed by value. References a
re passed by value.
Which of the following are true? | An anonymous inner class may implement at mo
st one interface. An anonymous inner class may extend a parent class other than
Object.
Which of the following are valid arguments to the DataInputStream constructor? |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or? | All the above
Which of the following calls may be made from a non-static synchronized method?
| All the above
Which of the following classes implement java.util.List? | java.util.ArrayList
java.util.Stack
Which of the following classes implements a FIFO Queue? | LinkedList
Which of the following expressions results in a positive value in x? | int x = 1;
x = x >>> 5;
Which of the following interfaces does not allow duplicate objects? | set
Which of the following is not appropriate situations for assertions? | Precondit
ions of a public method
Which of the following is NOTa valid comment: | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method? | Throw java.lang.IllegalArgumentException.
Which of the following may appear on the left-hand side of an instance of operat
or? | A reference
Which of the following may appear on the right-hand side of an instance of opera
tor? (Choose two.) | Class interface
Which of the following may be declared final? (Choose two.) | Classes Methods
Which of the following may be statically imported? (Choose two.) | Static method
names Static field names
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.) | All of the others
Which of the following may not be synchronized? (Choose one.) | Classes
Which of the following methods in the Thread class are deprecated? (Choose one.)
| suspend() and resume()
Which of the following operations might throw an ArithmeticException? (Choose on
e.) | None of these
Which of the following operations might throw an ArithmeticException? (Choose on
e.) | /
Which of the following operators can perform promotion on their operands? (Choos
e three.) | + - ~
Which of the following restrictions apply to anonymous inner classes? (Choose on
e.) | They must be defined inside a code block.
Which of the following should always be caught? (Choose one.) | Checked exceptio
ns
Which of the following signatures are valid for the main() method entry point of
an application? (Choose two.) | public static void main(String[] args) public s
tatic void main(String arg[])
Which of the following statements about the wait() and notify() methods is true?
(Choose one.) | The thread that calls wait() goes into the monitor s pool of wait
ing threads.
Which of the following statements about threads is true? (Choose one.) | Threads
inherit their priority from their parent thread.
Which of the following statements are true? (Choose one.) | A final class may no
t be extended.
Which of the following statements are true? (Choose one.) | Given that Inner is
a nonstatic class declared inside a public class Outer and that appropriate cons
tructor forms are defined, an instance of Inner can be constructed like this: ne
w Outer().new Inner()
Which of the following statements is correct? (Choose one.) | Both primitives an
d object references can be both converted and cast.
Which of the following statements is true? (Choose one.) | Transient variables a
re not serialized.
Which of the following statements is true? (Choose one.) | Object references can
be converted in both method calls and assignments, and the rules governing thes
e conversions are identical.
Which of the statements below are true? (Choose one.) | Unicode characters are a
ll 16 bits.
is a set of java API for executing SQL statements | JDBC
method is used to wait for a client to initiate communications | accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect | Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source | Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source | Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally dependent on a native library, whi
ch limits their portability | Type 1
System.out.println(a.doit(4, 5)) | Line 26 prints a to System.out
Which two are true if a NullPointerException is thrown on line 3 of class C | co
de on line 29, The exception
What lines are output if the constructor at line 3 throws a MalformedURLExceptio
n | Bad URL, Doing finally, Carrying
What lines are output if the methods at lines 3 and 5 complete successfully with
out throwing any exceptions | Success, Doing, Carrying
If lines 24, 25 and 26 were removed, the code would compile and the output would
be 1 | 3.The code, would be 1, 2
An exception is thrown at runtime | An exception
first second first third snootchy 420 | third second first snootchy 420
dialog prevents user input to other windows in the application unitl the dialog
is closed | Modal
You would like to write code to read back the data from this file. Which solutio
ns will work | 2.FileInputStream, RandomAccessFile
A Java monitor must either extend Thread or implement Runnable | F
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1 | You cannot specify
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these ways | public void logIt(
String... msgs)
A signed data type has an equal number of non-zero positive and negative values
available | F
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread | F
catch (InterruptedException e) | running some time
object is used to submit a query to a database | Statement
object is uses to obtain a Connection to a Database | DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b | x13, a7, b8
Yen and Euro both return correct Country value | 2.Euro returns, error at line
25
BigOlLongStringWithMeaninglessName | tick all
Compilation of class A will fail. Compilation of class B will succeed | B fail,
A succeed
Line 46 will compile if enclosed in a try block, where TestException is caught |
2.if the enclosing, is caught
Holder h = new Holder() | 101
Decrementer dec = new Decrementer() | 12.3
Test t = (new Base()).new Test(1) | 2.new Test(1), new Test(1, 2)
Base(int j, int k, int l) | 2.Base(), Base(int j, int k)
Line 12 will not compile, because no version of crunch() takes a char argument |
output: int version
output results when the main method of the class Sub is run | Value 5 This value
6
Float floater = new Float(3.14f) | Line 6
The application must be run with the -enableassertions flag or another assertion
enabling flag | dai nhat, one or more
After line 3 executes, the StringBuffer object is eligible for garbage collectio
n | line 2 executes..collection
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | type SwampThing
The code will compile and run, but the cast in line 6 is not required and can be
eliminated | The code will compile and run
for (int i = 0; i < 2; i++) | 4.i0,j12 - i1,j02
outer: for (int i = 0; i < 2; i++) | i = 1 j = 0
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | Line 7 will not compile
int[] x = new int[25] | 2.x[24]=0, x.length is 25
public float aMethod(float a, float b) throws Exception | int a,b float p,q
public float aMethod(float a, float b, int c) throws Exception | 3.int a,b. floa
t a,b-int c. private
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i | Arrays.equals(a1, a2)
Assuming the class does not perform custom serialization, which fields are writt
en when an instance of Xyz is serialized | 3.Public, Private, Volatile
can legally be placed before aMethod() on line 3 and be placed before aMethod()
on line 8 | 3: private; 8: protected
NUTMEG, CINNAMON, CORIANDER, ROSEMARY | 3.Spice sp, Spice, String
List<String> names = new ArrayList<String>() | 2.Iterator, for
Compilation fails because of an error in line 15 | error in line 19
1 2 3 | 2 3
public interface B inheritsFrom A | B extends A
protected double getSalesAmount() { return 1230.45; } | 2.public, protected
Line 16 creates a directory named d and a file f within it in the file system | 3.An
exception, Line 13, line 14
Nav.Direction d = Nav.Direction.NORTH | Nav.Direction.NORTH
new class Foo { public int bar() { return 1; } } | new Foo()
IllegalArgumentException | StackOverflowError
Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw() | Shape s = ne
w Circle...s.draw()
Compilation fails because of an error in line 12 | 1 2 3
NullPointerException | Compilation fails
A NumberFormatException is thrown by the parse method at runtime | Compilation f
ails
An exception is thrown at runtime | Compilation fails
passed An AssertionException is thrown without the word stuff added to the stack t
race | An AssertionError...with the
collie | collie harrier
doStuff x = 6 main x = 6 | doStuff x =5 main x =5
The setCardlnformation method breaks encapsulation | The ownerName
The value of all four objects prints in natural order | Compilation fails...line
29
The code on line 33 executes successfully | 3.33 throws, 35 throws, 33 executes
What is the result if a NullPointerException occurs on line 34 | ac
Compilation will fail because of an error in line 55 | Line 57...value 3
java -ea test file1 file2 | 2.java -ea test, dai nhat
String s = 123456789 ; s = (s- 123 ).replace(1,3, 24 ) - 89 | 2.delete(4,6), delete(2,5)
rt( 1, 24 )
The Point class cannot be instatiated at line 15 | Line.Point p = new Line.Point
()
for( int i=0; i< x.length; i++ ) System.out.println(x[i]) | 2.for(int z : x),
dai nhat
int MY_VALUE = 10 | 3.final, static, public
Compilation fails because of an error in line: public void process() throws Runt
imeException | A Exception
How can you ensure that multithreaded code does not deadlock | There is no singl
e
How can you force garbage collection of an object | Garbage collection
How do you prevent shared data from being corrupted in a multithreaded environme
nt | Access the variables
How do you use the File class to list the contents of a directory | String[] con
tents
The number of bytes depends on the underlying system | 8
How many locks does an object have | One
If all three top-level elements occur in a source file, they must appear in whic
h order | Package declaration, imports
the two classes are in different packages, and class X has a protected method ca
lled abby(), then any instance of Y may call the abby() method of any | F
TestThread3 ttt = new TestThread3 | Y
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method | Comparable...compareTo
after execution of line 1, sbuf references an instance of the StringBuffer class
. After execution of line 2, sbuf still references the same instance | T
what are the possible types for variable result | int, long, float, double
helps manage the connection between a Java program and a database | Connection
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances | Y
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks | Y
JDBC supports ______ and ______ models | Two-tier and three-tier
MVC is short call of | Model-View-Controller
No output because of compile error at line: System.out.println("b="+b) | b = b *
b1
Object ob2= new Object() | Have a nice day
Object ob2= ob1 | ob1 equals ob2, ob1==ob2
String s2 = "xyz" | Line 4, Line 6
String s2 = new String("xyz") | Line 6
String s2 = new String(s1) | Line 6
Select correct statement about RMI | All the above
Select correct statement(s) about remote class | All the others choices
Select correct statements about remote interface | All the others choices
Select INCORRECT statement about serialization | When an Object Output
Select INCORRECT statement about deserialize | We use readObject
Select incorrect statement about RMI server | A client accesses
Select incorrect statement about ServerSocket class | To make the new object
Select incorrect statement about Socket class | server through UDP
Select the correct statement about JDBC two-tier processing model | A user's com
mands
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query | WHERE
Statement objects return SQL query results as | ResultSet
When a JDBC connection is created, it is in auto-commit mode | Both 1 and 2 are
true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block | If the JVM doesn't crash
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class | no
additional time
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file | slightly more time
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable | C must have a
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable | B must have a
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething() | private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething() | 2.public, protec
ted
void doSomething(int a, float b) | public...(int a, float b)
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods | 2.declared abstract, may not be
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries | for (float f:
salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal | When the...x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant | if (x == y)
Suppose you are writing a class that will provide custom deserialization. What a
ccess mode should the readObject() method have | private
Suppose you are writing a class that will provide custom serialization. What acc
ess mode should the writeObject() method have | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality | Override run()
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods | subclass java.lang.Math
Swing components cannot be combined with AWT components | T
class is the primary class that has the driver information | DriverManager
class is used to implement a pull-down menu that provides a number of items to s
elect from | Menu
The element method alters the contents of a Queue | F
The Swing component classes can be found in the | javax.swing
There are two classes in Java to enable communication using datagrams namely | D
ataPacket and DataSocket
Compilation of Parrot.java fails at line 7 because method getRefCount() is stati
c in the superclass, and static methods may not be overridden to be nonstatic |
dai nhat: nonstatic
Compilation of Nightingale will succeed, but an exception will be thrown at line
10, because method fly() is protected in the superclass | The program...After:
2
void doSomething() throws IOException, EOFException | ngan-dai nhat, throws EOFE
xception
URL referring to databases use the form | protocol:subprotocol:datasoursename
What are the legal types for whatsMyType | There are no possible legal types
What does the following code do | Throws an exception
There is no output because the code throws an exception at line 1 | output is i
= 20
1000 | -1
What happens when you try to compile and run the following application | thrown
at line 9
The code compiles, and prints out >>null<< | out >>null<<
An exception is thrown at line 6 | thrown at line 7
What is -50 >> 2 | -13
What is 7 % -4 | 3
What is -8 % 5 | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion | There is no difference
The code will compile as is. No modification is needed | On line 1, remove
What is the range of values that can be assigned to a variable of type byte | ?2
mu7 through 2mu7 ? 1
What is the range of values that can be assigned to a variable of type short | ?
2mu15 through
The code compiles and executes; afterward, the current working directory contain
s a file called datafile | The code fails to compile
What is the return type of the instanceof operator | A boolean
What method of the java.io.File class can create a file on the hard drive | crea
teNewFile()
The output: value is 99.99 | value is 9.0
The output: b contains 250 | b contains 5
What would be the output from this code fragment | message four
When a byte is added to a char, what is the type of the result | int
When a negative byte is cast to a long, what are the possible values of the resu
lt | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt | All the above
When a short is added to a float, what is the type of the result | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two | writing a line
When does an exception's stack trace get recorded in the exception object | is c
onstructed
When is it appropriate to pass a cause to an exception's constructor | in respon
se to catching
When is it appropriate to write code that constructs and throws an error | Never
When is x & y an int | Sometimes
When the user attempts to close the frame window, _______ event in generated | w
indow closing
When the user selects a menu item, _______ event is generated | Action event
Java programming language, the compiler converts the human-readable source file
into platform-independent code that a Java Virtual Machine can understand | byte
code
Whenever a method does not want to handle exceptions using the try block, the |
throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database | String url =jdbc:odbc
Which class and static method can you use to convert an array to a List | Arrays
.asList
Which is four-step approach to help you organize your GUI thinking | Identify, I
solate, Sketch
Which is the four steps are used in working with JDBC | Connect, Create, Look
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r | sc.useDelimiter("\\d")
Man has the best friend who is a Dog | private Dog bestFriend
Which methods return an enum constant s name | 2.name(), toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state | transient
Which of the following are legal argument types for a switch statement | 3.byte,
int, char
Which of the following are legal enums | 3.ngan-dai nhat, lion int weight
Which of the following are legal import statements | 2.import...Vector, Vector.*
Which of the following are legal loop constructions | for (int k=0, j+k != 10; j
++,k++)
Which of the following are legal loop definitions | None of the above
double d = 1.2d5 | 2.double d = 1.2d, 1.2D
int d = 0XABCD | 2.int c = 0xabcd, dai nhat
char c = 0x1234 | 2.0x.., '\u1234'
Vector <String> theVec = new Vector<String>() | 2.List...<String>(), dai nhat
Which of the following are methods of the java.util.SortedMap interface | headMa
p, tailMap, subMap
Which of the following are methods of the java.util.SortedSet interface | All th
e above
System.out has a println() method | All the above
The JVM runs until there is only one non-daemon thread | are no non-daemon
When an application begins running, there is one non-daemon thread, whose job is
to execute main() | 3.nhat, thread, non-daemon thread
When you declare a block of code inside a method to be synchronized, you can spe
cify the object on whose lock the block should synchronize | 2.the method always
, nhat
An enum definition should declare that it extends java.lang.Enum | 2.contain pub
lic, private
Primitives are passed by reference | 2.by value
An anonymous inner class that implements several interfaces may extend a parent
class other than Object | implement at most, class may extend
Which of the following are valid arguments to the DataInputStream constructor |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or | All the above
Which of the following calls may be made from a non-static synchronized method |
All the above
Which of the following classes implement java.util.List | 2.ArrayList, Stack
Which of the following classes implements a FIFO Queue | LinkedList
Which of the following declarations are illegal | 3.ngan-dai nhat, double d
int x = 6; if (!(x > 3)) | 2.dai nhat, x = ~x
String x = "Hello"; int y = 9; if (x == y) | 2.ngan nhat, x=x+y
Which of the following expressions results in a positive value in x | int x = 1;
x = x >>> 5
Which of the following interfaces does not allow duplicate objects | Set
Which of the following is not appropriate situations for assertions | Preconditi
ons of a public method
Which of the following is NOTa valid comment | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method | IllegalArgumentException
Readers have methods that can read and return floats and doubles | None of the a
bove
An enum definition may contain the main() method of an application | All the abo
ve
Which of the following may appear on the left-hand side of an instanceof operato
r | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or | 2.A class, An interface
Which of the following may be declared final | 2.Classes, Methods
Which of the following may be statically imported | 2.Static method, Static fiel
d
Which of the following may follow the static keyword | 3.Data, Methods, Code blo
cks
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation | All of
Which of the following may not be synchronized | Classes
Which of the following may override a method whose signature is void xyz(float f
) | 2.void, public void xyz(float f)
Which of the following methods in the Thread class are deprecated | suspend() an
d resume()
Which of the following operations might throw an ArithmeticException | None of
Which of the following operators can perform promotion on their operands | 3.con
g, tru, xap xi
Which of the following restrictions apply to anonymous inner classes | must be d
efined
Which of the following should always be caught | Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application | 2.static void...(String arg[])
Which of the following statements about the wait() and notify() methods is true
| calls wait() goes into
Which of the following statements about threads is true | Threads inherit their
A final class may not contain non-final data fields | may not be extended
An abstract class must declare that it implements an interface | None
An abstract class may not have any final methods | Only statement 2
Only object references are converted automatically; to change the type of a prim
itive, you have to do a cast | Both primitives
Transient methods may not be overridden | variables are not
Object references can be converted in both method calls and assignments, but the
rules governing these conversions are very different | conversions are identica
l
Bytecode characters are all 16 bits | Unicode characters
To change the current working directory, call the changeWorkingDirectory() metho
d of the File class | None
When you construct an instance of File, if you do not use the file-naming semant
ics of the local machine, the constructor will throw an IOException | None
When the application is run, thread hp1 will execute to completion, thread hp2 w
ill execute to completion, then thread hp3 will execute to completion | None of
Compilation succeeds, although the import on line 1 is not necessary. During exe
cution, an exception is thrown at line 3 | fails at line 2
Compilation fails at line 1 because the String constructor must be called explic
itly | succeeds. No exception
Line 4 executes and line 6 does not | Line 6 executes
There will be a compiler error, because class Greebo does not correctly implemen
t the Runnable interface | Runnable interface
The acceptable types for the variable j, as the argument to the switch() constru
ct, could be any of byte, short, int, or long | value is three
The returned value varies depending on the argument | returns 0
Lines 5 and 12 will not compile because the method names and return types are mi
ssing | output x = 3
Line 13 will not compile because it is a static reference to a private variable
| output is x = 104
Which statements about JDBC are NOT true | 2.database system, DBMS
Which two code fragments correctly create and initialize a static array of int
elements | 2.a = { 100,200 }, static
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework | 2.Map, Collection
A new directory called dirname and a new file called filename are created, both
in the current working directory | No directory
protected class Cat extends Owner | public class Cat extends Pet
Date vaccinationDue | 2.boolean, String
What is -15 % -10 | -5
command line on a Windows system | 2.must contain the statement, the file
The string created on line 2 does not become eligible for garbage collection in
this code | After line 3
When the application runs, what are the values of n and w.x after the call to bu
mp() in the main | n is 10, w.x is 11
The addAll() method of that interface takes a single argument, which is a ref
erence to a collection whose elements are compatible with E. What is the declar
ation of the addAll() method | addAll(Collection<? extends E> c)
If you want a vector in which you know you will only store strings, what are the
advantages of using fancyVec rather than plainVec | Attempting to...compiler er
ror
When should objects stored in a Set implement the java.util.Comparable interfac
e | Set is a TreeSet
What relationship does the extends keyword represent | is a
class bbb.Bbb, which extends aaa.AAA, wants to override callMe(). Which access m
odes for callMe() in aaa.AAA will allow this | 2.public, protected
Lemon lem = new Lemon(); Citrus cit = new Citrus() | 3.cit = lem, cit=(Citrus),
lem=(lemon)
it also has a method called chopWoodAndCarryWater(), which just calls the other
two methods | inappropriate cohesion, inappropriate coupling
sharedOb.wait() | 2.aThread.interrupt, sharedOb.notifyAll
line prints double d in a left-justified field that is 20 characters wide, with
15 characters to the right of the decimal point | System.out.format("%-20.15f",
d)
What code at line 3 produces the following output | String delim = \\d+
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc | NumberFormat.getInstance(loc)
you want to use a DateFormat to format an instance of Date. What factors influ
ence the string returned by DateFormat s format() method | 2.LONG, or FULL, The lo
cale
you want to create a class that compiles and can be serialized and deserialized
without causing an exception to be thrown. Which statements are true regarding
the class | 2.dai nhat, ngan nhat
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
What interfaces can be implemented in order to create a class that can be serial
ized | 2.dai nhat, ngan nhat
The file contains lines of 8-bit text, and the 8-bit encoding represents the lo
cal character set, as represented by the cur- rent default locale. The lines are
separated by newline characters | FileReader instance
shorty is a short and wrapped is a Short | all
How is IllegalArgumentException used | 2.certain methods, public methods
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction | None
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime | 2.assert x == 4
int[] ages = { 9, 41, 49 }; int sum = 0 | 2.i<ages.length, for (int i:ages)
Which of the following types are legal arguments of a switch statement | enums,
bytes
class A extends java.util.Vector { private A(int x) | does not create a defau
lt
void callMe(String names) | method, names is an array
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards | public Color ge
tTheTint()
are valid arguments to the DataInputStream constructor | FileInputStream
are valid mode strings for the RandomAccessFile constructor | r, rw, rws, rwd
method of the java.io.File class can create a file on the hard drive | createNe
wFile()
class A extends Object; Class B extends A; and class C extends B. Of these, only
class C implements java.io.Externalizable | C must have
class A extends Object; class B extends A; and class C extends B. Of these, only
class C implements java.io.Serializable | B must have
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
you are writing a class that will provide custom serialization. The class implem
ents java.io.Serializable (not java.io.Externalizable) | private
How do you use the File class to list the contents of a directory | String[] c
ontents = myFile.list();
call returns true if a1 and a2 have the same length, and a1[i].equals(a2[i]) fo
r every legal index i | java.util.Arrays.equals(a1, a2)
line of code tells a scanner called sc to use a single digit as a delimiter | sc
.useDelimiter( \\d )
you want to write a class that offers static methods to compute hyperbolic trigo
nometric functions. You decide to subclass java.lang.Math and provide the new f
unctionality as a set of static methods | java.lang.Math
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string | none
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do | Override run()
you prevent shared data from being corrupted in a multithreaded environment | Ac
cess the variables
Is it possible to write code that can execute only if the current thread owns
multiple locks | yes
Which of the following may not be synchronized | Classes
statements about the wait() and notify() methods is true | pool of waiting th
reads
methods in the Thread class are deprecated | suspend() and resume()
A Java monitor must either extend Thread or implement Runnable | F
One of the threads is thr1. How can you notify thr1 so that it alone moves from
the Waiting state to the Ready state | You cannot specify
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread | F
Which methods return an enum constant s name | name(), toString()
restrictions apply to anonymous inner classes | inside a code block
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual d
escription of its markings | boolean, string
Which of the following are valid declarations? Assume java.util | 1Vector 2Set 3
Map string,string
You can determine all the keys in a Map in which of the following ways | Set ob
ject from the Map
What keyword is used to prevent an object from being serialized | transient
abstract class can contain methods with declared bodies. | E. public, protecte
d, default, private
access modifier allows you to access method calls in libraries not created in J
ava | native
Which of the following statements are true? (Select all that apply.) | object c
annot reassigned
The keyword extends refers to what type of relationship | is a
keywords is used to invoke a method in the parent class | super
What is the value of x after the following operation is performed | 3
method call is used to tell a thread that it has the opportunity | notify()
Assertions are used to enforce all but which | Exceptions
force garbage collection by calling System.gc(). | B. False
Select the valid primitive data type | 1.boolean 2.char 3.float
How many bits does a float contain | 32
What is the value of x after the following line is executed | 32
StringBuffer is slower than a StringBuilder, but a StringBuffer | True
list of primitives ordered in smallest to largest bit size representation | D.
char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion | java.text.DateFormat
int x = 9; byte b = x | False
Which of the following code snippets compile | 1.Integer 2.Integer 3.byte
Java arrays always start at index 1 | False
accurately describes how variables are passed to methods | that are primitive t
ype are passed by value
change the value that is encapsulated by a wrapper class after you have instan
| None of the above.
The class implements java.io.Serializable (and not java.io.Externalizable) | pri
vate readObject
A signed data type has an equal number of non-zero positive and negative value
s | False
signatures are valid for the main() method entry point of an application | publi
c static void main(String[] args)
three top-level elements occur in a source file, they must appear | Package decl
aration, imports, class/interface/enum definitions
int[] x = new int[25] | x[24] is 0 and x.length is 25
How can you force garbage collection of an object | Garbage collection cannot
be forced.
range of values that can be assigned to a variable of type short | -215 through
215 - 1
range of values that can be assigned to a variable of type byte | -27 through 2
7 - 1
How do the imports affect the time required to compile the source file | Compi
lation takes slightly more time
How do the imports affect the time required to load the class? | Class loading
takes no additional time
legal import statements | 1.import java.util.Vector 2.import static java.ut
il.Vector
may be statically imported | 1.Static method names 2.Static field names
int c = 0xabcd and int d = 0XABCD | 2 dap an
double d = 1.2d and double d = 1.2D | 2 dap an
char c = \u1234 | 1 dap an
passed by value and passed by value | 2 dap an
int x = 6; if (!(x > 3)) and int x = 6; x = ~x | 2 dap an
int x = 1; x = x >>> 5 | 1 dap an
int y = 9; x += y; and int y = 9; x = x + y; | 2 dap an
What is -8 % 5 | -3
What is 7 % -4? | 3
ob1 == ob2 | No
When a byte is added to a char | int
When a short is added to a float | float
ArithmeticException | 1.None of these 2./
What is the return type of the instanceof operator | boolean
may appear on the left-hand side of an instanceof operator | reference
may appear on the right-hand side of an instanceof operator | class and interfa
ce
What is -50 >> 1 | -25
default String s ,, abstract double d ,, double hyperbolic | 3 dap an
A final class may not have any abstract methods | true
denote a variable that should not be written out as part of its class s persistent
state | transient
Both primitives and object references can be both converted and cast | dap an
and the rules governing these conversions are identical | dap an
may legally appear as the new type (between the parentheses) in a cast operati
on | All of the above
type of x is a class, and the declared type of y is an interface. When is the as
signment x = y | When the type of x is Object
xarr is an array of XXX, and the type of yarr is an array of YYY | Sometimes
When is x & y an int | Sometimes
negative long is cast to a byte | All of the above
negative byte is cast to a long | Negative
operators can perform promotion on their operands | + - ~(nga)
difference between the rules for method-call conversion and the rules for assign
ment conversion | There is no difference
Which of the following are appropriate situations for assertions | DAP AN SAI :
Preconditions of a public method
appropriate way to handle invalid arguments in a public method | IllegalArgumen
tException
Suppose salaries is an array containing floats | for (float f:salaries)
Suppose a method called finallyTest() consists of a try block | If the JVM does
n t crash and
appropriate to pass a cause to an exception s constructor | thrown in response to
catching of a different exception type
Which of the following should always be caught | Checked exceptions
When does an exception s stack trace get recorded in the exception object | is c
onstructed
A dialog prevents user input to other windows in the application umtl the dialog
is closed | Modal
public float aMethod(float x. float y) {} | 1
Runtime Exception | 1
What is the output of the following code class Main { static intk- 10; static {k
?- 5;} public static void main(Strmg argsQ){ System outpnntln(k).}static {k 5;}
} | 20
Assuming any exception handling has been set up. which of the following will cre
ate an instance of the RandomAccessFile class? | RandomAccessFile raf-new Random
AccessFilefmyfile txr."rW)
How do you prevent shared data from being corrupted in a | Access the variables
only via synchronized mothods
Compile time error | 1
A thread's run() method includes the following lines 1 try{ 2 sleep(IOO);3.} c
atch (InterruptedException e) {} | At line 2. the thread will stop running It wi
ll resume running some time after 100 milliseconds have elapsed
When a user selects a menu,______is generated | Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform-independent code that a
Java Virtual Machine can understand What is this platform-independent code calle
d? | bytecode
Which of the following operators can perform promotion on their operands? (Selec
t two) | + -
Select INCORRECT statement about FlowLayout | The Flow layout manager always hon
ors a component's preferred size D The Flow layout manager arranges components i
n horizontal rows
Which line contains only legal statements? | int x=6 x = ~x
Which Man class properly represents the relationship 'Man has the best friend wh
o is a Dog'? | class Man {private BestFnend dog;}
99 100 102 | 1
Select the most correct statement | A thread is in the ready state after it has
been created and started
Which of the following statements) is(are) true? 1)An abstract class can not hav
e any final methods 2)A final class may not have any abstract methods | Both sta
tement 1 and 2
What is the return type of the instanceof operator? | boolean
Study the statements: 1) When a JDBC connection is created, it is in auto
-commit mode 2) 0nce auto-commit mode is disabled, no SQL statements will be com
mitted until you call the method commit explicitly | both 1 and 2 are true
the code on line 29 will be executed | 1
No such file found. Doing finally.-1 | 1
Which of the following is true about Wrapped classes? | Wrapper classes are. Boo
lean. Char. Byte. Short. Integer. Long. Float and Double
Which of the followings statements is true? | The GndBagLayout manager is the de
fault manager for JFrame
What is the range of values that can be assigned to a variable of type short? |
2 mu 15 through 2 mu 15 -1
When is it appropriate to pass a cause to an exception's constructor? | When the
exception is being thrown in response to catching of a different exception type
Which of the statements below is true"? | When you construct an instance of File
, the file will not be created even if the corresponding file does not exist on
the local file system
Which of the following may follow the static keyword9 (Select two) | Methods and
Code blocks endosed in curly brackets
Which of the following statements is true | Constructors are not inherited
public interface B inheritsFrom A {} | 1
Which of the following statements is true | A for statement can loop infinitely,
for example for(;;);
Select INCORRECT statement about deserialize (choose 1) | We use readObjectO met
hod of ObjectOutputStream dass to deserialize
a#b, a==c | 1
Is it possible to define a dass called Thing so that the following method can re
turn true under certain drcumstances? boolean weirdfThing s) {Integer x = new ln
teger(5); return s.equals(x);} | yes
A(n)_____object is uses to obtain a Connection to a Database | DnverManager
Study the following Java statements:String sl= Hetlo ;String s2= Hello";String s3= He
llo";String s4= new Stnng( Hello");How many strings, specified by the above code,
are stored in the memory of the program | 2
What is the difference between a TextArea and a TextField | A TextArea can handl
e multiple lines of text
You have been given a design document for a veterinary registration system for i
mplementation in Java. It states"A pet has an owner, a registration date, and a
vacdnation-due date A cat is a pet that has a flag indicating whether it has bee
n neutered, and a textual description of its markings"Given that the Pet class h
as already been defined, which of the following fields would be appropriate for
inclusion in the Cat class as members9 (Select the most appropriate two declarat
ions) | String markings boolean neutered;
A___dialog prevents user input to other windows in the application unitl the dia
log is closed.|Modal.
A value variable contains data's value.|True.
A reference variable contains the address of data.|True.
The Reader/Writer class hierarchy is character-oriented, and the InputStream/Out
putStream class hierarchy is byte-oriented.|True.
String s = new String("Bicycle"); int iBegin = 1; char iEnd = 3; System.out.prin
tln(s.substring(iBegin, iEnd));|Bic.
Which of the following layout manager will present components with the same size
.|java.awt.GridLayout.
Object references can be converted in both method calls and assignments, and the
rules goverming these conversions are identical.|True.
The Reader/Writer class hierarchy is character-oriented, and the InputStream/Out
putStream class hierarchy is byte-oriented.|True.
String s = new String("Bicycle"); int iBegin = 1; char iEnd = 3; System.out.prin
tln(s.substring(iBegin, iEnd));|Bic.
Which of the following layout manager will present components with the same size
.|java.awt.GridLayout.
Object references can be converted in both method calls and assignments, and the
rules goverming these conversions are identical.|True.
Which is four-step approach to help you organize your GUI thinking.|Identifi-Iso
late-Sketch-Choose.
Which statement is true about BorderLayout?.|...and the center of a container.
A program can suggest that garbage collection be performed but not force it.|Tru
e.
An object's lock is a mechanism that is used by multilple threads to obtain sync
hronized access to the object.|True.
Which statements about JDBC are NOT true?.|database system - any kind of DBMS.
Which of the following statements is true about two base protocols used for netw
orking TCP(Transmission Control Protocol) and UDP(User Datagram Protocol)?|TCP i
s a connection-based protocol and UDP is not connection-based protocol.
Which of the following is not a keyword or a reserved word in Java?.|Then.
MVC is short call of|Model-View-Controller.
How can you ensure that multithreaded code does not deadlock?|There is no single
technique that can guarantee non-deadlocking code.
If you need a Set implementation that provides value-ordered iteration, which ca
lss should you use?|TreeSet.
When is a thread in suspended state?|When wait() method is called.
Which of the following declarations is legal?|transient int i = 41;
Unicode characters are all 16 bits.|True.
Which of the following statements can be used to call a constructor of the super
class from its sub-class?|super();
Which of the following protocols is a connection-based protocol that provides a
reliable flow of data between two computers?|Transmission Control Protocol.
Which of the following statements about monitor is true?|A monitor is an instanc
e of any class that has synchronized code.
Interfaces cannnot have constructors|True.
__Drivers that use a pure Java client and communicate with a middleware server u
sing a database-independent protocol The middleware server then communicates the
client's requests to the data source.|Type 3.
The default type of the ResultSet object is __|TYPE_FORWARD_ONLY.
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal?|When the type of x is Object.
A method in an interface can access class level variables|Incorrect.
double d = 1.2d;|legal.
How do you prevent shared data from being corrupted in a multilthreaded environm
ent?| Access the variables only via synchronized methods.
The Swing's list component(JList) can display text only.|Correct.
The Swing's label(JLabel) can present an image.|Correct.
Which of the following operations might throw an ArithmeticException?.|%.
Under no circumstances can a class be defined with the private modifier.|True.
Adding more classes via import statements will cause a performance overhead, onl
y import classes you actually use.|True.
Suppose class X contains the following method:|Public void doSomething(int a, fl
oat b){...}.
A protected method may only be accessed by classes of the same package or by sub
classes of the class in which it is declared.|Correct.
Vector does not allow duplicate elements.|Incorrect.
Which of the following is a valid argument to the DataInputStream constructor?|F
ileInputStream.
The___class is the primary class that has the driver information.|DriverManager.
Consider the following code developed in NetBeans.What does the thread t do?|The
program cause errors when it is compiled.
What is 7%-4?|3.
A signed data type has an equal number of non-zero positive and negative values
available.|False.
Both primitives and object references can be both converted and cast.|Correct.
Which of the following statements is true about two base protocols used for netw
orking :TCP(Transmission Control Protocol) and UDP(User Datagram Protocol)?|TCP
is a connection-base protocol and UDP is not connection-based protocol.
To check whether the file denoted by the abstract pathname is a driectory or not
call the isDirectory() method of the File class.|True.
Which of the following methods of the Collections class can be used to find the
largest value in a Vector?.|We don't need any method because elements in Vector
are automatically sorted. Therefore, the first element contains the maximum valu
e.
Select the correct statement which set the layout manager of a given frame to Fl
owLayoutManager.|setLayout(new FlowLayout());
Suppose salaries is an array containing floats.Which of the following are valid
loop control statements for processing each element of salaries?|for(float f.sal
aries);
String x = "Hello"; int y = 9; x=x+y;|Legal.
Whenever a method does not want to handle exceptions using the try block.the___i
s used.|throws.
You cannot call an enum's toString() method.|True.
Which is the four steps are used in working with JDBC?|Connect-Create-Look-Close
.
Which of the following methods of the java.io.File can be used to create a new f
ile?|createNewFile().
Give a string constructed by calling s = new String("xyzzy").which of the calls
modifies the string?|None of the others.
Which of the following statements is INCORRECT about a non-static synchronized m
ethod?|It cannot call to a static synchronized method of the current class.
How can you force garbage collection of an object?|Garbage collection cannot be
forced.
char c = \u1234;|Incorrect.
In RMI implementations, all methods, declared in the remote interface, must thro
w the __exception.|java.rmi.RemoteException.
What method of the java.io.File class can create a file on the hard drive?|creat
eNewFile().
BorderLayout is the default layout manager for every JFrame.|True.
1.A_dialog prevents user input to other windows in the application until the dia
log is closed|Model
2.how do you prevent shared data from being corrupted in a multithreaded environ
ment?|Access the variable only via synchronized methods
3.When a user selects a menu item,_is generated.|Action event
4.When you compile a program written in the Java programming language,the compil
er converts the human-readble soure file into platfom- independent code that a J
ava Virtual Machine can understand|bytecode
5.Which of the following operators can perform promotion on their operands?(sele
ct two)|+-
6.Which line contains only legal statements?|int x=6;x=~x
7.Which Man class properly represents the relationship "Man has the bestfriend w
ho is a Dog"?|class Man{private BestFriend dog;}
8.A thread is in the ready state after is has been created and started|most corr
ect
9.Which of the following statement(s) is(are) true?1) An abstract class can not
have any fianl methods.2)A final class may not have any abstract methods.|Only s
tatement2
10.Which is the return type of the instance of operator?|A boolean
11.Study the statements: 1) When a JDBC connection is created,it is auto-commit
mode.2) Once auto-commit mode is disabled, no SQL statements will be committed u
ntil you call the method commit explicity| Both 1 and 2 are not true
12.Which of the following is true about Wrapped classes?|Wrapper class are :Bool
ean,Char,Byte,Short,Interger,long,Float and Double
13.The GridBagLayout manager is the default manager for JFrame|true
14.What is the range of values that can be assigned to a variable of type short?
|-2^15 throught 2^15-1
15.When is it appropriate to pass a cause to an exception's constructor?|...in r
esponse to catching of a different exception type
16. When you construct an instance of File,the file will not be created even if
the corresponding file does not exist on the local file system|true
17.Which of the following may follow the static keyword?(select two)|Methods and
Non-inner class definitions
18.Constructors are not inherited|true
19.A for statement can loop infinitely, for example:for(;;)|true
20.We use readoject() method of ObjectOutputStream class to deserialize|INCORREC
T
21.A(n)_ object is used to obtain a Connection to a Database|DriverManager
22.What is the difference between a TextArea and a TextField?|A TextArea can han
dle multiple lines of text
23.A pet has an owner, a registration date;and a vaccination-duw date.Given that
the Pet class has already been defined|String markings and boolean neutered
Which of the following are valid declarations? Assume java.util.* is imported.|V
ector<Map>v Set<String>s Map<String, String>m;
You can determine all the keys in a Map in which of the following ways?|By gett
ing a Set object from the Map and iterating through it
What keyword is used to prevent an object from being serialized |transient
An abstract class can contain methods with declared bodies.|true
Select the order of access modifiers from least restrictive to most restrictive.
|public, protected, default, private
Which access modifier allows you to access method calls in libraries not create
d in Java?|native
Which of the following statements are true? (Select all that apply.)|A final ob
ject cannot be reassigned a new address in memory.
The keyword extends refers to what type of relationship?| is a
Which of the following keywords is used to invoke a method in the parent clas
s?|super
What is the value of x after the following operation is performed? x = 23 %
4;|3
Given the following code, what keyword must be used at line 4 in order to stop
execution of the for loop?|break
What method call is used to tell a thread that it has the opportunity to run?|
notify()
Assertions are used to enforce all but which of the following?|Exceptions
The developer can force garbage collection by calling System.gc().|False
Select the valid primitive data types. (Select all that apply.)|boolean char flo
at
How many bits does a float contain?|32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
|true
Select the list of primitives ordered in smallest to largest bit size represent
ation.|char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion?|java.text.DateFormat
The following line of code is valid. int x = 9; byte b = x;|false
Java arrays always start at index 1.|false
Which of the following statements accurately describes how variables are passe
d to methods?|Arguments that are primitive type are passed by value.
How do you change the value that is encapsulated by a wrapper class after you
have instan- tiated it?|None of the above.
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method s
hould imple- ment the custom deserialization, and what is its access mode?|priva
te readObject
A signed data type has an equal number of non-zero positive and negative value
s available.|false
If all three top-level elements occur in a source file, they must appear in whi
ch order?|Package declaration, imports, class/interface/enum definitions
How can you force garbage collection of an object?|Garbage collection cannot b
e forced.
What is the range of values that can be assigned to a variable of type short?|-2
^15 through 2^15 - 1
What is the range of values that can be assigned to a variable of type byte?|-2^
7 through 2^7 - 1
Suppose a source file contains a large number of import statements. How do the
imports affect the time required to compile the source file?|Compilation takes
slightly more time
Suppose a source file contains a large number of import statements and one cl
ass definition.How do the imports affect the time required to load the class?|
Class loading takes no additional time.
Which of the following are legal?|char c = \u1234 ;
After execution of the following code fragment, what are the values of the var
iables x, a, and b?|x = 13, a = 7, b = 8
Which of the following expressions results in a positive value in x?|int x = 1
; x = x >>> 5;
What is -8 % 5?|-3
What is 7 % -4?|3
Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 =
= ob2) is false, can ob1.equals(ob2) ever be true?|no
When a byte is added to a char, what is the type of the result?|int
When a short is added to a float, what is the type of the result?|float
Which of the following operations might throw an ArithmeticException?|none of t
hese
Which of the following operations might throw an ArithmeticException?|/
What is the return type of the instanceof operator?|A boolean
Which of the following may appear on the left-hand side of an instanceof opera
tor?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose all that apply.)|A class,An interface
What is -50 >> 1?|-25
Which of the following statements is true?|A final class may not have any abstr
act methods
Which of the following statements is true?|Transient variables are not serializ
ed
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class s persistent state? (Choose the shortest pos
sible answer.)|transient
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access mod
es may Subby s version of the method have? (Choose all that apply.)|public prote
cted
Which of the following statements are true?|None of the above.
True or false: If class Y extends class X, the two classes are in different pack
ages, and class X has a protected method called abby(), then any instance of Y
may call the abby() method of any other instance of Y.|false
Which of the following statements are true?|A final class may not be extended.
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.)|and the rules governin
g these conversions are identical.
Which of the following may legally appear as the new type (between the parenthe
ses) in a cast operation?|All of the above
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal?|When the type of x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal?|Sometimes
When is x & y an int? (Choose one).|Sometimes
What are the legal types for whatsMyType? short s = 10; whatsMyType = !s;|There
are no possible legal types.
When a negative long is cast to a byte, what are the possible values of the resu
lt?|All of the above
When a negative byte is cast to a long, what are the possible values of the resu
lt?|negative
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion?|There is no difference; the rules are the same.
Suppose salaries is an array containing floats. Which of the following are vali
d loop control statements for processing each element of salaries?|for (float f
:salaries)
Suppose a method called finallyTest() consists of a try block, followed by a ca
tch block, followed by a finally block. Assuming the JVM doesn t crash and the cod
e does not execute a System.exit() call, under what circumstances will the fina
lly block not begin to execute?|If the JVM doesn t crash and the code does not exe
cute a System.exit() call, the finally block will always execute.
Which of the following are legal loop definitions? (Choose all that apply.)|Non
e of them are legal
Which of the following are legal argument types for a switch statement?|byte int
char
When is it appropriate to pass a cause to an exception s constructor?|being thrown
in response to catching of a different exception type
Which of the following should always be caught?|Checked exceptions
When does an exception s stack trace get recorded in the exception object?|When
the exception is constructed
When is it appropriate to write code that constructs and throws an error?|never
Which of the following statements are true? (Choose all that apply.)|new Outer(
).new Inner()new Outer().new Inner()
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant?|if (x == y)
Which of the following restrictions apply to anonymous inner classes?|They must
be defined inside a code block.
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread.|false
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1
so that it alone moves from the Waiting state to the Ready state?|You cannot s
pecify which thread will get notified.
A Java monitor must either extend Thread or implement Runnable.|false
Which of the following methods in the Thread class are deprecated?|suspend() an
d resume()
Which of the following statements about threads is true?|Threads inherit the
ir priority from their parent thread.
Which of the following statements about the wait() and notify() methods is tr
ue?|The thread that calls wait() goes into the monitor s pool of waiting threads
.
Which of the following may not be synchronized?|classes
How many locks does an object have?|one
Is it possible to write code that can execute only if the current thread owns
multiple locks?|yes
Which of the following are true?|The JVM runs until there are no non-daemon thre
ads.
How do you prevent shared data from being corrupted in a multithreaded environme
nt?|Access the variables only via synchronized methods.
How can you ensure that multithreaded code does not deadlock?|A, B, and C do not
ensure that multithreaded code does not deadlock.
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do?|Override run().
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string?|None of the above
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide t
he new functionality as a set of static methods. Which one statement is true ab
out this strategy?|subclass java.lang.Math
Which line of code tells a scanner called sc to use a single digit as a delimite
r?|sc.useDelimiter( \\d );
Given arrays a1 and a2, which call returns true if a1 and a2 have the same leng
th, and a1[i].equals(a2[i]) for every legal index i?|java.util.Arrays.equals(a1,
a2);
Which of the statements below are true? (Choose all that apply.)|Unicode charac
ters are all 16 bits.
Which of the statements below are true? (Choose all that apply.)|None of the ab
ove.
How do you use the File class to list the contents of a directory?|String[] co
ntents = myFile.list();
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have?|private
is a set of java API for executing SQL statements.|JDBC
method is used to wait for a client to initiate communications.|accept()
drivers that are written partly in the Java programming language and pa
rtly in native code. These drivers use a native client library specific to the d
ata source to which they connect. Again, because of the native code, their porta
bility is limited.|Type 2
drivers that are pure Java and implement the network protocol for a spe
cific data source. The client connects directly to the data source.|Type 4
drivers that use a pure Java client and communicate with a middleware s
erver using a database-independent protocol. The middleware server then communic
ates the client's requests to the data source.|Type 3
drivers that implement the JDBC API as a mapping to another data access
API, such as ODBC. Drivers of this type are generally|Type 1
26. System.out.println(a.doit(4, 5));|Line 26 prints a to System.out.
1. public class A {
2. public void method1() {|The code on line 29 will be executed,The excepti
on will be propagated back to line 27.
IOException extends Exception StreamCorruptedException extends IOException Malfo
rmedURLException extends IOException|Bad URL,Doing finally part,Carrying on
1. try { 2. // assume s is previously defined 3. URL u = new URL(s);|Succ
ess,Doing finally part,Carrying on
public class Beta {|The code compiles and the output is 2.,If lines 16, 17 and 1
8 were removed, the code would compile and the output would be 2.,If lines 24, 2
5 and 26 were removed, the code would compile and the output would be 1.
10. public class ClassA { 11. public void methodA() {|An exception is thrown a
t runtime.
11. public class Bootchy {|third second first snootchy 420
A dialog prevents user input to other windows in the application unitl th
e dialog is closed.|Modal
1. FileOutputStream fos = new FileOutputStream("datafile");|Construct a FileInpu
tStream, passing the name of the file. Onto the FileInputStream, chain a DataInp
utStream, and call its readInt() method.|Construct a RandomAccessFile, passing t
he name of the file. Call the random access file s readInt() method.
A Java monitor must either extend Thread or implement Runnable.|False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.)|Y
ou cannot specify which thread will get notified.
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these|public void logIt(String.
.. msgs)
A signed data type has an equal number of non-zero positive and negative values
available.|False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread|False
A thread s run() method includes the following lines:|At line 2, the thread will s
top running. It will resume running some time after 100 milliseconds have elapse
d
A(n) object is used to submit a query to a database|Statement
A(n) object is uses to obtain a Connection to a Database|DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b? 1. int x, a = 6, b = 7; 2. x = a++ + b++;|x = 13, a = 7, b = 8
10. public class Money {|Euro returns correct Country value.,Compilation fails b
ecause of an error at line 25.
Choose the valid identifiers from those listed here. (Choose all that apply.)|Bi
gOlLongStringWithMeaninglessName,$int,bytes,$1,finalist
1. public class SomeException {|Compilation of class B will fail. Compilation of
class A will succeed.
1. public class TestException extends Exception {|Line 46 will compile if the en
closing method throws a TestException.,Line 46 will compile if enclosed in a try
block, where TestException is caught.
1. class Q6 {|101
1. class Q7 {|12.3
1. public class Test extends Base {|Test t = new Test(1);,Test t = new Test(1, 2
);
1. public class Test extends Base { 2. public Test(int j) {|Base() { },Base(int
j, int k) { }
1. class Cruncher {|The code will compile and produce the following output: int
version.
1. public class Base { 2. public void method(int i) {|Value is 5This value
is 6
2. String[] stringarr = new String[50];|Line 6
1. public class Assertification {|The application must be run with the -enableas
sertions flag or another assertionenabling flag.,The args array must have one or
more elements.
1. StringBuffer sbuf = new StringBuffer();|After line 2 executes, the StringBuff
er object is eligible for garbage collection.
1. Cat sunflower;|The code will compile but will throw an exception at line 7, b
ecause the runtime class of wawa cannot be converted to type SwampThing.
1. Dog rover, fido;|The code will compile and run.
1. for (int i = 0; i < 2; i++) {|i = 0 j = 1,i = 0 j = 2,i = 1 j = 0,i = 1 j = 2
1. outer: for (int i = 0; i < 2; i++) {|i = 1 j = 0
1. Raccoon rocky;|Line 7 will not compile; an explicit cast is required to conve
rt a Washer to a SwampThing.
1. public class Outer {|a,b,c,e
int[] x = new int[25];|x[24] is 0,x.length is 25
Which of the following methods would be legal (individually) at line 2 in class
Test2? (Choose two)|public int aMethod(int a, int b) throws Exception {...},publ
ic float aMethod(float p, float q) {...}
Which of the following methods would be legal if added (individually) at line 4?
(Choose three.)|public int aMethod(int a, int b) { },public float aMethod(float
a, float b, int c) throws Exception { },private float aMethod(int a, int b, int
c) { }
11. public static Iterator reverse(List list) {|Compilation fails.
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? (Choose one.)|None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? (Choose one.)|java.util.Arra
ys.equals(a1, a2);
public class Xyz implements java.io.Serializable {|iAmPublic,iAmPrivate,iAmVolat
ile
1. class SuperDuper|line 3: private; line 8: protected
enum Spice { NUTMEG, CINNAMON, CORIANDER, ROSEMARY; }|Spice sp = Spice.NUTMEG; O
bject ob = sp;,Spice sp = Spice.NUTMEG; Object ob = (Object)sp;,Object ob = new
Object(); Spice sp = (Spice)ob;
15. public static void main(String[] args) {|Compilation fails.
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? (Choose one.)|None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? (Choose one.)|java.util.Arra
ys.equals(a1, a2);
List<String> names = new ArrayList<String>();|Iterator<String> iter = names.iter
ator();,for (String s:names)
12. void process() throws Exception { throw new Exception(); }|Compilation
fails because of an error in line 19.
boolean b1 = true; boolean b2 = false; if((x==4) && !b2)|2 3
2. String DEFAULT_GREETING = Hello World ;|public interface B extends A { }
10. abstract public class Employee {|public double getSalesAmount() { return 123
0.45; },protected double getSalesAmount() { return 1230.45; }
10. class MakeFile {|An exception is thrown at runtime.,Line 13 creates a File o
bject named d. ,Line 14 creates a File object named f.
What keyword is used to prevent an object from being serialized?|transient
An abstract class can contain methods with declared bodies.|True
Select the order of access modifiers from least restrictive to most restrictive.
|public, protected, default, private
Which access modifier allows you to access method calls in libraries not create
d in Java?|native
Which of the following statements are true? (Select all that apply.)|A final ob
ject cannot be reassigned a new address in memory.
The keyword extends refers to what type of relationship?| is a
Which of the following keywords is used to invoke a method in the parent clas
s?|super
Given the following code, what will be the outcome?f.add(1, 2);|The code does no
t compile.
What is the value of x after the following operation is performed?x = 23 % 4
;|3
Given the following code, what keyword must be used at line 4 in order to stop
execution of the for loop?|break
What method call is used to tell a thread that it has the opportunity to run?|
notify()
Given the following code, which of the results that follow would you expect?pack
age mail;|The code will not compile because of line 4.
Assertions are used to enforce all but which of the following?|Exceptions
The developer can force garbage collection by calling System.gc().|False
Select the valid primitive data types. (Select all that apply.)|boolean,char,flo
at
How many bits does a float contain?|32
What is the value of x after the following line is executed?x = 32 * (31 -
10 * 3);|32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
|True
Select the list of primitives ordered in smallest to largest bit size represent
ation.|char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion?|java.text.DateFormat
The following line of code is valid.int x = 9; byte b = x;|False
Which of the following code snippets compile?|i = 7;i = new (5);j = i; byte b
= 7;
What will be the output of the following code? StringTest| same will be printed ou
t to the console.
Java arrays always start at index 1.|False
Which of the following statements accurately describes how variables are passe
d to methods?|Arguments that are primitive type are passed by value.
How do you change the value that is encapsulated by a wrapper class after you
have instan- tiated it?|None of the above.
Suppose you are writing a class that provides custom deserialization.|private r
eadObject
A signed data type has an equal number of non-zero positive and negative value
s available.|False
Choose the valid identifiers from those listed here. (Choose all that apply.)|Bi
gOlLongStringWithMeaninglessName,$int,bytes,$1,finalist
Which of the following signatures are valid for the main() method entry point of
an application?|public static void main(String arg[]),(String[] args)
If all three top-level elements occur in a source file, they must appear in whi
ch order?|Package declaration, imports, class/interface/enum definitions.
Consider the following line of code: int[] x = new int[25];|x[24] is 0,x.lengt
h is 25
Consider the following application:|101
How can you force garbage collection of an object?|Garbage collection cannot b
e forced.
What is the range of values that can be assigned to a variable of type short?|-2
15 through 215 - 1
What is the range of values that can be assigned to a variable of type byte?|-27
through 27 - 1
Suppose a source file contains a large number of import statements. How do the
imports affect the time required to compile the source file?|Compilation takes
slightly more time.
How do the imports affect the time required to load the class?|Class loading t
akes no additional time.
Which of the following are legal import statements?|import java.util.Vector;imp
ort static java.util.Vector.*;
Which of the following may be statically imported? (Choose all that apply.)|Stat
ic method names,Static field names
Which of the following are legal? (Choose all that apply.)|int c = 0xabcd;int
d = 0XABCD;
Which of the following are legal? (Choose all that apply.)|double d = 1.2d;dou
ble d = 1.2D;
Which of the following are legal?|char c = \u1234 ;
Consider the following code:|After line 2 executes, the StringBuffer object is
eligible for garbage collection.
Which of the following are true? (Choose all that apply.)|Primitives are passed
by value.References are passed by value.
After execution of the following code fragment, what are the values of the var
iables x, a, and b?|x = 13, a = 7, b = 8
Which of the following expressions are legal? (Choose all that apply.)|int x =
6; if (!(x > 3)) {},int x = 6; x = ~x;
Which of the following expressions results in a positive value in x?|int x = 1
; x = x >>> 5;
Which of the following expressions are legal? (Choose all that apply.)|String x
= "Hello"; int y = 9; x += y;int y = 9; x = x + y;
What is -8 % 5?|-3
What is 7 % -4?|3
What results from running the following code?class Xor|The output: b contains
5
What results from attempting to compile and run the following code?Conditional|T
he output: value is 9.0
What does the following code do?|Throws an exception.
Suppose ob1 and ob2 are references to instances of java.lang|No
When a byte is added to a char, what is the type of the result?|int
When a short is added to a float, what is the type of the result?|float
int selfXor(int i) { return i ^ i;|A. It always returns 0.
Which of the following operations might throw an ArithmeticException?|None of t
hese
Which of the following operations might throw an ArithmeticException?|/
What is the return type of the instanceof operator?|A boolean
Which of the following may appear on the left-hand side of an instanceof opera
tor?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose all that apply.)|A class,An interface
What is -50 >> 1?|-25
Which of the following statements is true?|A final class may not have any abstr
act methods.
What is the minimal modification that will make this code compile correctly?fina
l class Aaa|On line 1, remove the final modifier.
Which of the following statements is true?|Transient variables are not serializ
ed.
Which statement is true about this application?class StaticStuff|The code compi
les and execution produces the output x = 3.
Which statement is true about this code?class HasStatic|The program compiles an
d the output is x = 104.
class SuperDuper|line 3: private; line 8: protected
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class s persistent state?|transient
This question concerns the following class definition:|The program will compile
and execute. The output will be Before: 0 After: 2.
Suppose class Supe, in package packagea, has a method called doSomething()|publi
c,protected
Which of the following statements are true?|None of the above.
Which of the following may be declared final? (Choose all that apply.)|Classes,D
ata,Methods
class MakeFile {|An exception is thrown at runtime.,Line 13 creates a File objec
t named d. ,Line 14 creates a File object named f.
12. public int fubar( Foo foo) { return foo.bar(); }|new Foo() { public int
bar(){return 1; } }
10. public class ClassA { 11. public void count(int i) {|StackOverflowError
11. public abstract class Shape {|Shape s = new Circle(); s.setAnchor(10,10); s.
draw();
11. public static void main(String[] args) {|1 2 3
11. public static void main(String[] args) { 12. try {|Compilation fails.
11. public static void parse(String str) {|Compilation fails.
11. String test = This is a test ;|Compilation fails.
12. public class AssertStuff {|passed An AssertionError is thrown with the word s
tuff added to the stack trace.
12. public class Test { 13. public enum Dogs {collie, harrier};|collie harri
er
13. public class Pass {|doStuff x = 5 main x = 5
20. public class CreditCard {|The ownerName variable breaks encapsulation.
23. Object [] myObjects = {|Compilation fails due to an error in line 29.
31. // some code here|The code on line 33 throws an exception.,The code on line
35 throws an exception.,The code on line 31 throws an exception.
35. }catch (NullPointerException e1) {|ac
55. int []x= {1, 2,3,4, 5};|Line 57 will print the value 3.
10. assert a.length == 1;|java -ea test,java -ea test file1 file2
1. public class TestString3 {|StringBuffer s = new StringBuffer( 123456789 ); s.dele
te(0,3).replace( 1,3, 24 ).delete(4,6);,StringBuilder s = new StringBuilder( 12345678
9 ); s.delete(0,3).delete( 1 ,3).delete(2,5).insert( 1, 24 );
10. class Line {|Line.Point p = new Line.Point();
10. public class Bar { 11. static void foo(int...x) {|for(int z : x) System
.out.println(z);,for( int i=0; i< x.length; i++ ) System.out.println(x[i]);
12. /* insert code here */ int MY_VALUE = 10;|final,static,public
catch (Exception e) { System.out.print("Exception "); }|A Exception
How can you ensure that multithreaded code does not deadlock? (Choose one.)|Ther
e is no single technique that can guarantee non-deadlocking code.
How can you force garbage collection of an object? (Choose one.)|Garbage collect
ion cannot be forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? (Choose one.)|Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory? (Choose one.)
|String[] contents = myFile.list();
2. FileOutputStream fos = newFileOutputStream("dest");|8
How many locks does an object have? (Choose one.)|One
If all three top-level elements occur in a source file, they must appear in whic
h order? (Choose one.)|Package declaration, imports, class/interface/enum defini
tions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any other instance of Y.|False
1. class TestThread3 extends Thread {|Yes
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use? (Choose one.)|TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? (Choose one.)|Comparable interface and its compareTo meth
od.
1. StringBuffer sbuf = new StringBuffer("FPT");|True
1. byte b = 11; 2. short s = 13; 3. result = b * ++s;|int, long, float, double
Interface helps manage the connection between a Java program and a databa
se.|Connection
boolean weird(Thing s) { Integer x = new Integer(5); return s.equals(x);|Yes
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks?|Yes
JDBC supports and models.|Two-tier and three-tier
MVC is short call of|Model-View-Controller
byte b = 2; byte b1 = 3; b = b * b1;|No output because of compile error at line:
b = b * b1;
public static void main(String[] args){ Object ob1= new Object(); Object ob2= ne
w Object();|Have a nice day!
public static void main(String[] args){ Object ob1= new Object(); Object ob2= ob
1;|ob1 equals ob2,ob1==ob2,Have a nice day!
if (s1 == s2) System.out.println("Line 4"); if (s1.equals(s2)) System.out.printl
n("Line 6");|Line 4 Line 6
public static void main(String[] args){ String s1 = "xyz";|Line 6
if (s1.equals(s2)) System.out.println("Line 6");|Line 6
s2=s2.intern();|Line 4 Line 6
Select correct statement about RMI. (choose 1)|All the above
Select correct statement(s) about remote class.(choose one)|All the others choic
es
Select correct statements about remote interface. (choose 1)|All the others choi
ces
Select INCORRECT statement about serialization. (choose 1)|When an Object Outpu
t Stream serializes an object that contains references to another object, every
referenced object is not serialized along with the original object.
Select INCORRECT statement about deserialize. (choose 1)|We use readObject() met
hod of ObjectOutputStream class to deserialize.
Select incorrect statement about RMI server.(choose 1)|A client accesses a remot
e object by specifying only the server name.
Select incorrect statement about ServerSocket class. (choose 1)|To make the new
object available for client connections, call its accept() method, which returns
an instance of ServerSocket
Select incorrect statement about Socket class. (choose 1)|The java.net.Socket cl
ass contains code that knows how to find and communicate with a server through U
DP.
Select the correct statement about JDBC two-tier processing model.|A user's comm
ands are delivered to the database or other data source, and the results of thos
e statements are sent back to the user.
SQL keyword is followed by the selection criteria that specify the rows to
select in a query|WHERE
Statement objects return SQL query results as objects|ResultSet
2)Once auto-commit mode is disabled, no SQL statements will be committed until y
ou call the method commit explicitly|Both 1 and 2 are true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block. Assuming the JVM doesn t crash and the code
does not execute a System.exit() call, under what circumstances will the finall
y block not begin to execute? (Choose one.)|If the JVM doesn't crash and the cod
e does not execute a System.exit() call, the finally block will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? (Cho
ose one.)|Class loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? (Choose one.)|Compil
ation takes slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? (Choose one.)|C must have a no-args constructor.
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C?
(Choose one.)|B must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? (Choose one)|private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby s version of the method have? (Choose two.)|public,protected
void doSomething(int a, float b) { }|public void doSomething(int a, float b) { }
Suppose interface Inty defines five methods. Suppose class Classy declares|The c
lass will compile if it is declared abstract.,The class may not be instantiated.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.)|All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? (Choose one.)|
for (float f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? (Choose one.)|When the type of x is
Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? (Choose one.)|Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.)|if (x ==
y)
The class implements java.io.Serializable (not java.io.Externalizable). What acc
ess mode should the |private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? (Choose one.)|Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric |The strategy fails because you cannot add static methods to a
subclass.
Swing components cannot be combined with AWT components.|True
The class is the primary class that has the driver information.|DriverManag
er
class is used to implement a pull-down menu that provides a number of items to s
elect from.|Menu
The element method alters the contents of a Queue.|False
The Swing component classes can be found in the package.|javax.swing
There are two classes in Java to enable communication using datagrams namely.|Da
taPacket and DataSocket
6. protected void fly() { /* Flap wings, etc. */ }|Compilation of Parrot.ja
va fails at line 7 because method getRefCount() is static in the superclass, and
static methods may not be overridden to be nonstatic.
3. class Nightingale extends abcde.Bird {|The program will compile and execute.
The output will be Before: 0 After: 2.
This question involves IOException, AWTException, and EOFException.|void doSomet
hing() { },void doSomething() throws EOFException { },void doSomething() throws
IOException, EOFException { }
URL referring to databases use the form:|protocol:subprotocol:datasoursename
What are the legal types for whatsMyType? (Choose one.) short s = 10;|There are
no possible legal types.
if (i != null & i.intValue() == 5) System.out.println("Value is 5");|Throws an e
xception.
1. FileOutputStream fos = new FileOutputStream("xx");|The output is i = 20.
that1.x = 5; that2.x = 1000; x = -1;|-1
3. public class Xxx {|An exception is thrown at line 9.
public static void main(String[] args) { System.out.println(">>" + s + "<<");|Th
e code compiles, and prints out >>null<<
5. Set<Apple> set = new TreeSet<Apple>();|An exception is thrown at line 7.
What is -50 >> 2|-13
What is 7 % -4?|3
What is -8 % 5?|-3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? (Choose one.)|There is no difference; the rules are
the same.
1. final class Aaa|On line 1, remove the final modifier.
What is the range of values that can be assigned to a variable of type byte? (Ch
oose one.)|-2^7 through 2^7 - 1
What is the range of values that can be assigned to a variable of type short? (C
hoose one.)|-2^15 through 2^15 - 1
4. BufferedOutputStream bos = new BufferedOutputStream(raf);|The code fails
to compile.
What is the return type of the instanceof operator?|A boolean
What method of the java.io.File class can create a file on the hard drive? (Choo
se one.)|createNewFile()
4. System.out.println("value is " + ((x > 4) ? 99.99 : 9));|The output: va
lue is 9.0
3. byte b = 10; // 00001010 binary|The output: b contains 5
1. int x = 0, y = 4, z = 5;|message four
When a byte is added to a char, what is the type of the result?|int
When a negative byte is cast to a long, what are the possible values of the resu
lt? (Choose one.)|Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? (Choose one.)|All the above
When a short is added to a float, what is the type of the result?|float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? (Choose one.)|writing a line separator
to the stream
When does an exception's stack trace get recorded in the exception object? (Choo
se one.)|When the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? (Choose on
e.)|When the exception is being thrown in response to catching of a different ex
ception type
When is it appropriate to write code that constructs and throws an error? (Choos
e one.)|Never
When is x & y an int? (Choose one).|Sometimes
When the user attempts to close the frame window, event in generated.|win
dow closing
When the user selects a menu item, event is generated.|Action event
When you compile a program written in the Java programming language,|bytecode
Whenever a method does not want to handle exceptions using the try block, the
is used.|throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database?|String url ="jdbc:odbc:data_source_name"; Connection con
= DriverManager.getConnection (url, user", "password");
Which class and static method can you use to convert an array to a List? (Choose
one.)|Arrays.asList
Which is four-step approach to help you organize your GUI thinking. (Choose one.
)|Identify needed components. Isolate regions of behavior. Sketch the GUI. Choos
e layout managers.
Which is the four steps are used in working with JDBC?|1)Connect to the database
,2)Create a statement and execute the query,3)Look at the result set,4)Close con
nection
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed?|two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? (Choose one.)|sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? (Choose one.)|class Man { private Dog bestFriend; }
Which methods return an enum constant s name? (Choose two.)|name().,toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? (Choose the shortest pos
sible answer.)|transient
Which of the following are legal argument types for a switch statement? (Choose
three.)|byte,int,char
Which of the following are legal import statements? (Choose two.)|import java.ut
il.Vector;,import static java.util.Vector.*;
Which of the following are legal loop constructions? (Choose one.)|for (int k=0,
j+k != 10; j++,k++) { System.out.println("j=" + j + ", k=" + k);
Which of the following are legal loop definitions? (Choose one.)|None of the abo
ve.
Which of the following are legal? (Choose three.)|for (int i=0, j=1; i<10; i++,
j++),for (int i=0, j=1;; i++, j++),for (String s = ""; s.length()<10; s += '!')
Which of the following are legal? (Choose two.)|double d = 1.2d;,double d = 1.2D
;
Which of the following are legal? (Choose two.)|int c = 0xabcd;,int d = 0XABCD;
Which of the following are legal? (Choose two.)|char c = 0x1234;,char c = '\u123
4';
Which of the following are legal? (Choose two.)|List<String> theList = new Vecto
r<String>();,Vector <String> theVec = new Vector<String>();
Which of the following are methods of the java.util.SortedMap interface? (Choose
three.)|headMap,tailMap,subMap
Which of the following are methods of the java.util.SortedSet interface? (Choose
one.)|All the above
Which of the following are true? (Choose one.)|All the above
Which of the following are true? (Choose one.)|The JVM runs until there are no n
on-daemon threads.
Which of the following are true? (Choose three.)|When an application begins runn
ing, there is one non-daemon thread, whose job is to execute main().,A thread cr
eated by a daemon thread is initially also a daemon thread.,A thread created by
a non-daemon thread is initially also a non-daemon thread.
Which of the following are true? (Choose two.)|When you declare a method to be s
ynchronized, the method always synchronizes on the lock of the current object.,W
hen you declare a block of code inside a method to be synchronized, you can spec
ify the object on whose lock the block should synchronize.
Which of the following are true? (Choose two.)|An enum may contain public method
definitions.,An enum may contain private data.
Which of the following are true? (Choose two.)|Primitives are passed by value.|R
eferences are passed by value.
Which of the following are true? (Choose two.)|An anonymous inner class may impl
ement at most one interface,An anonymous inner class may extend a parent class o
ther than Object.
Which of the following are valid arguments to the DataInputStream constructor? (
Choose one.)|FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose one.)|All the above
Which of the following calls may be made from a non-static synchronized method?
(Choose one.)|All the above
Which of the following classes implement java.util.List? (Choose two.)|java.util
.ArrayList,java.util.Stack
Which of the following classes implements a FIFO Queue? (Choose one.)|LinkedLis
t
Which of the following declarations are illegal? (Choose three.)|default String
s;,abstract double d;,abstract final double hyperbolicCosine();
Which of the following expressions are legal? (Choose two.)|int x = 6; if (!(x >
3)) {},int x = 6; x = ~x;
Which of the following expressions are legal? (Choose two.)|String x = "Hello";
int y = 9; x += y;,String x = "Hello"; int y = 9; x = x + y;
Which of the following expressions results in a positive value in x? (Choose one
.)|int x = 1; x = x >>> 5;
Which of the following interfaces does not allow duplicate objects? (Choose one.
)|Set
Which of the following is not appropriate situations for assertions? (Choose one
)|Preconditions of a public method
Which of the following is NOTa valid comment:|/* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method?|Throw java.lang.IllegalArgumentException.
Which of the following is true? (Choose one.)|Readers have methods that can read
and return floats and doubles.-->None of the above
An enum definition may contain the main() method of an application.|All the abov
e
Which of the following may appear on the left-hand side of an instanceof operato
r?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose two.)|A class,An interface
Which of the following may be statically imported? (Choose two.)|Static method n
ames,Static field names
Which of the following may follow the static keyword? (Choose three.)|Data,Metho
ds,Code blocks enclosed in curly brackets
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.)|All of the others
Abstract classes|All of the above
Which of the following may not be synchronized? (Choose one.)|Classes
Which of the following may override a method whose signature is void xyz(float f
)? (Choose two.)|void xyz(float f),public void xyz(float f)
Which of the following methods in the Thread class are deprecated? (Choose one.)
|suspend() and resume()
Which of the following operations might throw an ArithmeticException? (Choose on
e.)|None of these
Which of the following operations might throw an ArithmeticException? (Choose on
e.)|/
Which of the following operators can perform promotion on their operands? (Choos
e three.)|+ - ~
Which of the following restrictions apply to anonymous inner classes? (Choose on
e.)|They must be defined inside a code block.
Which of the following should always be caught? (Choose one.)|Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application? (Choose two.)|public static void main(String arg[]),public stat
ic void main(String[] args)
Which of the following statements about the wait() and notify() methods is true?
(Choose one.)|The thread that calls wait() goes into the monitor s pool of waitin
g threads.
Which of the following statements about threads is true? (Choose one.)|Threads i
nherit their priority from their parent thread.
Which of the following statements are true? (Choose one.)|A final class may not
be extended.
Which of the following statements are true? (Choose one.)|new Outer().new Inner(
)
An abstract class may be instantiated.|None of the above
Which of the following statements are true? (Choose two.)|StringBuilder is gener
ally faster than StringBuffer.,StringBuffer is threadsafe; StringBuilder is not.
1)An abstract class may not have any final methods.|Only statement 2
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.)|Transient variables are
not serialized.
Which of the following statements is true? (Choose one.)|Object references can b
e converted in both method calls and assignments, and the rules governing these
conversions are identical.
Which of the statements below are true? (Choose one.)|Unicode characters are all
16 bits.
To change the current working directory, call the setWorkingDirectory() method o
f the File class.|None of the above
When you construct an instance of File, if you do not use the file-naming|None o
f the above.
1. byte b = 5; 2. char c = 5 ;|Line 6
1. class HiPri extends Thread {|None of the above scenarios can be guaranteed to
happen in all cases.
3. System.out.println("cosine of 0.123 = " + myMath.cos(0.123));|Compilation fa
ils at line 2.
1. String s = "FPT"; 2. StringBuffer s1 = new StringBuffer("FPT"); 3. if (s.equa
ls(s1)) 4. s1 = null;|Compilation succeeds. No exception is thrown during e
xecution.
1. String s1 = "abc" + "def";|Line 6 executes and line 4 does not.
1. class Greebo extends java.util.Vector implements Runnable {|There will be a
compiler error, because class Greebo does not correctly implement the Runnable i
nterface.
2. switch (j) {|The output would be the text value is two followed by the text v
alue is three.
int selfXor(int i) {|int selfXor(int i) {
1. class StaticStuff|The code compiles and execution produces the output x = 3.
1. class HasStatic|The program compiles and the output is x = 104.
Which statements about JDBC are NOT true? (choose 2)|JDBC is a Java database sy
stem.,JDBC is a Java API for connecting to any kind of DBMS
Which two code fragments correctly create and initialize a static array of int
elements? (Choose two.)|static final int[] a = { 100,200 };,static final int[] a
; static { a=new int[2]; a[0]=100; a[1]=200; }
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? (Choose two.)|Map,Collection
2. File f2 = new File(f1, "filename");|No directory is created, and no file is c
reated.
"A pet has an owner, a registration date, and a vaccination-due date. A cat|publ
ic class Cat extends Pet
Given that the Pet class has already been defined, which of the following fields
would be appropriate for inclusion in the Cat class as members? (Choose two.)|b
oolean neutered;,String markings;
Suppose class A has a method called doSomething(), with default access|public,p
rotected,Default
True or false: If class Y extends class X|False
Which of the following statements are true?|A final class may not be extended.
What does the following code print? public class A|-1
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which one line in the following code will not compile? byte b = 5;|Line 6
In the following code, what are the possible types for variable result? (Choose
the most complete true answer.)|int, long, float, double
class Cruncher|The code will compile and produce the following output: int ver
sion.
Which of the following statements is true? (Choose one.)|Object references can
be converted in both method calls and assignments, and the rules governing the
se conversions are identical.
1. Object ob = new Object();|Line 6
1. Cat sunflower;|wawa cannot be converted to type SwampThing.
1. Raccoon rocky;|Line 7 will not compile; an explicit cast is required
to convert a Washer to a SwampThing.
Which of the following may legally appear as the new type (between the parenthe
ses) in a cast operation?|All of the above
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal?|When the type of x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal?|Sometimes
What are the legal types for whatsMyType?|There are no possible legal types.
When a negative long is cast to a byte, what are the possible values of the resu
lt?|All of the above
When a negative byte is cast to a long, what are the possible values of the resu
lt?|Negative
Which of the following operators can perform promotion on their operands? (Choo
se all that apply.)|+,-,~
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion?|There is no difference; the rules are the same.
for (int i = 0; i < 2; i++) {|i = 0 j = 1,i = 0 j = 2,i = 1 j = 0,i =
1 j = 2
outer: for (int i = 0; i < 2; i++) {|i = 1 j = 0
int x = 0, y = 4, z = 5;|message four
int j = 2;|The output would be the text value is two followed by the text value
is three.
Which of the following is the most appropriate way to handle invalid arguments
in a public method?|Throw java.lang.IllegalArgumentException.
Suppose salaries is an array containing floats. Which of the following are vali
d loop control statements for processing each element of salaries?|for (float f
:salaries)
Suppose a method called finallyTest() consists of a try block|If the JVM
Which of the following are legal loop definitions? (Choose all that apply.)|Non
e of them are legal.
Which of the following are legal argument types for a switch statement?|byte,int
,char
When is it appropriate to pass a cause to an exception s constructor?|B. When the
exception is being thrown in response to catching of a different exception ty
pe
Which of the following should always be caught?|Checked exceptions
When does an exception s stack trace get recorded in the exception object?|When
the exception is constructed
When is it appropriate to write code that constructs and throws an error?|Never
public class Test1 {|public int,throws Exception,private
What output results when the main method of the class Sub is run?|Value is 5
This value is 6
public class Test extends Base {|Test t = new Test(1);Test t = new Test(1, 2
);
1. public class Outer {|a,b,c,e
Which of the following may override a method whose signature is void xyz(float
f)?|void xyz(float f),public void xyz(float f)
Which of the following are true? (Choose all that apply.)|An enum may contain p
ublic method definitions.data.
Suppose x and y are of type TrafficLightState, which is an enum|if (x == y)
Which of the following restrictions apply to anonymous inner classes?|They must
be defined inside a code block.
Which methods return an enum constant s name?|name(),toString()
void doSomething(int a, float b) { }|public void doSomething(int a, float
b) { }
Which of the following statements about the wait() and notify() methods is tr
ue?|The thread that calls wait() goes into the monitor s pool of waiting threads
.
Which of the following may not be synchronized?|Classes
How many locks does an object have?|One
Is it possible to write code that can execute only if the current thread owns
multiple locks?|Yes
Which of the following are true?|The JVM runs until there are no non-daemon thre
ads.
How do you prevent shared data from being corrupted in a multithreaded environme
nt?|Access the variables only via synchronized methods.
How can you ensure that multithreaded code does not deadlock?|A, B, and C do not
ensure that multithreaded code does not deadlock.
Suppose you want to create a custom thread class by extending java.lang.Thread
|Override run().
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string?|None of the above
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions|The strategy fails because you cannot subclass java.
lang.Math
import java.lang.Math;|Compilation fails at line 2.
String s = abcde ;|Compilation succeeds. No exception is thrown during execution.
sbuf.insert(3, xyz );|True
Which of the following are methods of the java.util.SortedMap interface?|headMa
p,tailMap,subMap
Which line of code tells a scanner called sc to use a single digit as a delimite
r?|sc.useDelimiter( \\d );
Set<Apple> set = new TreeSet<Apple>();|An exception is thrown at line 7.
Given arrays a1 and a2, which call returns true if a1 and a2 have the same leng
th, and a1[i].equals(a2[i]) for every legal index i?|java.util.Arrays.equals(a1,
a2);
Which of the following statements are true?|StringBuilder is not,StringBuffer.
Which of the statements below are true? (Choose all that apply.)|Unicode charac
ters are all 16 bits.
Which of the statements below are true? (Choose all that apply.)|None of the ab
ove.
How do you use the File class to list the contents of a directory?|String[] co
ntents = myFile.list();
FileOutputStream fos = newFileOutputStream( dest );|12
What does the following code fragment print out at line 9?The output is i = 20.
FileOutputStream fos = new FileOutputStream( datafile );|Construct a FileInputStream
,Construct a RandomAccessFile
Which of the following is true?|None of the above.
File f1 = new File( dirname );|No directory is created, and no file is created.
BufferedOutputStream bos = new|The code fails to compile
What access mode should the writeObject() method have?|private
What access mode should the readObject() method have?|private
java.io.Serializable|B must have a no-args constructor.
java.io.Externalizable|C must have a no-args constructor.
public class Xyz implements java.io.Serializable|iAmPublic,iAmPrivate,iAmVolatil
e
What method of the java.io.File class can create a file on the hard drive?|crea
teNewFile()
File f = new File("xxx.ser");|An exception is thrown at line 9.
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose all that apply.)| r , rw , rws , rwd
Which of the following are valid arguments to the DataInputStream constructor?|
FileInputStream
public void eee() { }|b,d,fff()
public abstract class Abby|SubAbby generates a compiler error.,If,variables.
int[] heights = new int[10];|heights is initialized to a reference to an array
with zero elements.
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards?|public Color get
TheTint()
void callMe(String names) { }|Within the method, names is an array containing
Strings.
public class Food { }|Fruit,Citrus,Pomelo
class A extends java.util.Vector { private A(int x)|The compiler does not cre
ate a default constructor.
Which of the following types are legal arguments of a switch statement?|enums,b
ytes
int[] ages = { 9, 41, 49 }; int sum = 0;|for (int i=0; i<ages.length; i++),f
or (int i:ages) sum += i;
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime.|assert x == 4;assert x == 4 : x is not 4 ;
Which are appropriate uses of assertions?|Checking preconditions in a private me
thod,Checking postconditions
EOFException and ObjectStreamException both extend IOException|void callMe(),C.
void callMe() throws NotSerializableException
try { callMe();|Object Stream,Finally
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown.|None of the above.
How is IllegalArgumentException used? (Choose all correct options.)|public metho
ds have been violated.preconditions have been violated.
Which of the following statements are true? (Choose all correct options.)|Strin
gBuilder encapsulates a mutable string.StringBuffer is threadsafe.
Suppose you want to read a file that was not created by a Java program|Create a
FileReader instance. Pass it into the constructor of LineNumberReader. Use Line
NumberReader s readLine() method.
What interfaces can be implemented in order to create a class that can be serial
ized? (Choose all that apply.)|interface.readExternal and writeExternal
The class implements java.io.Serializable (not java.io.Externalizable)|private
Suppose you want to use a DateFormat to format an instance of Date|The style, w
hich is one of SHORT, MEDIUM, LONG, or FULL,The locale
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc?|NumberFormat nf = NumberFormat.getInstance(loc);
String scanMe = aeiou9876543210AEIOU ;|String delim = \\d+ ;
Which line prints double d in a left-justified field that is 20 characters wide,
with 15 characters to the right of the decimal point?|System.out.format("%-20.1
5f", d);
Suppose MyThread extends java.lang.Thread, and MyRunnable implements java.lang.
Runnable|(new MyThread()).start();(new Thread(new MyRunnable()))
try { sleep(5000);|The code prints Going to sleep, then Waking up, and then All do
ne.
sharedOb.wait();|aThread.interrupt();sharedOb.notifyAll();
Suppose class Home has methods chopWood() and carryWater();|inappropriate cohes
ion.inappropriate coupling.
Lemon lem = new Lemon(); Citrus cit = new Citrus();|cit = lem;lem = (Lemon)c
it;cit = (Citrus)lem;
Grapefruit g = new Grapefruit();|The cast in line 2 is not necessary.The code c
ompiles, and throws an exception at line 3.
Suppose class bbb.Bbb, which extends aaa.AAA, wants to override callMe()|public
,protected
class Zebra extends Animal |Class Zebra generates a compiler error.
What code at line 4 results in a class that compiles?|super();this(1.23f);
What relationship does the extends keyword represent?| is a
When should objects stored in a Set implement the java.util.Comparable interfac
e?|When the Set is a TreeSet
Which methods below honor the hash code contract?|public int hashCode() { r
eturn a; },(int)Math.random();
plainVec; Vector<String> fancyVec;|Attempting to add anything other than a str
ing to fancyVec results in a compiler error.
The declaration of the java.util.Collection interface is interface Collection <
E>|public boolean addAll(Collection<? extends E> c)
package ocean; public class Fish {|public void swim() { },size = 12;
Assuming App.class is stored in an appropriate location in file appjar.jar, wha
t is printed when you type the following command line?|4
public class Wrapper { public int x;|n is 10, w.x is 11
When does the string created on line 2 become eligible for garbage collection?|A
fter line 3
What is -15 % -10?|-5
is a set of java API for executing SQL statements | JDBC
method is used to wait for a client to initiate communications | accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect | Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source | Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source | Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally dependent on a native library, whi
ch limits their portability | Type 1
System.out.println(a.doit(4, 5)) | Line 26 prints a to System.out
Which two are true if a NullPointerException is thrown on line 3 of class C | co
de on line 29, The exception
What lines are output if the constructor at line 3 throws a MalformedURLExceptio
n | Bad URL, Doing finally, Carrying
What lines are output if the methods at lines 3 and 5 complete successfully with
out throwing any exceptions | Success, Doing, Carrying
If lines 24, 25 and 26 were removed, the code would compile and the output would
be 1 | 3.The code, would be 1, 2
An exception is thrown at runtime | An exception
first second first third snootchy 420 | third second first snootchy 420
dialog prevents user input to other windows in the application unitl the dialog
is closed | Modal
You would like to write code to read back the data from this file. Which solutio
ns will work | 2.FileInputStream, RandomAccessFile
A Java monitor must either extend Thread or implement Runnable | F
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1 | You cannot specify
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these ways | public void logIt(
String... msgs)
A signed data type has an equal number of non-zero positive and negative values
available | F
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread | F
catch (InterruptedException e) | running some time
object is used to submit a query to a database | Statement
object is uses to obtain a Connection to a Database | DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b | x13, a7, b8
Yen and Euro both return correct Country value | 2.Euro returns, error at line
25
BigOlLongStringWithMeaninglessName | tick all
Compilation of class A will fail. Compilation of class B will succeed | B fail,
A succeed
Line 46 will compile if enclosed in a try block, where TestException is caught |
2.if the enclosing, is caught
Holder h = new Holder() | 101
Decrementer dec = new Decrementer() | 12.3
Test t = (new Base()).new Test(1) | 2.new Test(1), new Test(1, 2)
Base(int j, int k, int l) | 2.Base(), Base(int j, int k)
Line 12 will not compile, because no version of crunch() takes a char argument |
output: int version
output results when the main method of the class Sub is run | Value 5 This value
6
Float floater = new Float(3.14f) | Line 6
The application must be run with the -enableassertions flag or another assertion
enabling flag | dai nhat, one or more
After line 3 executes, the StringBuffer object is eligible for garbage collectio
n | line 2 executes..collection
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | type SwampThing
The code will compile and run, but the cast in line 6 is not required and can be
eliminated | The code will compile and run
for (int i = 0; i < 2; i++) | 4.i0,j12 - i1,j02
outer: for (int i = 0; i < 2; i++) | i = 1 j = 0
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | Line 7 will not compile
int[] x = new int[25] | 2.x[24]=0, x.length is 25
public float aMethod(float a, float b) throws Exception | int a,b float p,q
public float aMethod(float a, float b, int c) throws Exception | 3.int a,b. floa
t a,b-int c. private
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i | Arrays.equals(a1, a2)
Assuming the class does not perform custom serialization, which fields are writt
en when an instance of Xyz is serialized | 3.Public, Private, Volatile
can legally be placed before aMethod() on line 3 and be placed before aMethod()
on line 8 | 3: private; 8: protected
NUTMEG, CINNAMON, CORIANDER, ROSEMARY | 3.Spice sp, Spice, String
List<String> names = new ArrayList<String>() | 2.Iterator, for
Compilation fails because of an error in line 15 | error in line 19
1 2 3 | 2 3
public interface B inheritsFrom A | B extends A
protected double getSalesAmount() { return 1230.45; } | 2.public, protected
Line 16 creates a directory named d and a file f within it in the file system | 3.An
exception, Line 13, line 14
Nav.Direction d = Nav.Direction.NORTH | Nav.Direction.NORTH
new class Foo { public int bar() { return 1; } } | new Foo()
IllegalArgumentException | StackOverflowError
Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw() | Shape s = ne
w Circle...s.draw()
Compilation fails because of an error in line 12 | 1 2 3
NullPointerException | Compilation fails
A NumberFormatException is thrown by the parse method at runtime | Compilation f
ails
An exception is thrown at runtime | Compilation fails
passed An AssertionException is thrown without the word stuff added to the stack t
race | An AssertionError...with the
collie | collie harrier
doStuff x = 6 main x = 6 | doStuff x =5 main x =5
The setCardlnformation method breaks encapsulation | The ownerName
The value of all four objects prints in natural order | Compilation fails...line
29
The code on line 33 executes successfully | 3.33 throws, 35 throws, 33 executes
What is the result if a NullPointerException occurs on line 34 | ac
Compilation will fail because of an error in line 55 | Line 57...value 3
java -ea test file1 file2 | 2.java -ea test, dai nhat
String s = 123456789 ; s = (s- 123 ).replace(1,3, 24 ) - 89 | 2.delete(4,6), delete(2,5)
rt( 1, 24 )
The Point class cannot be instatiated at line 15 | Line.Point p = new Line.Point
()
for( int i=0; i< x.length; i++ ) System.out.println(x[i]) | 2.for(int z : x),
dai nhat
int MY_VALUE = 10 | 3.final, static, public
Compilation fails because of an error in line: public void process() throws Runt
imeException | A Exception
How can you ensure that multithreaded code does not deadlock | There is no singl
e
How can you force garbage collection of an object | Garbage collection
How do you prevent shared data from being corrupted in a multithreaded environme
nt | Access the variables
How do you use the File class to list the contents of a directory | String[] con
tents
The number of bytes depends on the underlying system | 8
How many locks does an object have | One
If all three top-level elements occur in a source file, they must appear in whic
h order | Package declaration, imports
the two classes are in different packages, and class X has a protected method ca
lled abby(), then any instance of Y may call the abby() method of any | F
TestThread3 ttt = new TestThread3 | Y
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method | Comparable...compareTo
after execution of line 1, sbuf references an instance of the StringBuffer class
. After execution of line 2, sbuf still references the same instance | T
what are the possible types for variable result | int, long, float, double
helps manage the connection between a Java program and a database | Connection
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances | Y
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks | Y
JDBC supports ______ and ______ models | Two-tier and three-tier
MVC is short call of | Model-View-Controller
No output because of compile error at line: System.out.println("b="+b) | b = b *
b1
Object ob2= new Object() | Have a nice day
Object ob2= ob1 | ob1 equals ob2, ob1==ob2
String s2 = "xyz" | Line 4, Line 6
String s2 = new String("xyz") | Line 6
String s2 = new String(s1) | Line 6
Select correct statement about RMI | All the above
Select correct statement(s) about remote class | All the others choices
Select correct statements about remote interface | All the others choices
Select INCORRECT statement about serialization | When an Object Output
Select INCORRECT statement about deserialize | We use readObject
Select incorrect statement about RMI server | A client accesses
Select incorrect statement about ServerSocket class | To make the new object
Select incorrect statement about Socket class | server through UDP
Select the correct statement about JDBC two-tier processing model | A user's com
mands
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query | WHERE
Statement objects return SQL query results as | ResultSet
When a JDBC connection is created, it is in auto-commit mode | Both 1 and 2 are
true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block | If the JVM doesn't crash
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class | no
additional time
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file | slightly more time
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable | C must have a
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable | B must have a
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething() | private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething() | 2.public, protec
ted
void doSomething(int a, float b) | public...(int a, float b)
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods | 2.declared abstract, may not be
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries | for (float f:
salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal | When the...x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant | if (x == y)
Suppose you are writing a class that will provide custom deserialization. What a
ccess mode should the readObject() method have | private
Suppose you are writing a class that will provide custom serialization. What acc
ess mode should the writeObject() method have | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality | Override run()
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods | subclass java.lang.Math
Swing components cannot be combined with AWT components | T
class is the primary class that has the driver information | DriverManager
class is used to implement a pull-down menu that provides a number of items to s
elect from | Menu
The element method alters the contents of a Queue | F
The Swing component classes can be found in the | javax.swing
There are two classes in Java to enable communication using datagrams namely | D
ataPacket and DataSocket
Compilation of Parrot.java fails at line 7 because method getRefCount() is stati
c in the superclass, and static methods may not be overridden to be nonstatic |
dai nhat: nonstatic
Compilation of Nightingale will succeed, but an exception will be thrown at line
10, because method fly() is protected in the superclass | The program...After:
2
void doSomething() throws IOException, EOFException | ngan-dai nhat, throws EOFE
xception
URL referring to databases use the form | protocol:subprotocol:datasoursename
What are the legal types for whatsMyType | There are no possible legal types
What does the following code do | Throws an exception
There is no output because the code throws an exception at line 1 | output is i
= 20
1000 | -1
What happens when you try to compile and run the following application | thrown
at line 9
The code compiles, and prints out >>null<< | out >>null<<
An exception is thrown at line 6 | thrown at line 7
What is -50 >> 2 | -13
What is 7 % -4 | 3
What is -8 % 5 | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion | There is no difference
The code will compile as is. No modification is needed | On line 1, remove
What is the range of values that can be assigned to a variable of type byte | ?2
mu7 through 2mu7 ? 1
What is the range of values that can be assigned to a variable of type short | ?
2mu15 through
The code compiles and executes; afterward, the current working directory contain
s a file called datafile | The code fails to compile
What is the return type of the instanceof operator | A boolean
What method of the java.io.File class can create a file on the hard drive | crea
teNewFile()
The output: value is 99.99 | value is 9.0
The output: b contains 250 | b contains 5
What would be the output from this code fragment | message four
When a byte is added to a char, what is the type of the result | int
When a negative byte is cast to a long, what are the possible values of the resu
lt | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt | All the above
When a short is added to a float, what is the type of the result | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two | writing a line
When does an exception's stack trace get recorded in the exception object | is c
onstructed
When is it appropriate to pass a cause to an exception's constructor | in respon
se to catching
When is it appropriate to write code that constructs and throws an error | Never
When is x & y an int | Sometimes
When the user attempts to close the frame window, _______ event in generated | w
indow closing
When the user selects a menu item, _______ event is generated | Action event
Java programming language, the compiler converts the human-readable source file
into platform-independent code that a Java Virtual Machine can understand | byte
code
Whenever a method does not want to handle exceptions using the try block, the |
throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database | String url =jdbc:odbc
Which class and static method can you use to convert an array to a List | Arrays
.asList
Which is four-step approach to help you organize your GUI thinking | Identify, I
solate, Sketch
Which is the four steps are used in working with JDBC | Connect, Create, Look
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r | sc.useDelimiter("\\d")
Man has the best friend who is a Dog | private Dog bestFriend
Which methods return an enum constant s name | 2.name(), toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state | transient
Which of the following are legal argument types for a switch statement | 3.byte,
int, char
Which of the following are legal enums | 3.ngan-dai nhat, lion int weight
Which of the following are legal import statements | 2.import...Vector, Vector.*
Which of the following are legal loop constructions | for (int k=0, j+k != 10; j
++,k++)
Which of the following are legal loop definitions | None of the above
double d = 1.2d5 | 2.double d = 1.2d, 1.2D
int d = 0XABCD | 2.int c = 0xabcd, dai nhat
char c = 0x1234 | 2.0x.., '\u1234'
Vector <String> theVec = new Vector<String>() | 2.List...<String>(), dai nhat
Which of the following are methods of the java.util.SortedMap interface | headMa
p, tailMap, subMap
Which of the following are methods of the java.util.SortedSet interface | All th
e above
System.out has a println() method | All the above
The JVM runs until there is only one non-daemon thread | are no non-daemon
When an application begins running, there is one non-daemon thread, whose job is
to execute main() | 3.nhat, thread, non-daemon thread
When you declare a block of code inside a method to be synchronized, you can spe
cify the object on whose lock the block should synchronize | 2.the method always
, nhat
An enum definition should declare that it extends java.lang.Enum | 2.contain pub
lic, private
Primitives are passed by reference | 2.by value
An anonymous inner class that implements several interfaces may extend a parent
class other than Object | implement at most, class may extend
Which of the following are valid arguments to the DataInputStream constructor |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or | All the above
Which of the following calls may be made from a non-static synchronized method |
All the above
Which of the following classes implement java.util.List | 2.ArrayList, Stack
Which of the following classes implements a FIFO Queue | LinkedList
Which of the following declarations are illegal | 3.ngan-dai nhat, double d
int x = 6; if (!(x > 3)) | 2.dai nhat, x = ~x
String x = "Hello"; int y = 9; if (x == y) | 2.ngan nhat, x=x+y
Which of the following expressions results in a positive value in x | int x = 1;
x = x >>> 5
Which of the following interfaces does not allow duplicate objects | Set
Which of the following is not appropriate situations for assertions | Preconditi
ons of a public method
Which of the following is NOTa valid comment | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method | IllegalArgumentException
Readers have methods that can read and return floats and doubles | None of the a
bove
An enum definition may contain the main() method of an application | All the abo
ve
Which of the following may appear on the left-hand side of an instanceof operato
r | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or | 2.A class, An interface
Which of the following may be declared final | 2.Classes, Methods
Which of the following may be statically imported | 2.Static method, Static fiel
d
Which of the following may follow the static keyword | 3.Data, Methods, Code blo
cks
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation | All of
Which of the following may not be synchronized | Classes
Which of the following may override a method whose signature is void xyz(float f
) | 2.void, public void xyz(float f)
Which of the following methods in the Thread class are deprecated | suspend() an
d resume()
Which of the following operations might throw an ArithmeticException | None of
Which of the following operators can perform promotion on their operands | 3.con
g, tru, xap xi
Which of the following restrictions apply to anonymous inner classes | must be d
efined
Which of the following should always be caught | Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application | 2.static void...(String arg[])
Which of the following statements about the wait() and notify() methods is true
| calls wait() goes into
Which of the following statements about threads is true | Threads inherit their
A final class may not contain non-final data fields | may not be extended
An abstract class must declare that it implements an interface | None
An abstract class may not have any final methods | Only statement 2
Only object references are converted automatically; to change the type of a prim
itive, you have to do a cast | Both primitives
Transient methods may not be overridden | variables are not
Object references can be converted in both method calls and assignments, but the
rules governing these conversions are very different | conversions are identica
l
Bytecode characters are all 16 bits | Unicode characters
To change the current working directory, call the changeWorkingDirectory() metho
d of the File class | None
When you construct an instance of File, if you do not use the file-naming semant
ics of the local machine, the constructor will throw an IOException | None
When the application is run, thread hp1 will execute to completion, thread hp2 w
ill execute to completion, then thread hp3 will execute to completion | None of
Compilation succeeds, although the import on line 1 is not necessary. During exe
cution, an exception is thrown at line 3 | fails at line 2
Compilation fails at line 1 because the String constructor must be called explic
itly | succeeds. No exception
Line 4 executes and line 6 does not | Line 6 executes
There will be a compiler error, because class Greebo does not correctly implemen
t the Runnable interface | Runnable interface
The acceptable types for the variable j, as the argument to the switch() constru
ct, could be any of byte, short, int, or long | value is three
The returned value varies depending on the argument | returns 0
Lines 5 and 12 will not compile because the method names and return types are mi
ssing | output x = 3
Line 13 will not compile because it is a static reference to a private variable
| output is x = 104
Which statements about JDBC are NOT true | 2.database system, DBMS
Which two code fragments correctly create and initialize a static array of int
elements | 2.a = { 100,200 }, static
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework | 2.Map, Collection
A new directory called dirname and a new file called filename are created, both
in the current working directory | No directory
protected class Cat extends Owner | public class Cat extends Pet
Date vaccinationDue | 2.boolean, String
What is -15 % -10 | -5
command line on a Windows system | 2.must contain the statement, the file
The string created on line 2 does not become eligible for garbage collection in
this code | After line 3
When the application runs, what are the values of n and w.x after the call to bu
mp() in the main | n is 10, w.x is 11
The addAll() method of that interface takes a single argument, which is a ref
erence to a collection whose elements are compatible with E. What is the declar
ation of the addAll() method | addAll(Collection<? extends E> c)
If you want a vector in which you know you will only store strings, what are the
advantages of using fancyVec rather than plainVec | Attempting to...compiler er
ror
When should objects stored in a Set implement the java.util.Comparable interfac
e | Set is a TreeSet
What relationship does the extends keyword represent | is a
class bbb.Bbb, which extends aaa.AAA, wants to override callMe(). Which access m
odes for callMe() in aaa.AAA will allow this | 2.public, protected
Lemon lem = new Lemon(); Citrus cit = new Citrus() | 3.cit = lem, cit=(Citrus),
lem=(lemon)
it also has a method called chopWoodAndCarryWater(), which just calls the other
two methods | inappropriate cohesion, inappropriate coupling
sharedOb.wait() | 2.aThread.interrupt, sharedOb.notifyAll
line prints double d in a left-justified field that is 20 characters wide, with
15 characters to the right of the decimal point | System.out.format("%-20.15f",
d)
What code at line 3 produces the following output | String delim = \\d+
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc | NumberFormat.getInstance(loc)
you want to use a DateFormat to format an instance of Date. What factors influ
ence the string returned by DateFormat s format() method | 2.LONG, or FULL, The lo
cale
you want to create a class that compiles and can be serialized and deserialized
without causing an exception to be thrown. Which statements are true regarding
the class | 2.dai nhat, ngan nhat
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
What interfaces can be implemented in order to create a class that can be serial
ized | 2.dai nhat, ngan nhat
The file contains lines of 8-bit text, and the 8-bit encoding represents the lo
cal character set, as represented by the cur- rent default locale. The lines are
separated by newline characters | FileReader instance
shorty is a short and wrapped is a Short | all
How is IllegalArgumentException used | 2.certain methods, public methods
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction | None
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime | 2.assert x == 4
int[] ages = { 9, 41, 49 }; int sum = 0 | 2.i<ages.length, for (int i:ages)
Which of the following types are legal arguments of a switch statement | enums,
bytes
class A extends java.util.Vector { private A(int x) | does not create a defau
lt
void callMe(String names) | method, names is an array
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards | public Color ge
tTheTint()
are valid arguments to the DataInputStream constructor | FileInputStream
are valid mode strings for the RandomAccessFile constructor | r, rw, rws, rwd
method of the java.io.File class can create a file on the hard drive | createNe
wFile()
class A extends Object; Class B extends A; and class C extends B. Of these, only
class C implements java.io.Externalizable | C must have
class A extends Object; class B extends A; and class C extends B. Of these, only
class C implements java.io.Serializable | B must have
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
you are writing a class that will provide custom serialization. The class implem
ents java.io.Serializable (not java.io.Externalizable) | private
How do you use the File class to list the contents of a directory | String[] c
ontents = myFile.list();
call returns true if a1 and a2 have the same length, and a1[i].equals(a2[i]) fo
r every legal index i | java.util.Arrays.equals(a1, a2)
line of code tells a scanner called sc to use a single digit as a delimiter | sc
.useDelimiter( \\d )
you want to write a class that offers static methods to compute hyperbolic trigo
nometric functions. You decide to subclass java.lang.Math and provide the new f
unctionality as a set of static methods | java.lang.Math
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string | none
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do | Override run()
you prevent shared data from being corrupted in a multithreaded environment | Ac
cess the variables
Is it possible to write code that can execute only if the current thread owns
multiple locks | yes
Which of the following may not be synchronized | Classes
statements about the wait() and notify() methods is true | pool of waiting th
reads
methods in the Thread class are deprecated | suspend() and resume()
A Java monitor must either extend Thread or implement Runnable | F
One of the threads is thr1. How can you notify thr1 so that it alone moves from
the Waiting state to the Ready state | You cannot specify
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread | F
Which methods return an enum constant s name | name(), toString()
restrictions apply to anonymous inner classes | inside a code block
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual d
escription of its markings | boolean, string
Which of the following are valid declarations? Assume java.util | 1Vector 2Set 3
Map string,string
You can determine all the keys in a Map in which of the following ways | Set ob
ject from the Map
What keyword is used to prevent an object from being serialized | transient
abstract class can contain methods with declared bodies. | E. public, protecte
d, default, private
access modifier allows you to access method calls in libraries not created in J
ava | native
Which of the following statements are true? (Select all that apply.) | object c
annot reassigned
The keyword extends refers to what type of relationship | is a
keywords is used to invoke a method in the parent class | super
What is the value of x after the following operation is performed | 3
method call is used to tell a thread that it has the opportunity | notify()
Assertions are used to enforce all but which | Exceptions
force garbage collection by calling System.gc(). | B. False
Select the valid primitive data type | 1.boolean 2.char 3.float
How many bits does a float contain | 32
What is the value of x after the following line is executed | 32
StringBuffer is slower than a StringBuilder, but a StringBuffer | True
list of primitives ordered in smallest to largest bit size representation | D.
char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion | java.text.DateFormat
int x = 9; byte b = x | False
Which of the following code snippets compile | 1.Integer 2.Integer 3.byte
Java arrays always start at index 1 | False
accurately describes how variables are passed to methods | that are primitive t
ype are passed by value
change the value that is encapsulated by a wrapper class after you have instan
| None of the above.
The class implements java.io.Serializable (and not java.io.Externalizable) | pri
vate readObject
A signed data type has an equal number of non-zero positive and negative value
s | False
signatures are valid for the main() method entry point of an application | publi
c static void main(String[] args)
three top-level elements occur in a source file, they must appear | Package decl
aration, imports, class/interface/enum definitions
int[] x = new int[25] | x[24] is 0 and x.length is 25
How can you force garbage collection of an object | Garbage collection cannot
be forced.
range of values that can be assigned to a variable of type short | -215 through
215 - 1
range of values that can be assigned to a variable of type byte | -27 through 2
7 - 1
How do the imports affect the time required to compile the source file | Compi
lation takes slightly more time
How do the imports affect the time required to load the class? | Class loading
takes no additional time
legal import statements | 1.import java.util.Vector 2.import static java.ut
il.Vector
may be statically imported | 1.Static method names 2.Static field names
int c = 0xabcd and int d = 0XABCD | 2 dap an
double d = 1.2d and double d = 1.2D | 2 dap an
char c = \u1234 | 1 dap an
passed by value and passed by value | 2 dap an
int x = 6; if (!(x > 3)) and int x = 6; x = ~x | 2 dap an
int x = 1; x = x >>> 5 | 1 dap an
int y = 9; x += y; and int y = 9; x = x + y; | 2 dap an
What is -8 % 5 | -3
What is 7 % -4? | 3
ob1 == ob2 | No
When a byte is added to a char | int
When a short is added to a float | float
ArithmeticException | 1.None of these 2./
What is the return type of the instanceof operator | boolean
may appear on the left-hand side of an instanceof operator | reference
may appear on the right-hand side of an instanceof operator | class and interfa
ce
What is -50 >> 1 | -25
default String s ,, abstract double d ,, double hyperbolic | 3 dap an
A final class may not have any abstract methods | true
denote a variable that should not be written out as part of its class s persistent
state | transient
Both primitives and object references can be both converted and cast | dap an
and the rules governing these conversions are identical | dap an
may legally appear as the new type (between the parentheses) in a cast operati
on | All of the above
type of x is a class, and the declared type of y is an interface. When is the as
signment x = y | When the type of x is Object
xarr is an array of XXX, and the type of yarr is an array of YYY | Sometimes
When is x & y an int | Sometimes
negative long is cast to a byte | All of the above
negative byte is cast to a long | Negative
operators can perform promotion on their operands | + - ~(nga)
difference between the rules for method-call conversion and the rules for assign
ment conversion | There is no difference
Which of the following are appropriate situations for assertions | DAP AN SAI :
Preconditions of a public method
appropriate way to handle invalid arguments in a public method | IllegalArgumen
tException
Suppose salaries is an array containing floats | for (float f:salaries)
Suppose a method called finallyTest() consists of a try block | If the JVM does
n t crash and
appropriate to pass a cause to an exception s constructor | thrown in response to
catching of a different exception type
Which of the following should always be caught | Checked exceptions
When does an exception s stack trace get recorded in the exception object | is c
onstructed
Which of the following are valid declarations? Assume java.util.* is imported. |
Map<String> m;
You can determine all the keys in a Map in which of the following ways?|By getti
ng a Set object from the Map and iterating through it.
What keyword is used to prevent an object from being serialized?|transient
An abstract class can contain methods with declared bodies.|True
Select the order of access modifiers from least restrictive to most restrictive.
|public, protected, default, private
Which access modifier allows you to access method calls in libraries not created
in Java?|native
Which of the following statements are true? (Select all that apply.)|A final obj
ect cannot be reassigned a new address in memory.
The keyword extends refers to what type of relationship?| is a
Which of the following keywords is used to invoke a method in the parent class?|
super
What is the value of x after the following operation is performed? x = 23 %
4; |3
What method call is used to tell a thread that it has the opportunity to run?|n
otify()
Assertions are used to enforce all but which of the following?|Exceptions
The developer can force garbage collection by calling System.gc().|False
Select the valid primitive data types. (Select all that apply.)|boolean, char, f
loat
How many bits does a float contain?|32
What is the value of x after the following line is executed? x = 32 * (31 -
10 * 3); |32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
|True
Select the list of primitives ordered in smallest to largest bit size representa
tion.|char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion?|java.text.DateFormat
The following line of code is valid. int x = 9; byte b = x;|False
Which of the following code snippets compile?|Integer i = 7;, Integer i =
new Integer(5); int j = i;, byte b = 7;
Java arrays always start at index 1.|False
Which of the following statements accurately describes how variables are passed
to methods?|Arguments that are primitive type are passed by value.
How do you change the value that is encapsulated by a wrapper class after you h
ave instan- tiated it?|None of the above.
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method s
hould imple- ment the custom deserialization, and what is its access mode?|priva
te readObject
A signed data type has an equal number of non-zero positive and negative values
available.|False
Choose the valid identifiers from those listed here. (Choose all that apply.)|Bi
gOlLongStringWithMeaninglessName, $int, bytes, $1, finalist
Which of the following signatures are valid for the main() method entry point of
an application? (Choose all that apply.)|public static void main(String arg[])
, public static void main(String[] args)
If all three top-level elements occur in a source file, they must appear in whi
ch order?|Package declaration, imports, class/interface/enum definitions.
How can you force garbage collection of an object?|Garbage collection cannot b
e forced.
What is the range of values that can be assigned to a variable of type short?| ?
2^15 through 2^15 ? 1
What is the range of values that can be assigned to a variable of type byte?| ?2
^7 through 2^7 ? 1
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file?| Compilation takes
slightly more time.
Suppose a source file contains a large number of import statements and one class
definition.How do the imports affect the time required to load the class?|Cla
ss loading takes no additional time.
Which of the following are legal import statements?| import java.util.Vector;,
import static java.util.Vector.*;
Which of the following may be statically imported? (Choose all that apply.)| St
atic method names, Static field names
Which of the following are legal? (Choose all that apply.)| int c = 0xabcd;,
int d = 0XABCD;
Which of the following are legal? (Choose all that apply.)| double d = 1.2d;,
double d = 1.2D;
Which of the following are legal?| char c = \u1234 ;
Which of the following are true? (Choose all that apply.)| Primitives are passe
d by value., References are passed by value.
Which of the following expressions are legal? (Choose all that apply.)| int x
= 6; if (!(x > 3)) {}, int x = 6; x = ~x;
Which of the following expressions results in a positive value in x?| int x = 1
; x = x >>> 5;
Which of the following expressions are legal? (Choose all that apply.)| String
x = "Hello"; int y = 9; x += y;, String x = "Hello"; int y = 9; x
= x + y;
What is -8 % 5?|-3
What is 7 % -4?|3
Is it possible to define a class called Thing so that the following method can
return true under certain circumstances? boolean weird(Thing s) { Integer x
= new Integer(5); return s.equals(x); }|Yes
Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 ==
ob2) is false, can ob1.equals(ob2) ever be true?|No
When a byte is added to a char, what is the type of the result?|int
When a short is added to a float, what is the type of the result?|float
Which statement is true about the following method?int selfXor(int i) { return
i ^ i;}|It always returns 0
Which of the following operations might throw an ArithmeticException?|None of th
ese
Which of the following operations might throw an ArithmeticException?|/
Which of the following may appear on the left-hand side of an instanceof operat
or?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose all that apply.)|A class, An interface
What is -50 >> 1?|-25
Which of the following declarations are illegal? (Choose all that apply.)| defau
lt String s;, abstract double d;, abstract final double hyperboli
cCosine();
Which of the following statements is true?|A final class may not have any abstra
ct methods.
Which of the following statements is true?|Transient variables are not serialize
d.
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class s persistent state? (Choose the shortest pos
sible answer.)|transient
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access mod
es may Subby s version of the method have? (Choose all that apply.)|public, p
rotected
Which of the following statements are true?|None of the above.
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five int
erface methods. Which is/are true?|The class will compile if it is declared abst
ract., The class may not be instantiated.
Which of the following may be declared final? (Choose all that apply.)|Classes,
Data, Methods
Which of the following may follow the static keyword? (Choose all that apply.)|
Data, Methods, Code blocks enclosed in curly brackets
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may apply to
B s version of doSomething()? (Choose all that apply.)|public, protected, Def
ault
True or false: If class Y extends class X, the two classes are in different pack
ages, and class X has a protected method called abby(), then any instance of Y
may call the abby() method of any other instance of Y.|False
Which of the following statements are true?|A final class may not be extended.
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.)|Object references can b
e converted in both method calls and assignments, and the rules governing the
se conversions are identical.
Which of the following statements is true? (Choose one.)|Line 7 will not compile
; an explicit cast is required to convert a Washer to a SwampThing.
Which of the following may legally appear as the new type (between the parenthe
ses) in a cast operation?|All of the above
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal?|When the type of x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal?|Sometimes
When is x & y an int? (Choose one).|Sometimes
What are the legal types for whatsMyType? short s = 10; whatsMyType = !s;|There
are no possible legal types.
When a negative long is cast to a byte, what are the possible values of the resu
lt?|All of the above
Which of the following operators can perform promotion on their operands? (Choo
se all that apply.)|+, -, ~
When a negative byte is cast to a long, what are the possible values of the resu
lt?|Negative
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion?|There is no difference; the rules are the same.
Which of the following are appropriate situations for assertions?|Postconditions
of a public method, Preconditions of a private method, Postconditions o
f a private method
Which of the following is the most appropriate way to handle invalid arguments
in a public method?|Throw java.lang.IllegalArgumentException.
Which of the following are legal? (Choose all that apply.)|for (int i=0, j=1; i
<10; i++, j++), for (int i=0, j=1;; i++, j++), for (String s = ; s.le
ngth()<10; s += ! )
Suppose a method called finallyTest() consists of a try block, followed by a ca
tch block, followed by a finally block. Assuming the JVM doesn t crash and the cod
e does not execute a System.exit() call, under what circumstances will the fina
lly block not begin to execute?|If the JVM doesn t crash and the code does not exe
cute a System.exit() call, the finally block will always execute.
Which of the following are legal loop definitions? (Choose all that apply.)|Non
e of them are legal.
Which of the following are legal argument types for a switch statement?|byte,
int, char
When is it appropriate to pass a cause to an exception s constructor?|When the exc
eption is being thrown in response to catching of a different exception type
Which of the following should always be caught?|Checked exceptions
When does an exception s stack trace get recorded in the exception object?|When
the exception is constructed
When is it appropriate to write code that constructs and throws an error?|Never
Which of the following statements are true? (Choose all that apply.)|Given that
Inner is a nonstatic class declared inside a public class Outer and that appro-
priate constructor forms are defined, an instance of Inner can be constructed l
ike this: new Outer().new Inner()
Which of the following may override a method whose signature is void xyz(float
f)?|void xyz(float f), public void xyz(float f)
Which of the following are true? (Choose all that apply.)|An enum may contain p
ublic method definitions., An enum may contain private data
Which of the following are true? (Choose all that apply.)|An enum definition ma
y contain the main() method of an application., You can call an enum s
toString() method., You can call an enum s wait() method., You can ca
ll an enum s notify() method.
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant?|if (x == y)
Which of the following restrictions apply to anonymous inner classes?|They must
be defined inside a code block.
Which of the following are true?|An anonymous inner class may implement at most
one interface., An anonymous inner class may extend a parent class other
than Object.
Which methods return an enum constant s name?|name(), toString()
Suppose class X contains the following method: void doSomething(int a, float b)
{ } Which of the following methods may appear in class Y, which extend
s X?|public void doSomething(int a, float b) { }
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread.|False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1
so that it alone moves from the Waiting state to the Ready state?|You cannot s
pecify which thread will get notified.
A Java monitor must either extend Thread or implement Runnable.|False
Which of the following methods in the Thread class are deprecated?|suspend() an
d resume()
Which of the following statements about threads is true?|Threads inherit the
ir priority from their parent thread.
Which of the following statements about the wait() and notify() methods is tr
ue?|The thread that calls wait() goes into the monitor s pool of waiting threads
.
Which of the following may not be synchronized?|Classes
How many locks does an object have?|One
Is it possible to write code that can execute only if the current thread owns
multiple locks?|Yes.
Which of the following are true?|The JVM runs until there are no non-daemon thre
ads.
How do you prevent shared data from being corrupted in a multithreaded environme
nt?|Access the variables only via synchronized methods.
How can you ensure that multithreaded code does not deadlock?|A, B, and C do not
ensure that multithreaded code does not deadlock.
Which of the following are true? (Choose all that apply.)|When you declare a met
hod to be synchronized, the method always synchronizes on the lock of the curren
t object., When you declare a block of code inside a method to be synchron
ized, you can specify the object on whose lock the block should synchronize.
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do?|Override run().
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string?|None of the above
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide t
he new functionality as a set of static methods. Which one statement is true ab
out this strategy?|The strategy fails because you cannot subclass java.lang.Ma
th.
Suppose prim is an int and wrapped is an Integer. Which of the following are le
gal Java statements? (Choose all that apply.)|prim = wrapped;, wrapped =
prim;, prim = new Integer(9);, wrapped = 9;
Which of the following are legal? (Choose all that apply.)|List<String> theList
= new Vector<String>();, Vector <String> theVec = new Vector<String>()
;
Given the following, Map<String> names = new HashMap<String>(); which of the
following are legal? (Choose all that apply.)|Iterator<String> iter = names.ite
rator();, for (String s:names)
Which of the following classes implement java.util.List?|java.util.ArrayList,
java.util.Stack
Which of the following are methods of the java.util.SortedSet interface?|first,
last, headSet, tailSet, subSet
Which of the following are methods of the java.util.SortedMap interface?|headMap
, tailMap, subMap
Which line of code tells a scanner called sc to use a single digit as a delimite
r?|sc.useDelimiter( \\d );
Given arrays a1 and a2, which call returns true if a1 and a2 have the same leng
th, and a1[i].equals(a2[i]) for every legal index i?|java.util.Arrays.equals(a1
, a2);
Which of the following statements are true?|StringBuilder is generally faster th
an StringBuffer., StringBuffer is threadsafe; StringBuilder is not.
Which of the statements below are true? (Choose all that apply.)|Unicode charact
ers are all 16 bits.
How do you use the File class to list the contents of a directory?|String[] con
tents = myFile.list();
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have?|private
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access m
ode should the readObject() method have?|private
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C
?|B must have a no-args constructor.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C?|C must have a no-args constructor.
What method of the java.io.File class can create a file on the hard drive?|crea
teNewFile()
Which of the following are true? (Choose all that apply.)|System.out has a print
ln() method., System.out has a format() method., System.err has a printl
n() method., System.err has a format () method.
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose all that apply.)| r , rw , rws , rwd
Which of the following are valid arguments to the DataInputStream constructor?|F
ileInputStream
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards?|public Color get
TheTint()
Which of the following statements are true regarding the following method? void
callMe(String names) { }|Within the method, names is an array containing St
rings.
Which of the following types are legal arguments of a switch statement?|enums,
bytes
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime.|assert x == 4;, assert x == 4 : x is not 4 ;
Which are appropriate uses of assertions?|Checking preconditions in a private me
thod, Checking postconditions in a private method, Checking postcondition
s in a public method
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction?|None of the a
bove.
How is IllegalArgumentException used? (Choose all correct options.)|It is thrown
by certain methods of certain core Java classes to indicate that preconditions
have been violated., It should be used by programmers to indicate that p
reconditions of public methods have been violated.
Suppose shorty is a short and wrapped is a Short. Which of the following are leg
al Java state- ments? (Choose all correct options.)|shorty = wrapped;, wra
pped = shorty;, shorty = new Short((short)9);, shorty = 9;
Which of the following statements are true? (Choose all correct options.)|Strin
gBuilder encapsulates a mutable string., StringBuffer is threadsafe.
Suppose you want to read a file that was not created by a Java program. The file
contains lines of 8-bit text, and the 8-bit encoding represents the local char
acter set, as represented by the cur- rent default locale. The lines are separat
ed by newline characters. Which strategy reads the file and produces Java strin
gs?|Create a FileReader instance. Pass it into the constructor of LineNumberRea
der. Use LineNumberReader s readLine() method.
What interfaces can be implemented in order to create a class that can be serial
ized? (Choose all that apply.)|Have the class declare that it implements java.io
.Serializable. There are no methods in the interface., Have the class decl
are that it implements java.io.Externalizable, which defines two methods: read
External and writeExternal
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access m
ode should the readObject() method have?|private
Suppose you want to create a class that compiles and can be serialized and deser
ialized without causing an exception to be thrown. Which statements are true r
egarding the class? (Choose all correct options.)|If the class implements java
.io.Externalizable, it must have a no-args constructor., If the class impleme
nts java.io.Serializable and does not implement java.io.Externalizable, its nea
rest superclass that doesn t implement Serializable must have a no-args construct
or.
Suppose you want to use a DateFormat to format an instance of Date. What facto
rs influence the string returned by DateFormat s format() method?|The style, which
is one of SHORT, MEDIUM, LONG, or FULL, The locale
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc?|NumberFormat nf = NumberFormat.getInstance(loc);
String s = nf.format(f);
Which line prints double d in a left-justified field that is 20 characters wide,
with 15 characters to the right of the decimal point?|System.out.format("%-20.1
5f", d);
Suppose MyThread extends java.lang.Thread, and MyRunnable implements java.lang.
Runnable (but does not extend Thread). Both classes have no-args constructors. W
hich of the following cause a thread in the JVM to begin execution? (Choose al
l correct options.)|(new MyThread()).start();, (new Thread(new MyRunnable
()))
What code can bThread execute in order to get aThread out of the waiting state,
no matter what other conditions prevail?|aThread.interrupt();, sharedOb.noti
fyAll();
Suppose class Home has methods chopWood() and carryWater(); it also has a method
called chopWoodAndCarryWater(), which just calls the other two methods. Which
statements are true? (Choose all that apply.)|chopWoodAndCarryWater() is an ex
ample of inappropriate cohesion., chopWoodAndCarryWater() is an example of in
appropriate coupling.
Suppose class aaa.Aaa has a method called callMe(). Suppose class bbb.Bbb, which
extends aaa.AAA, wants to override callMe(). Which access modes for callMe() i
n aaa.AAA will allow this?|public, protected
What relationship does the extends keyword represent?| is a
When should objects stored in a Set implement the java.util.Comparable interfac
e?|When the Set is a TreeSet
The java.util.Arrays class has a binarySearch(int[] arr, int key) method. Whi
ch statements are true regarding this method? (Choose all that apply.)|The me
thod is static., The return value is the index in the array of key., Th
e elements of the array must be sorted when the method is called.
When the application runs, what are the values of n and w.x after the call to bu
mp() in the main() method?|n is 10, w.x is 11
What is -15 % -10?|-5
is a set of java API for executing SQL statements.|JDBC
method is used to wait for a client to initiate communications.|accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect. Again, because of the native code, their portability is
limited.|Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source.|Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source.|Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generallydependent on a native library, whic
h limits their portability.|Type 1
A dialog prevents user input to other windows in the application unitl the dialo
g is closed.|Modal
A Java monitor must either extend Thread or implement Runnable.|False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.)|Y
ou cannot specify which thread will get notified.
A signed data type has an equal number of non-zero positive and negative values
available.|False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread.|False
A(n) object is used to submit a query to a database|Statement
A(n) object is uses to obtain a Connection to a Database|DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b? 1. int x, a = 6, b = 7; 2. x = a++ + b++;|x = 13, a = 7, b
= 8
Choose the valid identifiers from those listed here. (Choose all that apply.)|Bi
gOlLongStringWithMeaninglessName, $int, bytes, $1, finalist
How can you ensure that multithreaded code does not deadlock? (Choose one.)|Ther
e is no single technique that can guarantee non-deadlocking code.
How can you force garbage collection of an object? (Choose one.)|Garbage collect
ion cannot be forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? (Choose one.)|Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory? (Choose one.)
|String[] contents = myFile.list();
How many locks does an object have? (Choose one.)|One
If all three top-level elements occur in a source file, they must appear in whic
h order? (Choose one.)|Package declaration, imports, class/interface/enum defini
tions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any other instance of Y.|False
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use? (Choose one.)|TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? (Choose one.)|Comparable interface and its compareTo meth
od.
Interface helps manage the connection between a Java program and a databa
se.|Connection
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks?|Yes
JDBC supports and models.|Two-tier and three-tier
MVC is short call of|Model-View-Controller
Select correct statement about RMI. (choose 1)|All the above
Select correct statement(s) about remote class.(choose one)|All the others choic
es
Select correct statements about remote interface. (choose 1)|All the others choi
ces
Select INCORRECT statement about serialization. (choose 1)|When an Object Output
Stream serializes an object that contains references to another object, every r
eferenced object is not serialized along with the original object.
Select INCORRECT statement about deserialize. (choose 1)|We use readObject() met
hod of ObjectOutputStream class to deserialize.
Select incorrect statement about RMI server.(choose 1)|A client accesses a remot
e object by specifying only the server name.
Select incorrect statement about ServerSocket class. (choose 1)|To make the new
object available for client connections, call its accept() method, which returns
an instance of ServerSocket
Select incorrect statement about Socket class. (choose 1)|The java.net.Socket cl
ass contains code that knows how to find and communicate with a server through U
DP.
SQL keyword is followed by the selection criteria that specify the rows to
select in a query|WHERE
Statement objects return SQL query results as objects|ResultSet
Study the statements: 1)When a JDBC connection is created, it is in auto-commit
mode 2)Once auto-commit mode is disabled, no SQL statements will be committe
d until you call the method commit explicitly|Both 1 and 2 are true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block. Assuming the JVM doesn t crash and the code
does not execute a System.exit() call, under what circumstances will the finall
y block not begin to execute? (Choose one.)|If the JVM doesn't crash and the cod
e does not execute a System.exit() call, the finally block will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? (Cho
ose one.)|Class loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? (Choose one.)|Compil
ation takes slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? (Choose one.)|C must have a no-args constructor.
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C?
(Choose one.)|B must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? (Choose one)|private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby s version of the method have? (Choose two.)|public, protected
Suppose class X contains the following method:void doSomething(int a, float b) {
} Which of the following methods may appear in class Y, which extends X? (Choo
se one.)|public void doSomething(int a, float b) { }
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods. Which are true? (Choose two.)|The class will compile if it is dec
lared abstract., The class may not be instantiated.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.)|All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? (Choose one.)|
for (float f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? (Choose one.)|When the type of x is
Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? (Choose one.)|Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.)|if (x ==
y)
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access mo
de should the readObject() method have? (Choose one.)|private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? (Choose one.)|Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one statement is true abou
t this strategy?|The strategy fails because you cannot add static methods to a s
ubclass.
Swing components cannot be combined with AWT components.|True
The class is the primary class that has the driver information.|DriverManag
er
The class is used to implement a pull-down menu that provides a number of i
tems to select from.|Menu
The element method alters the contents of a Queue.|False
The Swing component classes can be found in the package.|javax.swing
There are two classes in Java to enable communication using datagrams namely.|Da
taPacket and DataSocket
What are the legal types for whatsMyType? (Choose one.) short s = 10; whatsMyTyp
e = !s;|There are no possible legal types.
What does the following code do? Integer i = null; if (i != null & i.intValue
() == 5) System.out.println("Value is 5");|Throws an exception.
What is -50 >> 2|-13
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? (Choose one.)|There is no difference; the rules are
the same.
What method of the java.io.File class can create a file on the hard drive?(Choos
e one.)|createNewFile()
When a byte is added to a char, what is the type of the result?|int
When a negative byte is cast to a long, what are the possible values of the resu
lt? (Choose one.)|Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? (Choose one.)|All the above
When a short is added to a float, what is the type of the result?|float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? (Choose one.)|writing a line separator
to the stream
When does an exception's stack trace get recorded in the exception object? (Choo
se one.)|When the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? (Choose on
e.)|When the exception is being thrown in response to catching of a different ex
ception type
When is it appropriate to write code that constructs and throws an error?(Choose
one.)|Never
When is x & y an int? (Choose one).|Sometimes
When the user attempts to close the frame window, event in generated.|win
dow closing
When the user selects a menu item, event is generated.|Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform- independent code that a
Java Virtual Machine can understand. What is this platform-independent code cal
led?|bytecode
Whenever a method does not want to handle exceptions using the try block, the
is used.|throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database?|String url ="jdbc:odbc:data_source_name"; Connection con
= DriverManager.getConnection (url, user", "password");
Which class and static method can you use to convert an array to a List?(Choose
one.)|Arrays.asList
Which is four-step approach to help you organize your GUI thinking.(Choose one.)
|Identify needed components. Isolate regions of behavior. Sketch the GUI. Choose
layout managers.
Which is the four steps are used in working with JDBC?| 1)Connect to the databa
se 2)Create a statement and execute the query 3)Look at the result set 4)Close
connection
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed?|two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? (Choose one.)|sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? (Choose one.)|class Man { private Dog bestFriend; }
Which methods return an enum constant s name? (Choose two.)|name(), toString(
)
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? (Choose the shortest pos
sible answer.)|transient
Which of the following are legal argument types for a switch statement?(Choose t
hree.)|byte, int, char
Which of the following are legal import statements? (Choose two.)||import java.u
til.Vector;, import static java.util.Vector.*;
Which of the following are legal loop constructions? (Choose one.)|int j = 0;
for (int k=0, j+k != 10; j++,k++) { System.out.println("j=" + j + ", k=" + k);
}
Which of the following are legal? (Choose three.)|for (int i=0, j=1; i<10; i++,
j++), for (int i=0, j=1;; i++, j++), for (String s = ""; s.length()<1
0; s += '!')
Which of the following are legal? (Choose two.)|double d = 1.2d;, doub
le d = 1.2D;
Which of the following are legal? (Choose two.)|int c = 0xabcd; int d = 0XABC
D;
Which of the following are legal? (Choose two.)|char c = 0x1234;, cha
r c = '\u1234';
Which of the following are legal? (Choose two.)|List<String> theList = new Vecto
r<String>();, Vector <String> theVec = new Vector<String>();
Which of the following are methods of the java.util.SortedSet interface?(Choose
one.)|All the above
Which of the following are true? (Choose one.)|The JVM runs until there are no n
on-daemon threads.
Which of the following are true? (Choose three.)|When an application begins runn
ing, there is one non-daemon thread,whose job is to execute main()., A thre
ad created by a daemon thread is initially also a daemon thread., A threa
d created by a non-daemon thread is initially also a non-daemon thread.
Which of the following are true? (Choose two.)|When you declare a method to be s
ynchronized, the method always synchronizes on the lock of the current object.,
When you declare a block of code inside a method to be synchronized, you
can specify the object on whose lock the block should synchronize.
Which of the following are true? (Choose two.)|An enum may contain public method
definitions., An enum may contain private data.
Which of the following are true? (Choose two.)|Primitives are passed by value.,
References are passed by value.
Which of the following are true? (Choose two.)|An anonymous inner class may impl
ement at most one interface., An anonymous inner class may extend a parent
class other than Object.
Which of the following calls may be made from a non-static synchronized method?
(Choose one.)|All the above
Which of the following classes implement java.util.List? (Choose two.)|java.util
.ArrayList, java.util.Stack
Which of the following classes implements a FIFO Queue? (Choose one.)|LinkedLis
t
Which of the following declarations are illegal? (Choose three.)|default String
s;, abstract double d;, abstract final double hyperboli
cCosine();
Which of the following expressions are legal? (Choose two.)|int x = 6; if (!(x >
3)) {}, int x = 6; x = ~x;
Which of the following expressions are legal? (Choose two.)|String x = "Hello";
int y = 9; x += y;, String x = "Hello"; int y = 9; x = x + y;
Which of the following expressions results in a positive value in x?(Choose one.
)|int x = 1; x = x >>> 5;
Which of the following interfaces does not allow duplicate objects?(Choose one.)
|Set
Which of the following is not appropriate situations for assertions?(Choose one)
|Preconditions of a public method
Which of the following is NOTa valid comment:|/* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method?|Throw java.lang.IllegalArgumentException.
Which of the following may appear on the left-hand side of an instanceof operato
r?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose two.)|A class, An interface
Which of the following may be declared final? (Choose two.)|Classes, Meth
ods
Which of the following may be statically imported? (Choose two.)|Static method n
ames, Static field names
Which of the following may follow the static keyword? (Choose three.)|Data,
Methods, Code blocks enclosed in curly brackets
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.)|All of the others
Which of the following may not be synchronized? (Choose one.)|Classes
Which of the following may override a method whose signature is void xyz(float f
)? (Choose two.)|void xyz(float f), public void xyz(float f)
Which of the following methods in the Thread class are deprecated?(Choose one.)|
suspend() and resume()
Which of the following operations might throw an ArithmeticException?(Choose one
.)|None of these
Which of the following operations might throw an ArithmeticException?(Choose one
.)|/
Which of the following operators can perform promotion on their operands? (Choos
e three.)|+ - ~
Which of the following restrictions apply to anonymous inner classes?(Choose one
.)|They must be defined inside a code block.
Which of the following should always be caught? (Choose one.)|Checked exceptions
Which of the following statements about the wait() and notify() methods is true?
(Choose one.)|The thread that calls wait() goes into the monitor s pool of waitin
g threads.
Which of the following statements about threads is true? (Choose one.)|Threads i
nherit their priority from their parent thread.
Which of the following statements are true? (Choose one.)|A final class may not
be extended.
Which of the following statements are true? (Choose one.)|Given that Inner is a
nonstatic class declared inside a public class Outer and that appropriate constr
uctor forms are defined, an instance of Inner can be constructed like this: new
Outer().new Inner()
Which of the following statements are true? (Choose one.)|None of the above
Which of the following statements are true? (Choose two.)|StringBuilder is gener
ally faster than StringBuffer., StringBuffer is threadsafe; StringBuilder is
not.
Which of the following statements are true? 1)An abstract class may not have any
final methods. 2)A final class may not have any abstract methods.|Only statemen
t 2
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.)|Transient variables are
not serialized.
Which of the following statements is true? (Choose one.)|Object references can b
e converted in both method calls and assignments, and the rules governing these
conversions are identical.
Which of the statements below are true? (Choose one.)|Unicode characters are all
16 bits.
Which statements about JDBC are NOT true? (choose 2)|JDBC is a Java database sy
stem., JDBC is a Java API for connecting to any kind of DBMS
Which two code fragments correctly create and initialize a static array of int e
lements? (Choose two.)|static final int[] a = { 100,200 }; static final i
nt[] a; static { a=new int[2]; a[0]=100; a[1]=200; }
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? (Choose two.)|Map Collection
Which of the following is legal import statement?|import java.util.Vector.*.*;
Which of the following code snippets does not compile?|int i = 7; byte b = i;
Which of the following signatures is valid for the main() method entry point of
an application?|public static void main(String arg[])
Which of the following will compile without error (select two)|package MyPackage
; import java.awt.*; class MyClass{}, /*This is a comment */ package
MyPackage; import java.awt.*; class MyClass{}
Which of the following will compile without error |package MyPackage; import j
ava.awt.*; class MyClass{}
Which of the following is an example of a bool-expression?|cause == bYes
Which of the following is an example of a bool-expression?|a==b
Which of the following is illegal statement?|float f=1.01;
When a short is added to a float, what is the type of the result?|float
What is the return type of the instanceof operator?|An boolean
Which of the following statements is true?|Object references can never be conver
ted.
Which of the following statements is true?|A class that has one abstract method
must be abstract class
We can access a static variable through the class name?|True
When you call start() method of a thread, the code inside method run() will run
immediately|False
Which is the last step of four-step approach to help you organize your GUI thin
king?|Choose layout managers.
Which of the following is NOT a swing component? |JText
Which of the following statements is true?|An abstract class may be inherited.
Study the statements: 1)When a JDBC connection is created, it is in auto-commi
t mode 2)Once auto-commit mode is disabled, no SQL statements will be committ
ed until you call the method commit explicitly|Both 1 and 2 are true
is a set of java API for executing SQL statements.|JDBC
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query|WHERE
Select the most correct statement:|If a checked exception may be thrown within t
he body of a method, the method must either catch the exception or declare it in
its throws clause.
All of the numeric wrapper classes in the java.lang package are subclasses of t
he abstract class .|java.lang.Number
Which of the following is invalid wrapper class|java.lang.int
In order for objects in a List to be sorted, those objects must implement which
interface and method?|Comparable interface and its compareTo method.
See picture:|GridBagLayout
One way to approach the daunting number of Swing components is to divide them in
to three categories: Container components Ordinary components Menu componen
ts|True
Which of the following may override a method whose signature is void xyz(float f
)?|public void xyz(float f)
Which of the following is true?|An enum definition may contain the main() method
of an application.
Which of the following is VALID?|Vector <String> theVec = new Vector<String>();
Which of the following statement about inner class is true?|An anonymous inner c
lass may implement at most one interface.
Which of the following class implement java.util.List?|java.util.ArrayList
Which of the following statements are true? (select two)|An inner class may be d
efined as static, An inner class may be defined as static
Which of the following methods of the java.io.File can be used to create a new f
ile?|createNewFile()
Select INCORRECT statement about ServerSocket class.|To make the new object avai
lable for client connections, call its accept() method, which returns an instanc
e of ServerSocket
Which of the following statements are true? (Select two)|TCP provides a point-to
-point channel for applications that require reliable connections. UDP is a
protocol that sends independent packets of data, called datagrams, from one com
puter to another with no guarantee about arrival
Which of the following statements is INCORRECT?|All methods in an abstract class
must be declared as abstract
An abstract class |can contain all concrete methods.

______________ drivers that implement the JDBC API as a mapping to another data
access API, such as ODBC. Drivers of this type are generally dependent on a nati
ve library, which limits their portability.|Type 1
______ method is used to wait for a client to initiate communications|accept()
language and partly in native code. These drivers use a native client library sp
ecific to the data source to which they connect. Again, because of the native co
de, their portability is limited.|Type 2
____________ drivers that are pure Java and implement the network protocol for a
specific data source. The client connects directly to the data source.|Type 4
____________ drivers that use a pure Java client and communicate with a middlewa
re server using a database-independent protocol. The middleware server then comm
unicates the client's requests to the data source.|Type 3
______________ drivers that implement the JDBC API as a mapping to another data
access API, such as ODBC. Drivers of this type are generally dependent on a nati
ve library, which limits their portability.|Type 1
A _____ dialog prevents user input to other windows in the application unitl the
dialog is closed.|Modal
A Java monitor must either extend Thread or implement Runnable.|False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.)|Y
ou cannot specify which thread will get notified
A signed data type has an equal number of non-zero positive and negative values
available.|False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread.|False
A(n) ___ object is used to submit a query to a database|Statement
A(n) ___ object is uses to obtain a Connection to a Database|DriverManager
Consider the following line of code: int[] x = new int[25]; |x[24] is 0
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? (Choose one.)| None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? |java.util.Arrays.equals(a1,
a2);
How can you ensure that multithreaded code does not deadlock? | There is no sing
le technique that can guarantee non-deadlocking code.
How can you force garbage collection of an object? (Choose one.) | Garbage colle
ction cannot be forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? | Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory?| String[] con
tents = myFile.list();
How many locks does an object have? | One
If all three top-level elements occur in a source file, they must appear in whic
h order? | Package declaration, imports, class/interface/enum definitions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any
other instance of Y.| False
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use? (Choose one.)|TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? (Choose one.)| Comparable interface and its compareTo met
hod.
Interface ____ helps manage the connection between a Java program and a database
.| Connection
Is it possible to write code that can execute only if the current thread owns |
Yes
JDBC supports ______ and ______ models. | Two-tier and three-tier
MVC is short call of | Model-View-Controller
Select correct statement about RMI. | All the above
Select correct statement(s) about remote class.(choose one) | All the others cho
ices
Select correct statements about remote interface | All the others choices
Select INCORRECT statement about serialization | When an Object Output Stream s
erializes an object that contains references to another object, every referenced
object is not serialized along with the original object.
Select INCORRECT statement about deserialize | We use readObject() method of Obj
ectOutputStream class to deserialize
Select incorrect statement about RMI server | A client accesses a remote object
by specifying only the server name.
Select incorrect statement about ServerSocket class | To make the new object ava
ilable for client connections, call its accept() method, which returns an instan
ce of ServerSocket
Select incorrect statement about Socket class | The java.net.Socket class contai
ns code that knows how to find and communicate with a server through UDP.
Select the correct statement about JDBC two-tier processing model. | A user's co
mmands are delivered to the database or other data source, and the results of th
ose statements are sent back to the user.
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query | WHERE
Statement objects return SQL query results as ___ objects | ResultSet
Study the statements: 1)When a JDBC connection is created, it is in auto-commit
mode | Both 1 and 2 are true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block. Assuming the JVM doesn t crash | If the JVM
doesn't crash and the code does not execute a System.exit() call, the finally b
lock will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? | Cl
ass loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? | Compilation takes
slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? | C must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? | private
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? | for (float
f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? | When the type of x is Object
Suppose the type of xarr is an array of XXX | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? | if (x == y)
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access mo
de should the readObject() method have? |private
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? | Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one statement is true abou
t this strategy |The strategy fails because you cannot subclass java.lang.Math
Swing components cannot be combined with AWT components.| True
The ______ class is the primary class that has the driver information | DriverMa
nager
The ______ class is used to implement a pull-down menu that provides a number of
items to select from | MenuBar
The element method alters the contents of a Queue. | False
The Swing component classes can be found in the ________________ package. | java
x.swing
There are two classes in Java to enable communication using datagrams namely. |
DataPacket and DataSocket
URL referring to databases use the form | protocol:subprotocol:datasoursename
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? | There is no difference; the rules are the same.
What is the return type of the instanceof operator? | A boolean
What method of the java.io.File class can create a file on the hard drive? | cr
eateNewFile()
When a byte is added to a char, what is the type of the result? | int
When a negative byte is cast to a long, what are the possible values of the resu
lt? | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? | All the above
When a short is added to a float, what is the type of the result? | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? | writing a line separator to the strea
m
When does an exception's stack trace get recorded in the exception object? | Whe
n the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? | When the
exception is being thrown in response to catching of a different exception type
When is it appropriate to write code that constructs and throws an error? | Neve
r
When is x & y an int? | Sometimes
When the user attempts to close the frame window, _______ event in generated | w
indow closing
When the user selects a menu item, _______ event is generated. | Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform-independent code that a
Java Virtual Machine can understand. What is this platform-independent code call
ed?| bytecode
Whenever a method does not want to handle exceptions using the try block, the __
______ is used.| throws
Which class and static method can you use to convert an array to a List? | Arra
ys.asList
Which is four-step approach to help you organize your GUI thinking. | Identify
needed components.Isolate regions of behavior.Sketch the GUI.Choose layout manag
ers.
Which is the four steps are used in working with JDBC? | 1)Connect to the databa
se 2)Create a statement and execute the query 3)Look at the result set 4)Close c
onnection
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed? | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? | sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? | class Man { private Dog bestFriend; }
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? | transient
Which of the following are methods of the java.util.SortedSet interface? | All t
he above
Which of the following are valid arguments to the DataInputStream constructor? |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or? | All the above
Which of the following calls may be made from a non-static synchronized method?
| All the above
Which of the following classes implement java.util.List? | java.util.ArrayList j
ava.util.Stack
Which of the following classes implements a FIFO Queue? |LinkedList
Which of the following interfaces does not allow duplicate objects? | Set
Which of the following is not appropriate situations for assertions? | Precondit
ions of a public method
Which of the following is NOTa valid comment: | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method? | Throw java.lang.IllegalArgumentException
Which of the following is true? | None of the above
Which of the following may appear on the left-hand side of an instanceof operato
r? | A reference
hich of the following may legally appear as the new type (between the parenthese
s) in a cast operation? | All of the others
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? | All of the above
Which of the following may not be synchronized? | Classes
Which of the following methods in the Thread class are deprecated? | suspend() a
nd resume()
Which of the following operations might throw an ArithmeticException? | None of
these
Which of the following operations might throw an ArithmeticException? | /
Which of the following operators can perform promotion on their operands? | =-~
Which of the following restrictions apply to anonymous inner classes? | They mus
t be defined inside a code block.
Which of the following should always be caught? | Checked exceptions
Which of the following statements about the wait() and notify() methods is true?
| The thread that calls wait() goes into the monitor s pool of waiting threads.
Which of the following statements about threads is true? | Threads inherit their
priority from their parent thread.
Which of the following statements are true?1)An abstract class may not have any
final methods.2)A final class may not have any abstract methods.| Only statement
2
Which of the following statements is correct? | Both primitives and object refer
ences can be both converted and cast.
Which of the following statements is true? | Transient variables are not seriali
zed.
Which of the following statements is true? | Object references can be converted
in both method calls and assignments, and the rules governing these conversions
are identical.
Which of the statements below are true? | Unicode characters are all 16 bits.
Which of the statements below are true? | None of the above
Which statements about JDBC are NOT true? | JDBC is a Java database system. and
JDBC is a Java API for connecting to any kind of DBMS
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? | Map and Collection
Which of the following operators might throw an ArithmeticException ? | /
Given arrays a1 and a2 which call returns true if a1 and a2 have the same length
, and a1[i] equais(a2[i]) for every legal index i | Java.util.Array.compare(a1,a
2)
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation ? | All of the others
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances?| Yes
Which of the following statements is true? | Object references can be converted
in both method calls and assignments, and the rules governing these conversions
are identical
What is the range of values that can be assigned to a variable of type byte?| -2
^7 through ^7-1
A signed data type has an equal number of non-zero positive and negative values
available.| False
Which of the following statements is true? | Transient variables are not seriali
zed.
Which of the following statements is correct? | Both primitives and object refer
ences can be both converted and cast.
Which of the following are valid declarations? Assume java.util.* is imported.
|Vector<Map> v;Set<String> ;Map<String, String> m;\
You can determine all the keys in a Map in which of the following ways |By get
ting a Set object from the Map and iterating through it.
What keyword is used to prevent an object from being serialized|D. transien
t
An abstract class can contain methods with declared bodies|true
Select the order of access modifiers from least restrictive to most restrictive|
E. public, protected, default, private
Which access modifier allows you to access method calls in libraries not create
d in Java|A. native
Which of the following statements are true? (Select all that apply|D. A final
object cannot be reassigned a new address in memory
The keyword extends refers to what type of relationship|G. is a
Which of the following keywords is used to invoke a method in the parent clas
s?|super
public class Funcs extends java.lang.Math|C. The code does not compile.
public class Test |D. The code does not compile.
What is the value of x after the following operation is performed x = 23 %
4;|3
Given the following code, what keyword must be used at line 4 in order to stop
execution of the for loop?|C. break
What method call is used to tell a thread that it has the opportunity to run?
|B. notify()
interface Box |A. The code will not compile because of line 4.
Assertions are used to enforce all but which of the following|C. Exceptio
ns
The developer can force garbage collection by calling System.gc().|false
Select the valid primitive data types. (Select all that apply.)|boolean char flo
at
How many bits does a float contain|32
What is the value of x after the following line is executed? x = 32 * (31 -
10 * 3);|32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe
|true
Select the list of primitives ordered in smallest to largest bit size represent
ation|D. char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion?|D. java.text.DateFormat
The following line of code is valid. int x = 9; byte b = x;|false
Which of the following code snippets compile|Integer i = 7; Integer i = new In
teger(5); int j = i;byte b = 7;
public class StringTest |D. same will be printed out to the console.
Java arrays always start at index 1|false
which of the following statements accurately describes how variables are passe
d to method|C. Arguments that are primitive type are passed by value.
How do you change the value that is encapsulated by a wrapper class after you
have instan- tiated it|D. None of the above
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method s
hould imple- ment the custom deserialization, and what is its access mode?|A.
private readObject
A signed data type has an equal number of non-zero positive and negative value
s available.|fasle
Choose the valid identifiers from those listed here. (Choose all that apply |Big
OlLongStringWithMeaninglessName - $int - bytes - $1 - finalist
Which of the following signatures are valid for the main() method entry point of
an application?(Choose all that apply.) |public static void main(String arg[])
- public static void main(String[] args)
If all three top-level elements occur in a source file, they must appear in whi
ch order?|D. Package declaration, imports, class/interface/enum definitions.
Consider the following line of code:int[] x = new int[25]; After execution, w
hich statements are true? (Choose all that apply.)|A. x[24] is 0 - E. x.length
is 25
class Q6 |101
class Q7 |12.3
How can you force garbage collection of an object|A. Garbage collection cann
ot be forced
What is the range of values that can be assigned to a variable of type short?|-2
15 through 215 - 1
What is the range of values that can be assigned to a variable of type byte|-27
through 27 - 1
Suppose a source file contains a large number of import statements. How do the
imports affect the time required to compile the source file?|B. Compilat
ion takes slightly more time.
Suppose a source file contains a large number of import statements and one cl
ass definition. How do the imports affect the time required to load the class?
|A. Class loading takes no additional time.
Which of the following are legal import statements|import java.util.Vector - im
port static java.util.Vector.*;
Which of the following may be statically imported? (Choose all that apply.)|Stat
ic method names-Static field names
public class Q15 |C. The code compiles, and prints out >>null<<
The code compiles, and prints out >>null<<|C. int c = 0xabcd- C. int c =
0xabcd
Which of the following are legal? (Choose all that apply.) |A. double d = 1.2
d; - B. double d = 1.2D;
Which of the following are legal?|A. char c = \u1234 ;
Consider the following code: StringBuffer sbuf = new StringBuffer(); sbuf = nu
ll; System.gc();|C. After line 2 executes, the StringBuffer object is eligib
le for garbage collection.
Which of the following are true? (Choose all that apply.)|B. Primitives are p
assed by value. - D. References are passed by value.
After execution of the following code fragment, what are the values of the var
iables x, a, and b? int x, a = 6, b = 7; x = a++ + b++; |C. x = 13, a = 7, b
= 8
Which of the following expressions are legal? (Choose all that apply.)|B.
int x = 6; if (!(x > 3)) {} - C. int x = 6; x = ~x;
Which of the following expressions results in a positive value in x? |A.
int x = 1; x = x >>> 5;
Which of the following expressions are legal? (Choose all that apply.)|tring x
= "Hello"; int y = 9; x += y; - C. String x = "Hello"; int y = 9; x =
x + y;
What is -8 % 5? | -3
What is 7 % -4? | 3
public class Xor |B. The output: b contains 5
public class Conditional |C. The output: value is 9.0
What does the following code do? Integer i = null; if (i != null & i.int
Value() == 5) System.out.println( Value is 5 ); |B. Throws an exception
Is it possible to define a class called Thing so that the following method can
return true under certain circumstances? boolean weird(Thing s) { Integer x
= new Integer(5); return s.equals(x); } |yes
Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 =
= ob2) is false, can ob1.equals(ob2) ever be true? |no
When a byte is added to a char, what is the type of the result? |int
When a short is added to a float, what is the type of the result? |float
Which statement is true about the following method? int selfXor(int i) { retur
n i ^ i;} |A. It always returns 0.
Which of the following operations might throw an ArithmeticException? |D.
None of these
Which of the following operations might throw an ArithmeticException? | /
Which of the following operations might throw an ArithmeticException? | a boole
an
Which of the following may appear on the left-hand side of an instanceof opera
tor? |A. A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose all that apply.)|B. A class -C. An interface
What is -50 >> 1? | -25
Which of the following declarations are illegal? (Choose all that apply.)|A.
default String s; - D. abstract double d; - D. abstract double d;
Which of the following statements is true? | B. A final class may not ha
ve any abstract methods.
final class Aaa| A. On line 1, remove the final modifier.
Which of the following statements is true? |E. Transient variables are not seri
alized.
class StaticStuff |E. The code compiles and execution produces the output x
= 3.
class HasStatic |E. The program compiles and the output is x = 104.
class SuperDuper |D. line 3: private; line 8: protected
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class s persistent state? (Choose the shortest pos
sible answer.) |D. transient
public class Bird |C. Compilation of Parrot.java fails at line 7 because metho
d getRefCount() is static in the superclass, and static methods may not be ove
rridden to be nonstatic.
class Nightingale extends abcde.Bird |A. The program will compile and exe
cute. The output will be Before: 0 After: 2.
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access mod
es may Subby s version of the method have? (Choose all that apply.) |public - pr
otected
Which of the following statements are true |F. None of the above
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five int
erface methods. Which is/are true?|The class will compile if it is declared abst
ract.- The class may not be instantiated.
Which of the following may be declared final? (Choose all that apply.) |Classes
- Data - Methods
Which of the following may follow the static keyword? (Choose all that apply.)
|Data - Methods - Code blocks enclosed in curly brackets
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may apply to
B s version of doSomething()? (Choose all that apply.) |public - protected - Defa
ult
True or false: If class Y extends class X, the two classes are in different pack
ages, and class X has a protected method called abby(), then any instance of Y
may call the abby() method of any other instance of Y. | false
Which of the following statements are true? |D. A final class may not be
extended.
Which of the following statements are true | D. A final class may not be
extended.
public class A | -1
Which of the following statements is correct? (Choose one.) |Both primitives an
d object references can be both converted and cast.
Which one line in the following code will not compile? |F. Line 6
Will the following code compile? ||E. int, long, float, double
class Cruncher | D. The code will compile and produce the following output:
int version
Which of the following statements is true? (Choose one |D. Object reference
s can be converted in both method calls and assignments, and the rules govern
ing these conversions are identical.
Consider the following code. Which line will not compile? |C. Line 6
Consider the following code |The code will compile and run.
Cat sunflower |The code will compile but will throw an exception at line 7, b
ecause the runtime class of wawa cannot be converted to type SwampThing.
Raccoon rocky; |Line 7 will not compile; an explicit cast is required to conv
ert a Washer to a SwampThing
Which of the following may legally appear as the new type (between the parenthe
ses) in a cast operation | All of the above
Which of the following may legally appear as the new type (between the parenthe
ses) in a cast operation? | D. All of the above
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? |A. When the type of x is Ob
ject
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? |A. Sometimes
When is x & y an int? (Choose one). | sometimes
What are the legal types for whatsMyType? short s = 10; whatsMyType = !s; | C.
There are no possible legal types
When a negative long is cast to a byte, what are the possible values of the resu
lt |D. All of the above
When a negative byte is cast to a long, what are the possible values of the resu
lt? | Negative
Which of the following operators can perform promotion on their operands? (Choo
se all that apply.) | + - ~
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? | A. There is no difference; the rules are th
e same
for (int i = 0; i < 2; i++) | i = 0 j = 1 - i = 0 j = 2 - i = 1 j = 0
- i = 1 j = 2
outer: for (int i = 0; i < 2; i++) | outer: for (int i = 0; i < 2; i++)
Which of the following are legal loop constructions? (Choose all that apply.) |
int j = 0; for (int k=0, j+k != 10; j++,k++) { System.out.println("j=" +
j + ", k=" + k); }
What would be the output from this code fragment | message four
int j = 2; | D. The output would be the text value is two followed by the text v
alue is three.
What lines are output if the method at line 5 throws an OutOfMemoryError? (Choos
e all that apply.) |E. Doing finally part
Which of the following are appropriate situations for assertions |Postconditions
of a public method - Preconditions of a private method - Postconditions of a pr
ivate method
Which of the following is the most appropriate way to handle invalid arguments
in a public method? | B. Throw java.lang.IllegalArgumentException.
Suppose salaries is an array containing floats. Which of the following are vali
d loop control statements for processing each element of salaries? - for (float
f:salaries)
Which of the following are legal? (Choose all that apply.)|for (int i=0, j=1; i
<10; i++, j++) - for (int i=0, j=1;; i++, j++) - for (String s = ; s.length()<10
; s += ! )
Suppose a method called finallyTest() consists of a try block, followed by a ca
tch block, followed by a finally block. Assuming the JVM doesn t crash and the cod
e does not execute a System.exit() call, under what circumstances will the fina
lly block not begin to execute? - D. If the JVM doesn t crash and the code does
not execute a System.exit() call, the finally block will always execute.
Which of the following are legal loop definitions? (Choose all that apply.) | N
one of them are legal.
Which of the following are legal argument types for a switch statement? | byte-
int - char
When is it appropriate to pass a cause to an exception s constructor | B. When the
exception is being thrown in response to catching of a different exception ty
pe
Which of the following should always be caught? | B. Checked exceptions
When does an exception s stack trace get recorded in the exception object? | A.
When the exception is constructed
When is it appropriate to write code that constructs and throws an error? |neve
r
public class Test1 | public int aMethod(int a, int b) { } - public float
aMethod(float a, float b, int c) throws Exception { }- private float aMethod(i
nt a, int b, int c) { }
public class Test1 |public int aMethod(int a, int b) throws Exception {...}
- public float aMethod(float p, float q) {...}
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual de
scription of its markings. | boolean neutered - String markings
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating if it has been neutered, and a textual descript
ion of its markings | public class Cat extends Pet
public class Base | Value is 5This value is 6
public class Test extends Base | Test t = new Test(1); Test t = new Test(1, 2
);
public class Test extends Base |Base() { } - Base(int j, int k) { }
public class Outer | a- b - c -e
Which of the following statements are true? (Choose all that apply.)|Given that
Inner is a nonstatic class declared inside a public class Outer and that appro-
priate constructor forms are defined, an instance of Inner can be constructed l
ike this: new Outer().new Inner()
Which of the following are legal enums | enum Animals {LION, TIGER, BEAR; int
weight;} - enum Animals {LION(450), TIGER(450), BEAR; int weight;Animals() { }
Animals(int w) {weight = w;}}
Which of the following may override a method whose signature is void xyz(float
f)? |void xyz(float f) - public void xyz(float f)
Which of the following are true? (Choose all that apply.) |An enum may contain
public method definitions. - An enum may contain private data.
Which of the following are true? (Choose all that apply.) |An enum definition m
ay contain the main() method of an application. - You can call an enum s toStrin
g() method. - You can call an enum s wait() method. - You can call an enum s notify(
) method.
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant | A. if (x == y)
Which of the following restrictions apply to anonymous inner classes? | They mus
t be defined inside a code block.
Given the following code, which of the following will not compile? enum Spice {
NUTMEG, CINNAMON, CORIANDER, ROSEMARY; } |String ob = new String(); Spice
sp = ob;
Which of the following are true |An anonymous inner class may implement at most
one interface. - An anonymous inner class may extend a parent class other than
Object
Which methods return an enum constant s name | name() - toString()
Suppose class X contains the following method: void doSomething(int a, float b)
{ } Which of the following methods may appear in class Y, which extends
X?|public void doSomething(int a, float b) { }
This question involves IOException, AWTException, and EOFException. They are al
l checked exception types. IOException and AWTException extend Exception, and EO
FException extends IOException. Suppose class X contains the following method:
void doSomething() throws IOException{ }|void doSomething() { } - void
doSomething() throws EOFException { } - void doSomething() throws IOExce
ption, EOFException { }
class Greebo extends java.util.Vector |There will be a compiler error, becaus
e class Greebo does not correctly implement the Runnable interface.
class HiPri extends Thread |C. When the application is run, all three threads (
hp1, hp2, and hp3) will execute concurrently, taking time-sliced turns in the CP
U.
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread. | false
A thread s run() method includes the following lines: | D. At line 2, the t
hread will stop running. It will resume running some time after 100 milliseconds
have elapsed.
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1
so that it alone moves from the Waiting state to the Ready state? |E. You cann
ot specify which thread will get notified.
class TestThread3 extends Thread |yes
A Java monitor must either extend Thread or implement Runnable.|fasle
Which of the following methods in the Thread class are deprecated|A. suspend(
) and resume()
Which of the following statements about threads is true?|B. Threads inherit
their priority from their parent thread.
Threads inherit their priority from their parent thread.|C. The thread that
calls wait() goes into the monitor s pool of waiting threads.
The thread that calls wait() goes into the monitor s pool of waiting threads. |c
lasses
Which of the following calls may be made from a non-static synchronized method?
| all
How many locks does an object have?|One
is it possible to write code that can execute only if the current thread owns
multiple locks?|yes
Which of the following are true? (Choose all that apply.) |there is one non-daem
on thread - A thread created by a daemon thread - A thread created by a non-
daemon thread
Which of the following are true? |D. The JVM runs until there are no non-daem
on threads.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? |D. Access the variables only via synchronized methods.
How can you ensure that multithreaded code does not deadlock|A, B, and C do not
ensure that multithreaded code does not deadlock.
Which of the following are true? (Choose all that apply |When you declare a meth
od to be synchronized, the method - When you declare a block of code inside a me
thod to be synchronized, you can
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do? |Override run().
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string? | none of the above
String s1 = abc + def ; | Line 6 executes and line 4 does not.
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide t
he new functionality as a set of static methods. Which one statement is true ab
out this strategy | D. The strategy fails because you cannot subclass java.lan
g.Math
import java.lang.Math; | Compilation fails at line 2.
String s = abcde ; | Compilation succeeds. No exception is thrown during execution
.
StringBuffer sbuf = new StringBuffer( abcde );|true
String s1 = xyz ; String s2 = xyz ;| true
String s1 = xyz ; String s2 = new String(s1);| false
Suppose prim is an int and wrapped is an Integer. Which of the following are le
gal Java statements? (Choose all that apply.) |prim = wrapped; - wrapped =
prim; - prim = new Integer(9); - wrapped = 9;
Which of the following are legal? (Choose all that apply.) |List<String> theList
= new Vector<String>(); - Vector <String> theVec = new Vector<String>();
Map<String> names = new HashMap<String>(); | Iterator<String> iter = names.ite
rator(); - for (String s:names)
Which of the following are legal clone() methods in a class called Q13 that ext
ends Object |public Object clone() throws CloneNotSupportedException { return s
uper.clone(); } - D. public Q13 clone() throws CloneNotSupportedException {
return (Q13)super.clone(); }
Which of the following classes implement java.util.List |java.util.ArrayList -
java.util.Stack
Which of the following are methods of the java.util.SortedSet interface?|first
- last - headSet - tailSet - subSet
Which of the following are methods of the java.util.SortedMap interface?|headMa
p- tailMap - subMap
Which line of code tells a scanner called sc to use a single digit as a delimite
r?|sc.useDelimiter( \\d );
public class Apple |C. An exception is thrown at line 7.
Given arrays a1 and a2, which call returns true if a1 and a2 have the same leng
th, and a1[i].equals(a2[i]) for every legal index i?|A. java.util.Arrays.equals(
a1, a2);
Which of the following statements are true?|A. StringBuilder is generally faste
r than StringBuffer. - StringBuilder is generally faster than StringBuffer.
Which of the statements below are true? (Choose all that apply | D. Unicode
characters are all 16 bits.
Which of the statements below are true? (Choose all that apply.)|D. None of
the above.
How do you use the File class to list the contents of a directory? |A. String[]
contents = myFile.list();
How many bytes does the following code write to file dest? |12
FileOutputStream fos = new FileOutputStream( xx ); | B. The output is i = 20.
FileOutputStream fos = new FileOutputStream( datafile ); |Construct a FileInputStrea
m - Construct a RandomAccessFile,
Which of the following is true about Readers have methods that can read ? |None
of the above
File f1 = new File( dirname ); | E. No directory is created, and no file is create
d.
Assume that the code fragment is part of an application that has write permissio
n in the current working directory. Also assume that before execution, the cur
rent working directory does not contain a file called datafile. | A.
The code fails to compile
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have? |private
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access m
ode should the readObject() method have? | private
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C
? |B. B must have a no-args constructor.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? | C. C must have a no-args constructor.
public class Xyz implements java.io.Serializable |iAmPublic - iAmPrivate - iAmVo
latile
What method of the java.io.File class can create a file on the hard drive |crea
teNewFile()
public class Xxx |B. An exception is thrown at line 9.
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose all that apply.) | r - rw - rws - rwd
Which of the following are valid arguments to the DataInputStream constructor?
| C. FileInputStream
public enum Wallpaper |Wallpaper wp = Wallpaper.BLUE; - void aMethod(Wallpaper
wp) { System.out.println(wp);} - int hcode = Wallpaper.BLUE.hashCode();
class Sploo | b - d - fff()
public abstract class Abby |SubAbby generates a compiler error. - If SubAbby wer
e declared abstract, it would compile without error. - Abby is a legal type for
variables.
class Xxx | heights is initialized to a reference to an array with zero elements
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards? | public Color g
etTheTint()
Which of the following statements are true regarding the following method? voi
d callMe(String names) { } | Within the method, names is an array containing
Strings.
public class Food |Fruit - Citrus - Pomelo
class A extends java.util.Vector |The compiler does not create a default const
ructor.
Which of the following types are legal arguments of a switch statement | enums
- bytes
int[] ages = { 9, 41, 49 }; int sum = 0; |for (int i=0; i<ages.length; i++)
sum += ages[i]; - for (int i:ages) sum += i;
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime. | assert x == 4; - assert x == 4 : x is not 4 ;
Which are appropriate uses of assertions |Checking preconditions in a private me
thod - Checking postconditions in a private method - Checking postconditions in
a public method
void callMe() throws ObjectStreamException | void callMe() - void callMe() thro
ws NotSerializableException
NotSerializableException extends ObjectStreamException. AWTException does not ex
tend any of these. All are checked exceptions. The callMe() method throws Not
SerializableException| Object Stream - Finally
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction? | none of the
above
How is IllegalArgumentException used? (Choose all correct options.) | It is thro
wn by certain methods - It should be used by programmers to indicate that precon
ditions of public
Suppose shorty is a short and wrapped is a Short. Which of the following are leg
al Java state- ments? (Choose all correct options.)| shorty = wrapped; - wrappe
d = shorty; - shorty = new Short((short)9); - shorty = 9;
Which of the following statements are true? (Choose all correct options.) | Str
ingBuilder encapsulates a mutable string. - StringBuffer is threadsafe.
The file contains lines of 8-bit text, and the 8-bit encoding represents the lo
cal character set, as represented by the cur- rent default locale | C. Create a
FileReader instance. Pass it into the constructor of LineNumberReader. Use Lin
eNumberReader s readLine() method.
What interfaces can be implemented in order to create a class that can be serial
ized? (Choose all that apply.) | java.io.Serializable. There are no methods - ja
va.io.Externalizable, which defines two methods: readExternal
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access m
ode should the readObject() method have? | private
Suppose you want to create a class that compiles and can be serialized and deser
ialized without causing an exception to be thrown. Which statements are true r
egarding the class? (Choose all correct options.) | java.io.Externalizable, it
must have a no-args - java.io.Serializable and does not implement
Suppose you want to use a DateFormat to format an instance of Date. What facto
rs influence the string returned by DateFormat s format() method? |The style, whic
h is one of SHORT, MEDIUM, LONG, or FULL - The locale
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc? | NumberFormat nf = NumberFormat.getInstance(loc)
;
String scanMe = aeiou9876543210AEIOU ; | String delim = \\d+ ;
Which line prints double d in a left-justified field that is 20 characters wide,
with 15 characters to the right of the decimal point? | System.out.format("%-20
.15f", d);
Suppose MyThread extends java.lang.Thread, and MyRunnable implements java.lang.
Runnable (but does not extend Thread). Both classes have no-args constructors. W
hich of the following cause a thread in the JVM to begin execution? (Choose al
l correct options.)|(new MyThread()).start(); - (new Thread(new MyRunnable()))
(new Thread(new MyRunnable())) | The code prints Going to sleep, then Waking up,
and then All done.
Suppose threads aThread and bThread are both accessing a shared object named sh
aredOb, and aThread has just executed: sharedOb.wait(); |aThread.interrupt(); -
sharedOb.notifyAll();
Suppose class Home has methods chopWood() and carryWater(); it also has a metho
d called chopWoodAndCarryWater(), which just calls the other two methods. Whic
h statements are true? (Choose all that apply.) | chopWoodAndCarryWater() is an
example of inappropriate cohesion. - chopWoodAndCarryWater() is an example of i
nappropriate coupling.
Lemon lem = new Lemon(); Citrus cit = new Citrus(); |cit = lem; - lem = (Lem
on)cit; - cit = (Citrus)lem;
Grapefruit g = new Grapefruit(); | The cast in line 2 is not necessary. - The c
ast in line 2 is not necessary.
Suppose class aaa.Aaa has a method called callMe(). Suppose class bbb.Bbb, which
extends aaa.AAA, wants to override callMe(). Which access modes for callMe() i
n aaa.AAA will allow this? |public - protected
class Animal | B. Class Zebra generates a compiler error
class Xyz | super(); - this(1.23f);
What relationship does the extends keyword represent? | is a
When should objects stored in a Set implement the java.util.Comparable interfac
e | D. When the Set is a TreeSet
class Xyzzy |public int hashCode() { return a; } - public int hashCode()
{ return (int)Math.random();}
plainVec; Vector<String> fancyVec; |Attempting to add anything other than a st
ring to fancyVec results in a compiler error.
The declaration of the java.util.Collection interface is interface Collection <
E> |D. public boolean addAll(Collection<? extends E> c)
package ocean; public class Fish |B. public void swim() { } - size = 12;
public class App | 4
public class Wrapper | C. n is 10, w.x is 11
String s = aaa ; | A. After line 3
java -classpath somewhere;elsewhere aaa.bbb.MyApplication|Class MyApplication m
ust contain the statement package aaa.bbb;. - D. The file MyApplication.c
lass must be found either in somewhere\aaa\bbb or in elsewhere\aaa\bbb. (Substit
ute forward slashes for backslashes on a Unix system
What is -15 % -10? | -5
is a set of java API for executing SQL statements.| JDBC
method is used to wait for a client to initiate communications.|accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect. Again, because of the native code, their portability is
limited.|type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source.|type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source. |type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally |type 1
public class A |Line 26 prints a to System.out.
public class A |The code on line 29 will be executed. - The exception will be pr
opagated back to line 27.
try { |Bad URL - Doing finally part - Carrying on
interface Foo |The code compiles and the output is 2. - If lines 16, 17 and 18 w
ere removed, the code would compile and the output would be 2. - If lines 24, 25
and 26 were removed, the code would compile and the output would be 1.
public class ClassA |An exception is thrown at runtime
public class Bootchy |third second first snootchy 420
A dialog prevents user input to other windows in the application unitl th
e dialog is closed. |modal
A Java monitor must either extend Thread or implement Runnable. | false
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.) |
You cannot specify which thread will get notified.
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these | public void logIt(Strin
g... msgs)
A signed data type has an equal number of non-zero positive and negative values
available.|false
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread.|false
try { |At line 2, the thread will stop running. It will resume running some time
after 100 milliseconds have elapsed
A(n) object is used to submit a query to a database |statement
A(n) object is uses to obtain a Connection to a Database |Drivermanager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b? 1. int x, a = 6, b = 7; 2. x = a++ + b++;|x = 13, a = 7, b = 8
public class Money |Euro returns correct Country value. - Compilation fails beca
use of an error at line 25
public class SomeException |Compilation of class B will fail. Compilation of cla
ss A will succeed
public class TestException extends Exception |Line 46 will compile if the enclos
ing - Line 46 will compile if enclosed.
class Q6 |101
class Q7 |12.3
public class Test extends Base |Test t = new Test(1); - Test t = new Test(1, 2);
public class Test extends Base |Base() { } - Base(int j, int k) { }
class Cruncher |The code will compile and produce the following output: int vers
ion
Object ob = new Object(); |line 6
public class Assertification |The application must be - The args array must have
one or more elements.
StringBuffer sbuf = new StringBuffer();|After line 2 executes, the StringBuffer
object is eligible for garbage collection.
Cat sunflower;|The code will compile but will throw an exception at line 7, beca
use the runtime class of wawa cannot be converted to type SwampThing.
Select correct statement(s) about remote class.(choose one)|All the others choic
es
Select correct statements about remote interface. (choose 1)|All the others choi
ces
Select INCORRECT statement about serialization. (choose 1|When an Object Output
Stream serializes an object that contains references to another object, every r
eferenced object is not serialized along with the original object
Select INCORRECT statement about deserialize. (choose 1)|We use readObject() met
hod of ObjectOutputStream class to deserialize.
Select incorrect statement about RMI server.(choose 1)|A client accesses a remot
e object by specifying only the server name
Select incorrect statement about ServerSocket class. (choose 1)|To make the new
object available for client connections, call its accept() method, which returns
an instance of ServerSocket
Select incorrect statement about Socket class. (choose 1) |The java.net.Socket c
lass contains code that knows how to find and communicate with a server through
UDP.
Select the correct statement about JDBC two-tier processing model|A user's comma
nds are delivered to the database or other data source, and the results of those
statements are sent back to the user.
SQL keyword is followed by the selection criteria that specify the rows to
select in a query |Where
Statement objects return SQL query results as objects|ResultSet
When a JDBC connection is created, it is in auto-commit mode 2)Once auto-commit
mode is disabled, no SQL statements will be committed until you call the method
commit explicitly|Both 1 and 2 are true Suppose a method called finallyTest() co
nsists of a try block, followed by a catch block, followed by a finally block. A
ssuming the JVM doesn t crash and the code does not execute a System.exit() call,
under what circumstances will the finally block not begin to execute?|If the JVM
doesn't crash and the code does not execute a System.exit() call,the finally bl
ock will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? (Cho
ose one.)|Class loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? (Choose one.|Suppose
a source file contains a large number of import statements. How do the imports
affect the time required to compile the source file? (Choose one.)
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? (Choose one.)|C must have a no-args constructor.
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C?
(Choose one.)|B must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? (Choose one)|private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby s version of the method have? (Choose two.)|public - protected
Suppose class X contains the following method: void doSomething(int a, float b)
{ } Which of the following methods may appear in class Y, which extends X? (Choo
se one.)|public void doSomething(int a, float b) { }
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods. Which are true? (Choose two.)|The class will compile if it is dec
lared abstract. The class may not be instantiated.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.)|All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? (Choose one.)|
for (float f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? (Choose one.)|When the type of x is
Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? (Choose one.)|Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.)|if (x ==
y)
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access mo
de should the readObject() method have? (Choose one.)|private
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have? (Choose one.)|private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? (Choose one.)|Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one|The strategy fails bec
ause you cannot add static methods to a subclass.
Swing components cannot be combined with AWT components.|true
The class is the primary class that has the driver information.|DriverManag
er
The class is used to implement a pull-down menu that provides a number of i
tems to select from.|menu
The element method alters the contents of a Queue.|false
The Swing component classes can be found in the package.|javax.swing
There are two classes in Java to enable communication using datagrams namely.|Da
taPacket and DataSocket
public class Bird|Compilation of Parrot.java fails at line 7 because method getR
efCount() is static in the superclass, and static methods may not be overridden
to be nonstatic.
public class Bird |The program will compile and execute. The output will be Befo
re: 0 After: 2.
URL referring to databases use the form:|protocol:subprotocol:datasoursename
What are the legal types for whatsMyType? (Choose one.) short s = 10;whatsMyType
= !s;|There are no possible legal types.
What does the following code do? Integer i = null; if (i != null & i.intValue()
== 5) System.out.println("Value is 5");|Throws an exception.
FileOutputStream fos = new FileOutputStream("xx");|The output is i = 20.
public class A|-1
public class Xxx |An exception is thrown at line 9.
public class Q |The code compiles, and prints out >>null<<
public class Apple|An exception is thrown at line 7.
What is -50 >> 2 | -13
What is 7 % -4?|3
What is -8 % 5?|-3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? (Choose one.)|There is no difference; the rules are
the same.
final class Aaa|On line 1, remove the final modifier. |On line 1, remove the f
inal modifier.
What is the range of values that can be assigned to a variable of type byte? (Ch
oose one.)|-2^7 through 2^7 - 1
What is the range of values that can be assigned to a variable of type short? (C
hoose one.)|-2^15 through 2^15 - 1
What is the result of attempting to compile and execute the following code fragm
ent? Assume that the code fragment is part of an application that has write perm
ission in the current working directory. Also assume that before execution, the
current working directory does not contain a file called datafile. (Choose one.)
|The code fails to compile.
The code fails to compile.|A boolean
What method of the java.io.File class can create a file on the hard drive? (Choo
se one.)|createNewFile()
public class Conditional |The output: value is 9.0
public class Xor |The output: b contains 5.
int x = 0, y = 4, z = 5;|message four
When a byte is added to a char, what is the type of the result|int
When a negative byte is cast to a long, what are the possible values of the resu
lt? (Choose one.)|Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? (Choose one.)|All the above
When a short is added to a float, what is the type of the result?|float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? (Choose one.)|writing a line separator
to the stream
When does an exception's stack trace get recorded in the exception object?(Choos
e one.)|When the exception is constructed
When is it appropriate to pass a cause to an exception's constructor?(Choose one
.)|When the exception is being thrown in response to catching of a different exc
eption type
When is it appropriate to write code that constructs and throws an error? (Choos
e one.)|never
When is x & y an int? (Choose one).|Sometimes
When the user attempts to close the frame window, event in generated.|win
dow closing
When the user selects a menu item, event is generated.|Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform- independent code that a
Java Virtual Machine can understand. What is this platform-independent code cal
led?|bytecode
Whenever a method does not want to handle exceptions using the try block, the
is used.|throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database?|String url ="jdbc:odbc:data_source_name"; Connection con
= DriverManager.getConnection (url, user", "password");
Which class and static method can you use to convert an array to a List? (Choose
one.)|Arrays.asList
Which is four-step approach to help you organize your GUI thinking. (Choose one.
)|Identify needed components. Isolate regions of behavior. Sketch the GUI. Choos
e layout managers.
Which is the four steps are used in working with JDBC?|1)Connect to the database
2)Create a statement and execute the query 3)Look at the result set 4)Close con
nection
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed?|two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? (Choose one.)|sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? (Choose one.)|class Man { private Dog bestFriend; }
Which methods return an enum constant s name? (Choose two.)|name() Which modifier
or modifiers should be used to denote a variable that should not be written out
as part of its class's persistent state? (Choose the shortest possible answer.)
toString()|transient
Which of the following are legal argument types for a switch statement? (Choose
three.)|byte - int - char
Which of the following are legal import statements? (Choose two.)|import java.ut
il.Vector; - import static java.util.Vector.*;
Which of the following are legal loop constructions? (Choose one.)|int j = 0; fo
r (int k=0, j+k != 10; j++,k++) { System.out.println("j=" + j + ", k=" + k); }
Which of the following are legal loop definitions? (Choose one.)|None of the abo
ve.
Which of the following are legal? (Choose three.)|for (int i=0, j=1; i<10; i++,
j++) - for (int i=0, j=1;; i++, j++) - for (String s = ""; s.length()<10; s += '
!')
Which of the following are legal? (Choose two.)|double d = 1.2d; double d = 1.2D
;
Which of the following are legal? (Choose two.)|int c = 0xabcd; int d = 0XABCD;
Which of the following are legal? (Choose two.)|char c = 0x1234; - char c = '\u1
234';
Which of the following are legal? (Choose two.)|List<String> theList = new Vecto
r<String>(); - List<String> theList = new Vector<String>();
Which of the following are methods of the java.util.SortedMap interface? (Choose
three.)|headMap - tailMap - subMap
Which of the following are methods of the java.util.SortedSet interface? (Choose
one.)|All the above
Which of the following are true? (Choose one.)|All the above
Which of the following are true? (Choose one.)|The JVM runs until there are no n
on-daemon threads.
Which of the following are true? (Choose two.)|When you declare a method to be s
ynchronized, the method - to be synchronized, you can specify the
Which of the following are true? (Choose two.)|An enum may contain public method
definitions. - An enum may contain private data.
Which of the following are true? (Choose two.)|Primitives are passed by value. -
References are passed by value.
Which of the following are true? (Choose two.)|An anonymous inner class may impl
ement at most one interface. - An anonymous inner class may extend a parent clas
s other than Object.
Which of the following are valid arguments to the DataInputStream constructor? (
Choose one.)|FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose one.)|All the above
Which of the following calls may be made from a non-static synchronized method?
(Choose one.)|All the above
Which of the following classes implement java.util.List? (Choose two.)|java.util
.ArrayList - java.util.Stack
Which of the following classes implements a FIFO Queue? (Choose one.)|LinkedLis
t
Which of the following declarations are illegal? (Choose three.)|default String
s; - abstract double d; - abstract final double hyperbolicCosine();
Which of the following expressions are legal? (Choose two.) | int x = 6; if (!(x
> 3)) {} - int x = 6; x = ~x;
Which of the following expressions are legal? (Choose two.) | String x = "Hello"
; int y = 9; x += y; - String x = "Hello"; int y = 9; x = x + y;
Which of the following expressions results in a positive value in x? (Choose one
.)|int x = 1; x = x >>> 5;
Which of the following interfaces does not allow duplicate objects? (Choose one.
) |set
Which of the following interfaces does not allow duplicate objects? (Choose one.
)|Preconditions of a public method
Which of the following is NOTa valid comment:|/* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method?|Throw java.lang.IllegalArgumentException.
Which of the following is true? (Choose one.) | None of the above
Which of the following is(are) true? (Choose one.) |All the above
Which of the following may appear on the left-hand side of an instance of operat
or?|A reference
Which of the following may appear on the right-hand side of an instance of opera
tor? (Choose two.)|A class - An interface
Which of the following may be declared final? (Choose two.) | Classes - Methods
Which of the following may be statically imported? (Choose two.)|Static method n
ames - Static field names
Which of the following may follow the static keyword? (Choose three.) | Data - M
ethods - Code blocks enclosed in curly brackets
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.) |All of the others
Which of the following may not be synchronized? (Choose one.) | Classes
Which of the following may override a method whose signature is void xyz(float f
)? (Choose two.)|void xyz(float f) - public void xyz(float f)
Which of the following methods in the Thread class are deprecated? (Choose one.)
| suspend() and resume()
Which of the following operations might throw an ArithmeticException? (Choose on
e.) | None of these
Which of the following operations might throw an ArithmeticException? (Choose on
e.) | /
Which of the following operators can perform promotion on their operands? (Choos
e three.)|+ - ~
Which of the following restrictions apply to anonymous inner classes? (Choose on
e.)|They must be defined inside a code block.
Which of the following should always be caught? (Choose one.)|Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application? (Choose two.)|public static void main(String arg[]) - public st
atic void main(String[] args)
Which of the following statements about the wait() and notify() methods is true?
(Choose one.)|The thread that calls wait() goes into the monitor s pool of waitin
g threads.
Which of the following statements about threads is true? (Choose one.) |Threads
inherit their priority from their parent thread.
Which of the following statements are true? (Choose one.)|A final class may not
be extended
Which of the following statements are true? (Choose one.)|Given that Inner is a
nonstatic class declared inside a public class Outer and that appropriate constr
uctor forms are defined, an instance of Inner can be constructed like this: new
Outer().new Inner()
Which of the following statements are true? (Choose one.) | None of the above
Which of the following statements are true? (Choose two.)|StringBuilder is gener
ally faster than StringBuffer. - StringBuffer is threadsafe; StringBuilder is no
t.
Which of the following statements are true? 1)An abstract class may not have any
final methods. 2)A final class may not have any abstract methods.|Only statemen
t 2
Which of the following statements is correct? (Choose one.) |Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.) |Transient variables ar
e not serialized.
Which of the following statements is true? (Choose one.) |Object references can
be converted in both method calls and assignments, and the rules governing these
conversions are identical.
Which of the statements below are true? (Choose one.)|Unicode characters are all
16 bits.
Which of the statements below are true? (Choose one.)|None of the above
byte b = 5; 2. char c = 5 ;|line 6
class HiPri extends Thread |None of the above scenarios can be guaranteed to hap
pen in all cases.
import java.lang.Math;|Compilation fails at line 2.
String s = "FPT";|Compilation succeeds. No exception is thrown during execution.
String s1 = "abc" + "def";|Line 6 executes and line 4 does not.
class Greebo extends java.util.Vector implements Runnable |There will be a comp
iler error, because class Greebo does not correctly implement the Runnable inter
face.
int j = 2;|The output would be the text value is two followed by the text value
is three.
Which statement is true about the following method? int selfXor(int i) { return
i ^ i; }|It always returns 0.
class StaticStuff|The code compiles and execution produces the output x = 3.
class HasStatic|The program compiles and the output is x = 104.
Which statements about JDBC are NOT true? (choose 2)|JDBC is a Java database sy
stem. JDBC is a Java API for connecting to any kind of DBMS
Which two code fragments correctly create and initialize a static array of int
elements? (Choose two.)|static final int[] a = { 100,200 }; - static final int[]
a; static { a=new int[2]; a[0]=100; a[1]=200; }
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? (Choose two.)|Map - Collection
You execute the following code in an empty directory. What is the result? (Choos
e one.) 1. File f1 = new File("dirname"); 2. File f2 = new File(f1, "filename");
|No directory is created, and no file is created.
"A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating if it has been neutered, and a textual descripti
on of its markings."|public class Cat extends Pet
"A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual desc
ription of its markings."|boolean neutered; - String markings;
public class Pass |doStuff x = 5 main x = 5
which of the following is incorrect | when an application begins running, there
is one deamon thread
public class test1|public float amethod(float x, float y){}
which of the following statements is true about two base protocols used for netw
orking:TPC and UDP|TPC is a connection-based protocol and UDP is not connec
public class Main|the program has a compile error
which method do you see to enable or disable components such as jbuttons|enable(
)
which of following methods of the java.io.file can be used to check whether a fi
le can be read or not|canread()
which statements about jdbc are not true|Jdbc is a java APi for connecting to an
y kind of DBMS - is a java database system
with respect to stops in RMI implementation | create interface - create object -
create stub- create client
the class is primary clas that has the driver information | drivermanager
select a correct statement | datainputstream, dataoutputstream are binary stream
s
select incorrect statement about remote class| it must extend java.rmi.server.un
icastremoteObject
the container can display three completely different components at different tim
es, depending perhaps on user input|cardlayout
public class Mine|No such file found, doing finally; -1
which to of the following interfaces are at the top of the hierarchies in the ja
va collections framework | collection - map
a dialog prevents user input to other windows in the application until the di
alog is closed | modal
MVC is short call of | model-view-controller
which of the followings statements is true | rows and columns ins a gridbaglayou
t can have different sizes
select the correct statement which set the layout manager of a given frame to fl
owlayoutmanager| setlayout(new flowlayout());
public class main|line 17 is never executed
which of the following statements is true| in the networking with client-server
model, the server computer has a socket ...also need
swing is part of the java foundation classes and provides a rich set of gui comp
onents |none of the others
fileoutputstream fos = new fileoutputstream("dest") | 12
public class setF extends frame|s.setbackground(color.pink)
which of the following layout manager will present components with the same size
|java.awt.gridlayour
the default type of the resultset object is | type_forward_only
public class main|line 17 throws an exception at runtime
select incorrect statement about remote class|it must extend java.rmi.server. re
moteObject
how can you change the current working directory using an instance of the file c
lass called filename|the file class does not support directly changing the curre
nt directory
in a client-server application model, which sides will initiate a connection|ser
ver
public class Mod|error at compilation: native method cannot be static
select the correct result of the expression: 5 >>> 1|2
class InOut|system.out.println(iArgs); - System.out.println(s);
which of the following methods of the java.io.File can be used to create a new f
ile|createNewFile()
Which of the following about Reader class is true|Reader has method that can rea
d a single character
which of the following is true|The >> operator carries the sign bit when shiftin
g right. The >>> zero-fills bits that have been shifted out
what is the difference between yielding and sleeping|when a task invokes its yie
ld() method, it returns to the ready state.
class base|Runtime exception
which of the followings is incorrect|when an application begins running, there i
s one deamon thread
which of the following is not an example pf a data type|public
which if the following is true| you cannot call enum's to string() method
what must a class do to implement an interface|it must provide all of the method
s in the interface and identify the interface in its implements clause
all of the numeric wrapper classes in the java.lang package are subclasses of th
e abstract class|java.lang.number
which of the following modifiers does not allow a variable to be modified its va
lue once it was initialized|final
public static void main|the program will run and output only "fliton"
RMI applications often often comprise two separate programs, a server and a clie
nt and they|can run in two separate machine
abstract class minebase|Error mine must be declared abstract
which of the following is true about Wrapped classes| Wrapped classes are classe
s that allow primitive types to be accessed as objects
if(check4Biz(storeNum)!= null){}|boolean - String
for a class defined inside a method, what rule governs access to the variables o
f the enclosing method|the class can only access final variables
select the correct statement which set the layout manager of a given frame to fl
owlayoutmanager | setLayout(new Flowlayout());
select the correct syntax for throwing an exception when declaring a method | [M
odifier] {return type] Indentifier (Parameters) throws TypeofException
in RMI implementations, all methods, declared in the remote interface, must thro
w the exception|java.rmi.RemoteException
public class Funcs extends java.lang.math|The line 10 causes compile-time error
which of the following statements is true about a variable created with the stat
ic modifier|A static variable created in a method will keep the same value betwe
en calls
try {|ac
what will happen if you try to compile and run the following code | 2
line.point p = new line.point();| true
the default type of the resultset object is| TYPE_FORWARD_ONLY
base(){} base (intj,int k){}| true
foo(count); | 1
suppose the declared type of x is a class| when the type of x is object
A method in an interface can access class level | true
double d = 1.2d|true
Access the variables only via synchronized methods | true
the swing's list + the swing's label| true
which of the following operations might throw an arithmetic exception| %
under no circumstances + adding more classes| true
a protected method may only be accessed by classes of the same | true
vector does not allow duplicate elements | true
datainputstream | fileinputstream
the program cause errors when it is compiled | true
tcp is a connection-based protocol | true
to check whether the file denoted by the abstract | true
what is the output when you try to compile and run the | EQUAL
we don't need any method because elements in vector are automatically sorted | t
rue
setlayout(new flowlayout());| true
for (float f:salaries)| true
a runtime error indicating that no run method |true
if(s.equalIgnoreCase(s2))| true
output one one two two | true
String x = *Hello*. int y = 9;x= x+ y | true
the compiler will compalin that the base class is not declared as abstract | tru
e
No compiler error and no exception | class A
you can not call an enum's to string | true
creatnewfile()| true
given a string constructed by calling s = new String("xyzzy") | none of the othe
r
b=m; | class base{}
cannot call to a static synchonized method | true
How can you force garbage collection of an object | garbage collection cannot be
force
char c = \u1234| true
boderlayout is the default layout manager | true
if(s.equalsIgnoreCase(s2)) | true
int x = 6; x =~x | true
What is the return type of the instanceof operator? | A boolean
Wrapper classes are: Boolean, Char, Byte, Short, Integer, Long, Float and Double
| true
The GridBagLayout managet is the default manager for JFame | true
When you construct an instance of File, the file will bot be created even if the
corresponding file does not exist on the | true
public interface B instanceOf A {} | true
A for statement can loop infinitely, for example: for(;;); | true
a # b; a == c | true
How many strings, specified by the above code, are stored in the memory of the p
rogram? | 2
What is the difference between a TextArea and a TextField? | A TextArea can hand
le multiple lines of text
You have been given a design document for a veterinary registration system for i
mplementation in Java. It states: | String markings; boolean neutered
The default type of the ResultSet object is...| TYPE_FORWARD_ONLY
Suppose the declared type of x is a class, and the declared type of is an interf
ace. When is the assignment x=y: legal? | When the type of x is Object
Which of the following statements is INCORRECT? | A method in a interface can ac
cess class level
Which of the following is legal? | double d =1.2d
How do you prevent shared data from being corrupted in a multithreaded environme
nt? | Access the variables only via synchronized
Sellect correct statement | 1.3
Which of the following operations might throw an ArithmeticException?| %
Select the most correct statement | A protected method may only be accessed by c
lasses of the same package or by subclasses of he class in which itt is declared
Which of the following statements is incorrect? | Vector does not allow duplicat
e elements
What is 7 % -4? | 3
A signed data type has an equal number of non-zero positive and negative values
available | false
Whih of the following statements is correct ? | Both primitives and object refer
ences can be both converted and cast
Which of the following statements is true about two base protocols used for netw
orking: TCP and UDP | TCP is a connection-based protocol and UDP is not connecti
on-based protocol
Which of the statements below are true ? | To check whether the file denoted by
the abstract pathname is a directory or not, call the isDirectory() method of th
e File class
Which of the following methods of the Collections class can be used to find the
largest value in a Vector? | We don't need any method because elements in Vector
are automatically sorted. Therefore, the first element contains the macimum val
ue
Select the correct statement which set the layout manager of a given frame to Fl
owLayoutManager | setLayout(new FlowLayout();
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? | for (float f
:salaries)
Whenever a method does not want to handle exceptions using try block, the______i
s used. | throws
Which of the following is true? | You cannot call an enum's toString() method
Which is the four steps are used in working with JDBC? |1Create a statement and
ecevute the query (2) Create the connection (3) Look at the result set (4) Close
connection
Which of the following method of the java.io.File can be used to create a new fi
le? | createNewFile()
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? | None of the others
Which of the following statements in INCORRECT about a non-static synchronized m
ethod? | It cannot call to a static synchronized method of the current class
Which of the following is INCORRECT? | char c=\u1234;
In RMI implementations, all methods, declared in the remote interface, must thro
w the...exception | java.rmi.RemoteException
What method of the java.io.File class can create a file on the hard drive? | cre
ateNewFile()
Which of the following statement is true? | BorderLayout is the default layout m
anager for every JFrame
A_____dialog prevents user input to other windows in the application until the d
ialof is closed. | Modal
How do you prevent shared data from being corrupted in a multithreaded environme
nt? | Access the variables only via synchronized methods
When a user selects a menu item, ______ is generated | Action event
Which of the following operators can perform promotion on their operands? | + -
Which line contains only legal statements? | int x=6; x=~x;
Which Man class property represents the relationship "Man has the best friend wh
o is a Dog"?| class Man { private BestFriend dog;}
Select the most correct statement | A thread is in the ready state after it has
been created and started
What is the return type of the instanceof operator? | A boolean
Which of the following is true about Wrapped classes? | Wrapper classes are: Boo
lean, Char, Byte, Short, Integer, Long, Float and Double
What is the range of values that cacn be assigned to a variable of type short? |
-2^15 through 2^15 -1
When is it appropriate to pass a cause to an exception's constructor? | When the
exception is being thrown in response to catching of a different exception type
Which of the statement below is true? | When yuo construct an instance of File,
the file will not be created even if the corresponding file does not exist on th
e local system
Which of the following may follow the static keyword? (Select two) | Methods and
Non-inner class definitions
Which of the following statements is true? | Constructors are not inherited
Which of the following statements is true? | A for statement can loop infinitely
, for example: for(;;);
Select INCORRECT statement about deserialize. | We use readObject() method of Ob
jectOutputStream class to deserialize
A(n)_____object is uses to obtain a Connection to a Database | DriverManager
What is the difference between a TextArea and A TextField? | A TextArea can hand
le multipe lines of text

Which of the following are valid declarations? Assume java.util.* is imported. |


Vector,Set,Map
You can determine all the keys in a Map in which of the following ways? | By ge
tting a Set object from the Map and iterating through it
What keyword is used to prevent an object from being serialized? | transient
An abstract class can contain methods with declared bodies. | True
Select the order of access modifiers from least restrictive to most restrictive.
| public,protected,default,private
Which access modifier allows you to access method calls in libraries not create
d in Java? | native
Which of the following statements are true? | A final object cannot be reassigne
d a new address in memory
The keyword extends refers to what type of relationship? | is a
Which of the following keywords is used to invoke a method in the parent class?
| super
Given the following code, what will be the outcome? public class Funcs extends j
ava.lang.Math{public int add(int x, int y){return x + y;}public int sub(int x,
int y){return x - y;}public static void main(String[]a){Funcs f = new Funcs(
);System.out.println("" + f.add(1, 2));}} | The code does not compile
public class Test {public static void main(String [] a){int [] b = [1,2,3,4,5,6,
7,8,9,0]; System.out.println("a[2]=" + a[2]);}} | The code does not compile
x = 23 % 4; | 3
<insert code> | break
What method call is used to tell a thread that it has the opportunity to run? |
notify()
Assertions are used to enforce all but which of the following? | Exceptions
The developer can force garbage collection by call System.gc() | False
Select the valid primitive data types. | boolean,char,float
How many bits does a float contain? | 32
What is the value of the x after the following line is executed? x = 32 * (31 -
10 *3) | 32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
| True
Select the list of primitives ordered in smallest bit size representation. | cha
r,int,float,long
Which class provides locale-sensitive text formatting for date and time informat
ion? | java.text.DateFormat
int x = 9; byte b = x; | False
Which of the following code snippets compile? | Integer i = 7;Interger i = new I
nteger(5);byte b=7
Java arrays always start at index 1. | False
Which of the following statements accurately describes how variables are passed
to methods? | Arguments that are primitve type are passed by value
How do you change the value that is encapsulated by a wrapper class after you ha
ve instan-tiated it? | None of the above:setXXX(),Parse,equals
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method sh
ould imple- ment the custom deserialization, and what is its access mode? | priv
ate readObject
Choose the valid identifiers from those listed here. | BigOlLongString,$int,byte
s,$1,finalist
Which of the following signatures are valid for the main() method entry point of
an application? | public static void main(String arg[]),(String args[])
If all three top-level elements occur in a source file, they must appear in whic
h order? | Package declaration,imports,class/interface/enum definitions.
int[] x = new int[25]; | x[24] is 0,x.length is 25
is a set of java API for executing SQL statements. | JDBC
method is used to wait for a client to initiate communications. | accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect. Again, because of the native code, their portability is
limited. | Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source. | Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source. | Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally ependent on a native library, whic
h limits their portability. | Type 1
x = 32 (31 - 10 3); | 32
A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe.
|
Java arrays always start at index 1. | False
Which of the following statements accurately describes how variables are passed
to methods? | Arguments that are primitive type are passed by value.
Suppose you are writing a class that provides custom deserialization. The class
implements java.io.Serializable (and not java.io.Externalizable). What method sh
ould imple- ment the custom deserialization, and what is its access mode? | priv
ate readObject
A signed data type has an equal number of non-zero positive and negative values
available. | False
What is the range of values that can be assigned to a variable of type short? |
-215 through 215 - 1
What is the range of values that can be assigned to a variable of type byte? | -
27 through 27 - 1
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? | Compilation takes
slightly more time.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? | Cl
ass loading takes no additional time.
Which of the following are legal import statements? | import java.util.Vector;im
port static java.util.Vector.*;
Which of the following may be statically imported? | Static method names,Method-
local variable names
Which of the following are legal? | int c = 0xabcd;int d = 0XABCD;
Which of the following are legal? | double d = 1.2d;double d = 1.2D;
Which of the following are legal? | char c = '\u1234';
int x, a = 6, b = 7; x = a++ + b++; | x = 13, a = 7, b = 8
Which of the following expressions are legal? | int x = 6; if (!(x > 3)) {};int
x = 6; x = ~x;
Which of the following expressions results in a positive value in x? | int x = -
1; x = x >>> 5;
Which of the following expressions are legal? | String x = "Hello"; int y = 9; x
+= y;String x = "Hello"; int y = 9; x = x + y;
What is -8 % 5? | -3
What is 7 % -4? | 3
What results from running the following code?public class Xor {public static voi
d main(String args[]) {byte b = 10; // 00001010 binary byte c = 15; // 00001111
binary b = (byte)(b ^ c);System.out.println("b contains " + b);}} | The output:
b contains 5
What results from attempting to compile and run the following code?public class
Conditional {public static void main(String args[]) {int x = 4;System.out.printl
n("value is " +((x > 4) ? 99.99 : 9));}} | The output: value is 9.0
What does the following code do?Integer i = null;if (i != null & i.intValue() ==
5) System.out.println("Value is 5"); | Throws an exception.
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances?boolean weird(Thing s) { Integer x = new
Integer(5); return s.equals(x);} | Yes
Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 ==
ob2) is false, can ob1.equals(ob2) ever be true? | No
When a byte is added to a char, what is the type of the result? | int
When a short is added to a float, what is the type of the result? | float
Which statement is true about the following method?int selfXor(int i) { return i
^ i;} | It always returns 0.
What is the return type of the instanceof operator? | A boolean
Which of the following may appear on the left-hand side of an instanceof operato
r? | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? | A class;An interface
What is -50 >> 1? | -25
Which of the following declarations are illegal? | default String s;public final
;abstract final double hyperbolicCosine();
Which of the following statements is true? | A final class may not have any abst
ract methods.
Which of the following statements is true? | Transient variables are not seriali
zed.
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? | transient
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby's version of the method have? | public;protected
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods. Which is/are true? | The class will compile;The class may not be
instantiated.
Which of the following may be declared final? | Classes;Data;Methods
Which of the following may follow the static keyword? | Data;Methods;Code blocks
enclosed in curly brackets
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may apply to B
's version of doSomething()? | public;protected;Default
True or false: If class Y extends class X, the two classes are in different pack
ages, and class X has a protected method called abby(), then any instance of Y m
ay call the abby() method of any other instance of Y. | False
Which of the following statements are true? | A final class may not be extended.
What does the following code print?public class A{static int x;public static voi
d main(String[] args) { A that1 = new A();A that2 = new A(); that1.x = 5; that2.
x = 1000;x = -1; System.out.println(x);}} | 1000
Which of the following statements is correct? | Both primitives and object refer
ences can be both converted and cast.
Which one line in the following code will not compile?byte b = 5;char c = '5';sh
ort s = 55;int i = 555;float f = 555.5f;b = s;i = c;if (f > b) f = i; | Line 6
In the following code, what are the possible types for variable result? byte b =
11;short s = 13;result = b * ++s; | int, long, float, double
Consider the following class:class Cruncher {void crunch(int i) {System.out.prin
tln("int version");}void crunch(String s) {System.out.println("String version");
} 8.public static void main(String args[]) {Cruncher crun = new Cruncher();char
ch = 'p';crun.crunch(ch);}} | The code will compile and produce the following ou
tput: int version.
Which of the following statements is true? | Object references can be converted
in both method calls and assignments, and the rules governing these conversions
are identical.
Consider the following code. Which line will not compile?Object ob = new Object(
);String[] stringarr = new String[50];Float floater = new Float(3.14f);ob = stri
ngarr;ob = stringarr[5];floater = ob;ob = floater; | Line 6
Consider the following code: Cat sunflower;Washer wawa;SwampThing pogo;sunflower
= new Cat();wawa = sunflower;pogo = (SwampThing)wawa; | The code will compile b
ut will throw an exception at line 7, because the runtime class of wawa cannot b
e converted to type SwamThing.
Consider the following code: Raccoon rocky;SwampThing pogo;Washer w;rocky = new
Raccoon();w = rocky;pogo = w; | Line 7 will not compile; an explicit cast is req
uired to convert a Washer to a SwampThing.
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? | All of the above
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? | When the type of x is Object
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? | All: Abstract,Final,Primitives
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? | Sometimes
When is x & y an int? (Choose one). | Sometimes
What are the legal types for whatsMyType?short s = 10; whatsMyType = !s; | There
are no possible legal types.
When a negative long is cast to a byte, what are the possible values of the resu
lt? | All:Positive,Zero,Negative
Which of the following operators can perform promotion on their operands? | + -
~
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? | There is no difference; the rules are the same.
is a set of java API for executing SQL statements | JDBC
method is used to wait for a client to initiate communications | accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect | Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source | Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source | Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally dependent on a native library, whi
ch limits their portability | Type 1
System.out.println(a.doit(4, 5)) | Line 26 prints a to System.out
Which two are true if a NullPointerException is thrown on line 3 of class C | co
de on line 29, The exception
What lines are output if the constructor at line 3 throws a MalformedURLExceptio
n | Bad URL, Doing finally, Carrying
What lines are output if the methods at lines 3 and 5 complete successfully with
out throwing any exceptions | Success, Doing, Carrying
If lines 24, 25 and 26 were removed, the code would compile and the output would
be 1 | 3.The code, would be 1, 2
An exception is thrown at runtime | An exception
first second first third snootchy 420 | third second first snootchy 420
dialog prevents user input to other windows in the application unitl the dialog
is closed | Modal
You would like to write code to read back the data from this file. Which solutio
ns will work | 2.FileInputStream, RandomAccessFile
A Java monitor must either extend Thread or implement Runnable | F
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1 | You cannot specify
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these ways | public void logIt(
String... msgs)
A signed data type has an equal number of non-zero positive and negative values
available | F
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread | F
catch (InterruptedException e) | running some time
object is used to submit a query to a database | Statement
object is uses to obtain a Connection to a Database | DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b | x13, a7, b8
Yen and Euro both return correct Country value | 2.Euro returns, error at line
25
BigOlLongStringWithMeaninglessName | tick all
Compilation of class A will fail. Compilation of class B will succeed | B fail,
A succeed
Line 46 will compile if enclosed in a try block, where TestException is caught |
2.if the enclosing, is caught
Holder h = new Holder() | 101
Decrementer dec = new Decrementer() | 12.3
Test t = (new Base()).new Test(1) | 2.new Test(1), new Test(1, 2)
Base(int j, int k, int l) | 2.Base(), Base(int j, int k)
Line 12 will not compile, because no version of crunch() takes a char argument |
output: int version
output results when the main method of the class Sub is run | Value 5 This value
6
Float floater = new Float(3.14f) | Line 6
The application must be run with the -enableassertions flag or another assertion
enabling flag | dai nhat, one or more
After line 3 executes, the StringBuffer object is eligible for garbage collectio
n | line 2 executes..collection
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | type SwampThing
The code will compile and run, but the cast in line 6 is not required and can be
eliminated | The code will compile and run
for (int i = 0; i < 2; i++) | 4.i0,j12 - i1,j02
outer: for (int i = 0; i < 2; i++) | i = 1 j = 0
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | Line 7 will not compile
int[] x = new int[25] | 2.x[24]=0, x.length is 25
public float aMethod(float a, float b) throws Exception | int a,b float p,q
public float aMethod(float a, float b, int c) throws Exception | 3.int a,b. floa
t a,b-int c. private
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i | Arrays.equals(a1, a2)
Assuming the class does not perform custom serialization, which fields are writt
en when an instance of Xyz is serialized | 3.Public, Private, Volatile
can legally be placed before aMethod() on line 3 and be placed before aMethod()
on line 8 | 3: private; 8: protected
NUTMEG, CINNAMON, CORIANDER, ROSEMARY | 3.Spice sp, Spice, String
List<String> names = new ArrayList<String>() | 2.Iterator, for
Compilation fails because of an error in line 15 | error in line 19
1 2 3 | 2 3
public interface B inheritsFrom A | B extends A
protected double getSalesAmount() { return 1230.45; } | 2.public, protected
Line 16 creates a directory named d and a file f within it in the file system | 3.An
exception, Line 13, line 14
Nav.Direction d = Nav.Direction.NORTH | Nav.Direction.NORTH
new class Foo { public int bar() { return 1; } } | new Foo()
IllegalArgumentException | StackOverflowError
Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw() | Shape s = ne
w Circle...s.draw()
Compilation fails because of an error in line 12 | 1 2 3
NullPointerException | Compilation fails
A NumberFormatException is thrown by the parse method at runtime | Compilation f
ails
An exception is thrown at runtime | Compilation fails
passed An AssertionException is thrown without the word stuff added to the stack t
race | An AssertionError...with the
collie | collie harrier
doStuff x = 6 main x = 6 | doStuff x =5 main x =5
The setCardlnformation method breaks encapsulation | The ownerName
The value of all four objects prints in natural order | Compilation fails...line
29
The code on line 33 executes successfully | 3.33 throws, 35 throws, 33 executes
What is the result if a NullPointerException occurs on line 34 | ac
Compilation will fail because of an error in line 55 | Line 57...value 3
java -ea test file1 file2 | 2.java -ea test, dai nhat
String s = 123456789 ; s = (s- 123 ).replace(1,3, 24 ) - 89 | 2.delete(4,6), delete(2,5)
rt( 1, 24 )
The Point class cannot be instatiated at line 15 | Line.Point p = new Line.Point
()
for( int i=0; i< x.length; i++ ) System.out.println(x[i]) | 2.for(int z : x),
dai nhat
int MY_VALUE = 10 | 3.final, static, public
Compilation fails because of an error in line: public void process() throws Runt
imeException | A Exception
How can you ensure that multithreaded code does not deadlock | There is no singl
e
How can you force garbage collection of an object | Garbage collection
How do you prevent shared data from being corrupted in a multithreaded environme
nt | Access the variables
How do you use the File class to list the contents of a directory | String[] con
tents
The number of bytes depends on the underlying system | 8
How many locks does an object have | One
If all three top-level elements occur in a source file, they must appear in whic
h order | Package declaration, imports
the two classes are in different packages, and class X has a protected method ca
lled abby(), then any instance of Y may call the abby() method of any | F
TestThread3 ttt = new TestThread3 | Y
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method | Comparable...compareTo
after execution of line 1, sbuf references an instance of the StringBuffer class
. After execution of line 2, sbuf still references the same instance | T
what are the possible types for variable result | int, long, float, double
helps manage the connection between a Java program and a database | Connection
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances | Y
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks | Y
JDBC supports ______ and ______ models | Two-tier and three-tier
MVC is short call of | Model-View-Controller
No output because of compile error at line: System.out.println("b="+b) | b = b *
b1
Object ob2= new Object() | Have a nice day
Object ob2= ob1 | ob1 equals ob2, ob1==ob2
String s2 = "xyz" | Line 4, Line 6
String s2 = new String("xyz") | Line 6
String s2 = new String(s1) | Line 6
Select correct statement about RMI | All the above
Select correct statement(s) about remote class | All the others choices
Select correct statements about remote interface | All the others choices
Select INCORRECT statement about serialization | When an Object Output
Select INCORRECT statement about deserialize | We use readObject
Select incorrect statement about RMI server | A client accesses
Select incorrect statement about ServerSocket class | To make the new object
Select incorrect statement about Socket class | server through UDP
Select the correct statement about JDBC two-tier processing model | A user's com
mands
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query | WHERE
Statement objects return SQL query results as | ResultSet
When a JDBC connection is created, it is in auto-commit mode | Both 1 and 2 are
true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block | If the JVM doesn't crash
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class | no
additional time
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file | slightly more time
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable | C must have a
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable | B must have a
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething() | private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething() | 2.public, protec
ted
void doSomething(int a, float b) | public...(int a, float b)
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods | 2.declared abstract, may not be
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries | for (float f:
salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal | When the...x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant | if (x == y)
Suppose you are writing a class that will provide custom deserialization. What a
ccess mode should the readObject() method have | private
Suppose you are writing a class that will provide custom serialization. What acc
ess mode should the writeObject() method have | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality | Override run()
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods | subclass java.lang.Math
Swing components cannot be combined with AWT components | T
class is the primary class that has the driver information | DriverManager
class is used to implement a pull-down menu that provides a number of items to s
elect from | Menu
The element method alters the contents of a Queue | F
The Swing component classes can be found in the | javax.swing
There are two classes in Java to enable communication using datagrams namely | D
ataPacket and DataSocket
Compilation of Parrot.java fails at line 7 because method getRefCount() is stati
c in the superclass, and static methods may not be overridden to be nonstatic |
dai nhat: nonstatic
Compilation of Nightingale will succeed, but an exception will be thrown at line
10, because method fly() is protected in the superclass | The program...After:
2
void doSomething() throws IOException, EOFException | ngan-dai nhat, throws EOFE
xception
URL referring to databases use the form | protocol:subprotocol:datasoursename
What are the legal types for whatsMyType | There are no possible legal types
What does the following code do | Throws an exception
There is no output because the code throws an exception at line 1 | output is i
= 20
1000 | -1
What happens when you try to compile and run the following application | thrown
at line 9
The code compiles, and prints out >>null<< | out >>null<<
An exception is thrown at line 6 | thrown at line 7
What is -50 >> 2 | -13
What is 7 % -4 | 3
What is -8 % 5 | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion | There is no difference
The code will compile as is. No modification is needed | On line 1, remove
What is the range of values that can be assigned to a variable of type byte | ?2
mu7 through 2mu7 ? 1
What is the range of values that can be assigned to a variable of type short | ?
2mu15 through
The code compiles and executes; afterward, the current working directory contain
s a file called datafile | The code fails to compile
What is the return type of the instanceof operator | A boolean
What method of the java.io.File class can create a file on the hard drive | crea
teNewFile()
The output: value is 99.99 | value is 9.0
The output: b contains 250 | b contains 5
What would be the output from this code fragment | message four
When a byte is added to a char, what is the type of the result | int
When a negative byte is cast to a long, what are the possible values of the resu
lt | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt | All the above
When a short is added to a float, what is the type of the result | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two | writing a line
When does an exception's stack trace get recorded in the exception object | is c
onstructed
When is it appropriate to pass a cause to an exception's constructor | in respon
se to catching
When is it appropriate to write code that constructs and throws an error | Never
When is x & y an int | Sometimes
When the user attempts to close the frame window, _______ event in generated | w
indow closing
When the user selects a menu item, _______ event is generated | Action event
Java programming language, the compiler converts the human-readable source file
into platform-independent code that a Java Virtual Machine can understand | byte
code
Whenever a method does not want to handle exceptions using the try block, the |
throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database | String url =jdbc:odbc
Which class and static method can you use to convert an array to a List | Arrays
.asList
Which is four-step approach to help you organize your GUI thinking | Identify, I
solate, Sketch
Which is the four steps are used in working with JDBC | Connect, Create, Look
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r | sc.useDelimiter("\\d")
Man has the best friend who is a Dog | private Dog bestFriend
Which methods return an enum constant s name | 2.name(), toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state | transient
Which of the following are legal argument types for a switch statement | 3.byte,
int, char
Which of the following are legal enums | 3.ngan-dai nhat, lion int weight
Which of the following are legal import statements | 2.import...Vector, Vector.*
Which of the following are legal loop constructions | for (int k=0, j+k != 10; j
++,k++)
Which of the following are legal loop definitions | None of the above
double d = 1.2d5 | 2.double d = 1.2d, 1.2D
int d = 0XABCD | 2.int c = 0xabcd, dai nhat
char c = 0x1234 | 2.0x.., '\u1234'
Vector <String> theVec = new Vector<String>() | 2.List...<String>(), dai nhat
Which of the following are methods of the java.util.SortedMap interface | headMa
p, tailMap, subMap
Which of the following are methods of the java.util.SortedSet interface | All th
e above
System.out has a println() method | All the above
The JVM runs until there is only one non-daemon thread | are no non-daemon
When an application begins running, there is one non-daemon thread, whose job is
to execute main() | 3.nhat, thread, non-daemon thread
When you declare a block of code inside a method to be synchronized, you can spe
cify the object on whose lock the block should synchronize | 2.the method always
, nhat
An enum definition should declare that it extends java.lang.Enum | 2.contain pub
lic, private
Primitives are passed by reference | 2.by value
An anonymous inner class that implements several interfaces may extend a parent
class other than Object | implement at most, class may extend
Which of the following are valid arguments to the DataInputStream constructor |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or | All the above
Which of the following calls may be made from a non-static synchronized method |
All the above
Which of the following classes implement java.util.List | 2.ArrayList, Stack
Which of the following classes implements a FIFO Queue | LinkedList
Which of the following declarations are illegal | 3.ngan-dai nhat, double d
int x = 6; if (!(x > 3)) | 2.dai nhat, x = ~x
String x = "Hello"; int y = 9; if (x == y) | 2.ngan nhat, x=x+y
Which of the following expressions results in a positive value in x | int x = 1;
x = x >>> 5
Which of the following interfaces does not allow duplicate objects | Set
Which of the following is not appropriate situations for assertions | Preconditi
ons of a public method
Which of the following is NOTa valid comment | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method | IllegalArgumentException
Readers have methods that can read and return floats and doubles | None of the a
bove
An enum definition may contain the main() method of an application | All the abo
ve
Which of the following may appear on the left-hand side of an instanceof operato
r | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or | 2.A class, An interface
Which of the following may be declared final | 2.Classes, Methods
Which of the following may be statically imported | 2.Static method, Static fiel
d
Which of the following may follow the static keyword | 3.Data, Methods, Code blo
cks
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation | All of
Which of the following may not be synchronized | Classes
Which of the following may override a method whose signature is void xyz(float f
) | 2.void, public void xyz(float f)
Which of the following methods in the Thread class are deprecated | suspend() an
d resume()
Which of the following operations might throw an ArithmeticException | None of
Which of the following operators can perform promotion on their operands | 3.con
g, tru, xap xi
Which of the following restrictions apply to anonymous inner classes | must be d
efined
Which of the following should always be caught | Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application | 2.static void...(String arg[])
Which of the following statements about the wait() and notify() methods is true
| calls wait() goes into
Which of the following statements about threads is true | Threads inherit their
A final class may not contain non-final data fields | may not be extended
An abstract class must declare that it implements an interface | None
An abstract class may not have any final methods | Only statement 2
Only object references are converted automatically; to change the type of a prim
itive, you have to do a cast | Both primitives
Transient methods may not be overridden | variables are not
Object references can be converted in both method calls and assignments, but the
rules governing these conversions are very different | conversions are identica
l
Bytecode characters are all 16 bits | Unicode characters
To change the current working directory, call the changeWorkingDirectory() metho
d of the File class | None
When you construct an instance of File, if you do not use the file-naming semant
ics of the local machine, the constructor will throw an IOException | None
When the application is run, thread hp1 will execute to completion, thread hp2 w
ill execute to completion, then thread hp3 will execute to completion | None of
Compilation succeeds, although the import on line 1 is not necessary. During exe
cution, an exception is thrown at line 3 | fails at line 2
Compilation fails at line 1 because the String constructor must be called explic
itly | succeeds. No exception
Line 4 executes and line 6 does not | Line 6 executes
There will be a compiler error, because class Greebo does not correctly implemen
t the Runnable interface | Runnable interface
The acceptable types for the variable j, as the argument to the switch() constru
ct, could be any of byte, short, int, or long | value is three
The returned value varies depending on the argument | returns 0
Lines 5 and 12 will not compile because the method names and return types are mi
ssing | output x = 3
Line 13 will not compile because it is a static reference to a private variable
| output is x = 104
Which statements about JDBC are NOT true | 2.database system, DBMS
Which two code fragments correctly create and initialize a static array of int
elements | 2.a = { 100,200 }, static
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework | 2.Map, Collection
A new directory called dirname and a new file called filename are created, both
in the current working directory | No directory
protected class Cat extends Owner | public class Cat extends Pet
Date vaccinationDue | 2.boolean, String
What is -15 % -10 | -5
command line on a Windows system | 2.must contain the statement, the file
The string created on line 2 does not become eligible for garbage collection in
this code | After line 3
When the application runs, what are the values of n and w.x after the call to bu
mp() in the main | n is 10, w.x is 11
The addAll() method of that interface takes a single argument, which is a ref
erence to a collection whose elements are compatible with E. What is the declar
ation of the addAll() method | addAll(Collection<? extends E> c)
If you want a vector in which you know you will only store strings, what are the
advantages of using fancyVec rather than plainVec | Attempting to...compiler er
ror
When should objects stored in a Set implement the java.util.Comparable interfac
e | Set is a TreeSet
What relationship does the extends keyword represent | is a
class bbb.Bbb, which extends aaa.AAA, wants to override callMe(). Which access m
odes for callMe() in aaa.AAA will allow this | 2.public, protected
Lemon lem = new Lemon(); Citrus cit = new Citrus() | 3.cit = lem, cit=(Citrus),
lem=(lemon)
it also has a method called chopWoodAndCarryWater(), which just calls the other
two methods | inappropriate cohesion, inappropriate coupling
sharedOb.wait() | 2.aThread.interrupt, sharedOb.notifyAll
line prints double d in a left-justified field that is 20 characters wide, with
15 characters to the right of the decimal point | System.out.format("%-20.15f",
d)
What code at line 3 produces the following output | String delim = \\d+
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc | NumberFormat.getInstance(loc)
you want to use a DateFormat to format an instance of Date. What factors influ
ence the string returned by DateFormat s format() method | 2.LONG, or FULL, The lo
cale
you want to create a class that compiles and can be serialized and deserialized
without causing an exception to be thrown. Which statements are true regarding
the class | 2.dai nhat, ngan nhat
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
What interfaces can be implemented in order to create a class that can be serial
ized | 2.dai nhat, ngan nhat
The file contains lines of 8-bit text, and the 8-bit encoding represents the lo
cal character set, as represented by the cur- rent default locale. The lines are
separated by newline characters | FileReader instance
shorty is a short and wrapped is a Short | all
How is IllegalArgumentException used | 2.certain methods, public methods
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction | None
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime | 2.assert x == 4
int[] ages = { 9, 41, 49 }; int sum = 0 | 2.i<ages.length, for (int i:ages)
Which of the following types are legal arguments of a switch statement | enums,
bytes
class A extends java.util.Vector { private A(int x) | does not create a defau
lt
void callMe(String names) | method, names is an array
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards | public Color ge
tTheTint()
are valid arguments to the DataInputStream constructor | FileInputStream
are valid mode strings for the RandomAccessFile constructor | r, rw, rws, rwd
method of the java.io.File class can create a file on the hard drive | createNe
wFile()
class A extends Object; Class B extends A; and class C extends B. Of these, only
class C implements java.io.Externalizable | C must have
class A extends Object; class B extends A; and class C extends B. Of these, only
class C implements java.io.Serializable | B must have
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
you are writing a class that will provide custom serialization. The class implem
ents java.io.Serializable (not java.io.Externalizable) | private
How do you use the File class to list the contents of a directory | String[] c
ontents = myFile.list();
call returns true if a1 and a2 have the same length, and a1[i].equals(a2[i]) fo
r every legal index i | java.util.Arrays.equals(a1, a2)
line of code tells a scanner called sc to use a single digit as a delimiter | sc
.useDelimiter( \\d )
you want to write a class that offers static methods to compute hyperbolic trigo
nometric functions. You decide to subclass java.lang.Math and provide the new f
unctionality as a set of static methods | java.lang.Math
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string | none
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do | Override run()
you prevent shared data from being corrupted in a multithreaded environment | Ac
cess the variables
Is it possible to write code that can execute only if the current thread owns
multiple locks | yes
Which of the following may not be synchronized | Classes
statements about the wait() and notify() methods is true | pool of waiting th
reads
methods in the Thread class are deprecated | suspend() and resume()
A Java monitor must either extend Thread or implement Runnable | F
One of the threads is thr1. How can you notify thr1 so that it alone moves from
the Waiting state to the Ready state | You cannot specify
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread | F
Which methods return an enum constant s name | name(), toString()
restrictions apply to anonymous inner classes | inside a code block
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual d
escription of its markings | boolean, string
Which of the following are valid declarations? Assume java.util | 1Vector 2Set 3
Map string,string
You can determine all the keys in a Map in which of the following ways | Set ob
ject from the Map
What keyword is used to prevent an object from being serialized | transient
abstract class can contain methods with declared bodies. | E. public, protecte
d, default, private
access modifier allows you to access method calls in libraries not created in J
ava | native
Which of the following statements are true? (Select all that apply.) | object c
annot reassigned
The keyword extends refers to what type of relationship | is a
keywords is used to invoke a method in the parent class | super
What is the value of x after the following operation is performed | 3
method call is used to tell a thread that it has the opportunity | notify()
Assertions are used to enforce all but which | Exceptions
force garbage collection by calling System.gc(). | B. False
Select the valid primitive data type | 1.boolean 2.char 3.float
How many bits does a float contain | 32
What is the value of x after the following line is executed | 32
StringBuffer is slower than a StringBuilder, but a StringBuffer | True
list of primitives ordered in smallest to largest bit size representation | D.
char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion | java.text.DateFormat
int x = 9; byte b = x | False
Which of the following code snippets compile | 1.Integer 2.Integer 3.byte
Java arrays always start at index 1 | False
accurately describes how variables are passed to methods | that are primitive t
ype are passed by value
change the value that is encapsulated by a wrapper class after you have instan
| None of the above.
The class implements java.io.Serializable (and not java.io.Externalizable) | pri
vate readObject
A signed data type has an equal number of non-zero positive and negative value
s | False
signatures are valid for the main() method entry point of an application | publi
c static void main(String[] args)
three top-level elements occur in a source file, they must appear | Package decl
aration, imports, class/interface/enum definitions
int[] x = new int[25] | x[24] is 0 and x.length is 25
How can you force garbage collection of an object | Garbage collection cannot
be forced.
range of values that can be assigned to a variable of type short | -215 through
215 - 1
range of values that can be assigned to a variable of type byte | -27 through 2
7 - 1
How do the imports affect the time required to compile the source file | Compi
lation takes slightly more time
How do the imports affect the time required to load the class? | Class loading
takes no additional time
legal import statements | 1.import java.util.Vector 2.import static java.ut
il.Vector
may be statically imported | 1.Static method names 2.Static field names
What is -8 % 5 | -3
What is 7 % -4? | 3
ob1 == ob2 | No
When a byte is added to a char | int
When a short is added to a float | float
ArithmeticException | 1.None of these 2./
What is the return type of the instanceof operator | boolean
may appear on the left-hand side of an instanceof operator | reference
may appear on the right-hand side of an instanceof operator | class and interfa
ce
What is -50 >> 1 | -25
A final class may not have any abstract methods | true
denote a variable that should not be written out as part of its class s persistent
state | transient
may legally appear as the new type (between the parentheses) in a cast operati
on | All of the above
type of x is a class, and the declared type of y is an interface. When is the as
signment x = y | When the type of x is Object
xarr is an array of XXX, and the type of yarr is an array of YYY | Sometimes
When is x & y an int | Sometimes
negative long is cast to a byte | All of the above
negative byte is cast to a long | Negative
operators can perform promotion on their operands | + - ~(nga)
difference between the rules for method-call conversion and the rules for assign
ment conversion | There is no difference
Which of the following are appropriate situations for assertions | DAP AN SAI :
Preconditions of a public method
appropriate way to handle invalid arguments in a public method | IllegalArgumen
tException
Suppose salaries is an array containing floats | for (float f:salaries)
Suppose a method called finallyTest() consists of a try block | If the JVM does
n t crash and
appropriate to pass a cause to an exception s constructor | thrown in response to
catching of a different exception type
Which of the following should always be caught | Checked exceptions
When does an exception s stack trace get recorded in the exception object | is c
onstructed
Which of the following is illegal statement? | float f=1.01;
You want to find out the value of the last element of an array. You write the fo
llowing code. What will happen when you compile and run it.?public class MyAr{pu
blic static void main(String argv[]){int[] i = new int[5];System.out.println(i[5
]);}} | An error at run time
What is the return type of the instanceof operator? | A Boolean
Which of the following statements is true? | Object references can be converted
in both method calls and assignments, and the rules governing these conversions
are identical.
Which of the following statements is true? | A class that has one abstract metho
d must be abstract class
What is the difference between yielding and sleeping? | When a task invokes its
yield() method, it returns to the ready state. When a task invokes its sleep() m
ethod, it returns to the waiting state.
A____dialog prevents user input to other windows in the application unitl the di
alog is closed. | Modal
A Java monitor must either extend Thread or implement Runnable. | False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? | You cannot sp
ecify which thread will get notified.
A signed data type has an equal number of non-zero positive and negative values
available. | False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread. | False
A(n)____object is used to submit a query to a database | Statement
A(n)____object is uses to obtain a Connection to a Database | DriverManager
int x, a = 6, b = 7; x = a++ + b++; | x = 13, a = 7, b = 8
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? | java.util.Arrays.equals(a1
, a2);
public class Xyz implements java.io.Serializable | iAmPublic;iAmPrivate;iAmVolat
ile
Given the following code, and making no other changes, which combination of acce
ss modifiers (public, protected, or private) can legally be placed before aMetho
d() on line 3 and be placed before aMethod() on line 8? | line 3: private; line
8: protected
Given the following code, which of the following will compile? (Choose three.)en
um Spice { NUTMEG, CINNAMON, CORIANDER, ROSEMARY; } | 3 cai dai nhat
List<String> names = new ArrayList<String>(); | Iterator<String> iter = names.it
erator();for (String s:names)
String DEFAULT_GREETING = Hello World ; | public interface B extends A { }
protected abstract double getSalesAmount(); | public;protected
File file = new File(directory, f ); | An exception is thrown at runtime;File object
named d. ;Line 14 creates a File object named f.
public enum Direction { NORTH, SOUTH, EAST, WEST } | Nav.Direction d = Nav.Direc
tion.NORTH;
public int fubar( Foo foo) { return foo.bar(); } | new Foo() { public int bar(){
return 1; } }
ClassA a = new ClassA(); | StackOverflowError
public void setAnchor(int x, int y) { | Shape s = new Circle(); s.setAnchor(10,1
0); s.draw();
for (int i: someArray) System.out.print(i +" "); | 1 2 3
System.out.println( NullPointerException ); | Compilation fails.
} catch (NumberFormatException nfe) { | Compilation fails.
System.out.println(tokens.length); | Compilation fails.
System.out.print( collie ); | collie harrier
System.out.print("doStuff x = "+ x++); | doStuff x = 5 main x = 5
public void setCardlnformation(String cardlD,String ownerName,Integer limit) | T
he ownerName variable breaks encapsulation.
java.util.Array.sort(myObjects); | Compilation fails due to an error in line 29.
int []x= {1, 2,3,4, 5}; | Line 57 will print the value 3.
public static class Point { } | Line.Point p = new Line.Point();
static void foo(int...x) { | for(int z : x) System.out.println(z);for( int i=0;
i< x.length; i++ ) System.out.println(x[i]);
public interface Status { | final;static;public
if (true) throw new RuntimeException(); System.out.print("B"); | A Exception
How can you ensure that multithreaded code does not deadlock? | There is no sing
le technique that can guarantee non-deadlocking code.
How can you force garbage collection of an object? | Garbage collection cannot b
e forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? | Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory? | String[] co
ntents = myFile.list();
dos.writeFloat(0.0001f); | 8
How many locks does an object have? | One
If all three top-level elements occur in a source file, they must appear in whic
h order? | Package declaration, imports, class/interface/enum definitions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any other instance of Y. | False
ttt.start(); | yes
If you need a Set implementation that provides value-ordered iteration,which cla
ss should you use? | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? | Comparable interface and its compareTo method.
sbuf.insert("-University"); | True
sbuf.insert(3, "-University"); | True
result = b * ++s; | int, long, float, double
Interface____helps manage the connection between a Java program and a database.
| Connection
boolean weird(Thing s) { Integer x = new Integer(5); return s.equals(x); | Yes
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks? |
JDBC supports___and___models. | Two-tier and three-tier
MVC is short call of | Model-View-Controller
byte b = 2; byte b1 = 3; b = b * b1; | No output because of compile error at lin
e: b = b * b1;
System.out.println("Have a nice day!"); | Have a nice day!
String s2 = "xyz"; | Line 4;Line 6
String s2 = new String("xyz"); | Line 6
String s1 = "xyz"; | Line 6
s2=s2.intern(); | Line 4;Line 6
Select correct statement about RMI | All allow programmers;use object serializat
ion;RMI applications
Select correct statement(s) about remote class | All It must extend;It must impl
ement;It is the class
Select correct statements about remote interface. | A remote;All remote interfac
es;All methods;The type of
Select INCORRECT statement about serialization | dai nhat
Select INCORRECT statement about deserialize. | We use readObject() method of Ob
jectOutputStream class to deserialize.
Select incorrect statement about RMI server. | A client accesses a remote object
by specifying only the server name.
Select incorrect statement about ServerSocket class. | dai nhat
Select incorrect statement about Socket class | with a server through UDP.
Select the correct statement about JDBC two-tier processing model. | A user's co
mmands are delivered to the database or other data source, and the results of th
ose statements are sent back to the user.
SQL keyword____is followed by the selection criteria that specify the rows to se
lect in a query | WHERE
Statement objects return SQL query results as____objects | ResultSet
Study the statements: 1)When a JDBC connection is created, it is in auto-commit
mode 2)Once auto-commit mode is disabled, no SQL statements will be committed un
til you call the method commit explicitly | Both 1 and 2 are true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block. Assuming the JVM doesn t crash and the code
does not execute a System.exit() call, under what circumstances will the finall
y block not begin to execute? | If the JVM doesn't crash and the code does not e
xecute a System.exit() call,the finally block will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? | Cl
ass loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? | Compilation takes
slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B.Of thes
e, only class C implements java.io.Externalizable. Which of the following must b
e true in order to avoid an exception during deserialization of an instance of C
? | C must have a no-args constructor.
Suppose class A extends Object; class B extends A; and class C extends B.
Of these, only class C implements java.io.Serializable. Which of the following m
ust be true in order to avoid an exception during deserialization of an instance
of C? | B must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? | private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby s version of the method have? | public;protected
void doSomething(int a, float b) { } | public void doSomething(int a, float b) {
}
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods. Which are true? | The class will compile if it is declared abstra
ct;The class may not be instantiated.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? | All
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? | for (float f
:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? | When the type of x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? | if (x == y)
Suppose you are writing a class that will provide custom deserialization.The cla
ss implements java.io.Serializable (not java.io.Externalizable). What access mod
e should the readObject() method have? | private
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have? | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? | Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one statement is true abou
t this strategy? | The strategy fails because you cannot add static methods to a
subclass.
Swing components cannot be combined with AWT components. | True
The____class is the primary class that has the driver information. | DriverManag
er
The____class is used to implement a pull-down menu that provides a number of ite
ms to select from. | Menu
The element method alters the contents of a Queue. | False
The Swing component classes can be found in the package. | javax.swing
There are two classes in Java to enable communication using datagrams namely. |
DataPacket and DataSocket
whatsMyType = !s; | There are no possible legal types.
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? | There is no difference; the rules are the same.
What is the range of values that can be assigned to a variable of type byte? | -
2^7 through 2^7 - 1
What is the range of values that can be assigned to a variable of type short? |
-2^15 through 2^15 - 1
What is the return type of the instanceof operator? | A boolean
System.out.println("value is " + ((x > 4) ? 99.99 : 9)); | The output: value is
9.0
When a byte is added to a char, what is the type of the result? | int
When a negative byte is cast to a long, what are the possible values of the resu
lt? | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? | All
When a short is added to a float, what is the type of the result? | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? | writing a line separator to the strea
m
When does an exception's stack trace get recorded in the exception object? | Whe
n the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? | When the
exception is being thrown in response to catching of a different exception type
When is it appropriate to write code that constructs and throws an error? | Neve
r
When is x & y an int? | Sometimes
When the user attempts to close the frame window,_____event in generated. | wind
ow closing
When the user selects a menu item,_____event is generated. | Action event
When you compile a program written in the Java programming language,the compiler
converts the human-readable source file into platform- independent code that a
Java Virtual Machine can understand. What is this platform-independent code call
ed? | Bytecode
Whenever a method does not want to handle exceptions using the try block, the___
_is used. | Throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database? | String url ="jdbc:odbc:data_source_name"; Connection co
n = DriverManager.getConnection (url, user", "password");
Which class and static method can you use to convert an array to a List? | Array
s.asList
Which is four-step approach to help you organize your GUI thinking. | Identify n
eeded components.Isolate regions of behavior. Sketch the GUI.Choose layout manag
ers.
Which is the four steps are used in working with JDBC? | 1)Connect2)Create3)Look
4)Close
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed? | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? | sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? | class Man { private Dog bestFriend; }
Which methods return an enum constant s name? | name();toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? | Transient
Which of the following are legal argument types for a switch statement? | Byte;I
nt;Char
Which of the following are legal enums? | enum Animals { LION, TIGER, BEAR }
Which of the following classes implement java.util.List? | ArrayList;Stack
Which of the following classes implements a FIFO Queue? | LinkedList
Which of the following interfaces does not allow duplicate objects? | Set
Which of the following is not appropriate situations for assertions? | Precondit
ions of a public method
Which of the following is the most appropriate way to handle invalid arguments i
n a public method? | Throw java.lang.IllegalArgumentException.
Which of the following may appear on the left-hand side of an instanceof operato
r? | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? | A class; An interface
Which of the following may be declared final? | Classes;Methods
Which of the following may be statically imported? | Static method names;Static
field names
Which of the following may follow the static keyword? | Data;Methods;Code blocks
enclosed in curly brackets
Which of the following may not be synchronized? | Classes
Which of the following methods in the Thread class are deprecated? | suspend() a
nd resume()
Which of the following operations might throw an ArithmeticException? | /
Which of the following operators can perform promotion on their operands?
Which of the following restrictions apply to anonymous inner classes? | They mus
t be defined inside a code block.
Which of the following should always be caught? | Checked exceptions
Which of the following statements about the wait() and notify() methods is true?
| The thread that calls wait() goes into the monitor s pool of waiting threads.
Which of the following statements about threads is true? | Threads inherit their
priority from their parent thread.
Which of the following statements are true? 1)An abstract class may not have any
final methods. 2)A final class may not have any abstract methods. | Only statem
ent 2
Which of the following statements is correct? | Both primitives and object refer
ences can be both converted and cast.
Which of the following statements is true? | Object references can be converted
in both method calls and assignments,and the rules governing these conversions a
re identical.
Unicode characters are all 16 bits. | True
StringBuffer s1 = new StringBuffer("FPT"); | Compilation succeeds. No exception
is thrown during execution.
String s1 = "abc" + "def"; | Line 6 executes and line 4 does not.
Greebo g = new Greebo(); | There will be a compiler error, because class Greebo
does not correctly implement the Runnable interface.
case 2 + 1: | The output would be the text value is two followed by the text val
ue is three.
Which statements about JDBC are NOT true? | Java database;Java API for connecti
ng
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? | Map;Collection
1. File f1 = new File("dirname"); | No directory is created, and no file is crea
ted.
is a set of java API for executing SQL statements | JDBC
method is used to wait for a client to initiate communications | accept()
drivers that are written partly in the Java programming language and partly in n
ative code. These drivers use a native client library specific to the data sourc
e to which they connect | Type 2
drivers that are pure Java and implement the network protocol for a specific dat
a source. The client connects directly to the data source | Type 4
drivers that use a pure Java client and communicate with a middleware server usi
ng a database-independent protocol. The middleware server then communicates the
client's requests to the data source | Type 3
drivers that implement the JDBC API as a mapping to another data access API, suc
h as ODBC. Drivers of this type are generally dependent on a native library, whi
ch limits their portability | Type 1
System.out.println(a.doit(4, 5)) | Line 26 prints a to System.out
Which two are true if a NullPointerException is thrown on line 3 of class C | co
de on line 29, The exception
What lines are output if the constructor at line 3 throws a MalformedURLExceptio
n | Bad URL, Doing finally, Carrying
What lines are output if the methods at lines 3 and 5 complete successfully with
out throwing any exceptions | Success, Doing, Carrying
If lines 24, 25 and 26 were removed, the code would compile and the output would
be 1 | 3.The code, would be 1, 2
An exception is thrown at runtime | An exception
first second first third snootchy 420 | third second first snootchy 420
dialog prevents user input to other windows in the application unitl the dialog
is closed | Modal
You would like to write code to read back the data from this file. Which solutio
ns will work | 2.FileInputStream, RandomAccessFile
A Java monitor must either extend Thread or implement Runnable | F
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1 | You cannot specify
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these ways | public void logIt(
String... msgs)
A signed data type has an equal number of non-zero positive and negative values
available | F
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread | F
catch (InterruptedException e) | running some time
object is used to submit a query to a database | Statement
object is uses to obtain a Connection to a Database | DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b | x13, a7, b8
Yen and Euro both return correct Country value | 2.Euro returns, error at line
25
BigOlLongStringWithMeaninglessName | tick all
Compilation of class A will fail. Compilation of class B will succeed | B fail,
A succeed
Line 46 will compile if enclosed in a try block, where TestException is caught |
2.if the enclosing, is caught
Holder h = new Holder() | 101
Decrementer dec = new Decrementer() | 12.3
Test t = (new Base()).new Test(1) | 2.new Test(1), new Test(1, 2)
Base(int j, int k, int l) | 2.Base(), Base(int j, int k)
Line 12 will not compile, because no version of crunch() takes a char argument |
output: int version
output results when the main method of the class Sub is run | Value 5 This value
6
Float floater = new Float(3.14f) | Line 6
The application must be run with the -enableassertions flag or another assertion
enabling flag | dai nhat, one or more
After line 3 executes, the StringBuffer object is eligible for garbage collectio
n | line 2 executes..collection
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | type SwampThing
The code will compile and run, but the cast in line 6 is not required and can be
eliminated | The code will compile and run
for (int i = 0; i < 2; i++) | 4.i0,j12 - i1,j02
outer: for (int i = 0; i < 2; i++) | i = 1 j = 0
The code will compile but will throw an exception at line 7, because runtime con
version from an interface to a class is not permitted | Line 7 will not compile
int[] x = new int[25] | 2.x[24]=0, x.length is 25
public float aMethod(float a, float b) throws Exception | int a,b float p,q
public float aMethod(float a, float b, int c) throws Exception | 3.int a,b. floa
t a,b-int c. private
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string | None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i | Arrays.equals(a1, a2)
Assuming the class does not perform custom serialization, which fields are writt
en when an instance of Xyz is serialized | 3.Public, Private, Volatile
can legally be placed before aMethod() on line 3 and be placed before aMethod()
on line 8 | 3: private; 8: protected
NUTMEG, CINNAMON, CORIANDER, ROSEMARY | 3.Spice sp, Spice, String
List<String> names = new ArrayList<String>() | 2.Iterator, for
Compilation fails because of an error in line 15 | error in line 19
1 2 3 | 2 3
public interface B inheritsFrom A | B extends A
protected double getSalesAmount() { return 1230.45; } | 2.public, protected
Line 16 creates a directory named d and a file f within it in the file system | 3.An
exception, Line 13, line 14
Nav.Direction d = Nav.Direction.NORTH | Nav.Direction.NORTH
new class Foo { public int bar() { return 1; } } | new Foo()
IllegalArgumentException | StackOverflowError
Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw() | Shape s = ne
w Circle...s.draw()
Compilation fails because of an error in line 12 | 1 2 3
NullPointerException | Compilation fails
A NumberFormatException is thrown by the parse method at runtime | Compilation f
ails
An exception is thrown at runtime | Compilation fails
passed An AssertionException is thrown without the word stuff added to the stack t
race | An AssertionError...with the
collie | collie harrier
doStuff x = 6 main x = 6 | doStuff x =5 main x =5
The setCardlnformation method breaks encapsulation | The ownerName
The value of all four objects prints in natural order | Compilation fails...line
29
The code on line 33 executes successfully | 3.33 throws, 35 throws, 33 executes
What is the result if a NullPointerException occurs on line 34 | ac
Compilation will fail because of an error in line 55 | Line 57...value 3
java -ea test file1 file2 | 2.java -ea test, dai nhat
String s = 123456789 ; s = (s- 123 ).replace(1,3, 24 ) - 89 | 2.delete(4,6), delete(2,5)
rt( 1, 24 )
The Point class cannot be instatiated at line 15 | Line.Point p = new Line.Point
()
for( int i=0; i< x.length; i++ ) System.out.println(x[i]) | 2.for(int z : x),
dai nhat
int MY_VALUE = 10 | 3.final, static, public
Compilation fails because of an error in line: public void process() throws Runt
imeException | A Exception
How can you ensure that multithreaded code does not deadlock | There is no singl
e
How can you force garbage collection of an object | Garbage collection
How do you prevent shared data from being corrupted in a multithreaded environme
nt | Access the variables
How do you use the File class to list the contents of a directory | String[] con
tents
The number of bytes depends on the underlying system | 8
How many locks does an object have | One
If all three top-level elements occur in a source file, they must appear in whic
h order | Package declaration, imports
the two classes are in different packages, and class X has a protected method ca
lled abby(), then any instance of Y may call the abby() method of any | F
TestThread3 ttt = new TestThread3 | Y
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use | TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method | Comparable...compareTo
after execution of line 1, sbuf references an instance of the StringBuffer class
. After execution of line 2, sbuf still references the same instance | T
what are the possible types for variable result | int, long, float, double
helps manage the connection between a Java program and a database | Connection
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances | Y
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks | Y
JDBC supports ______ and ______ models | Two-tier and three-tier
MVC is short call of | Model-View-Controller
No output because of compile error at line: System.out.println("b="+b) | b = b *
b1
Object ob2= new Object() | Have a nice day
Object ob2= ob1 | ob1 equals ob2, ob1==ob2
String s2 = "xyz" | Line 4, Line 6
String s2 = new String("xyz") | Line 6
String s2 = new String(s1) | Line 6
Select correct statement about RMI | All the above
Select correct statement(s) about remote class | All the others choices
Select correct statements about remote interface | All the others choices
Select INCORRECT statement about serialization | When an Object Output
Select INCORRECT statement about deserialize | We use readObject
Select incorrect statement about RMI server | A client accesses
Select incorrect statement about ServerSocket class | To make the new object
Select incorrect statement about Socket class | server through UDP
Select the correct statement about JDBC two-tier processing model | A user's com
mands
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query | WHERE
Statement objects return SQL query results as | ResultSet
When a JDBC connection is created, it is in auto-commit mode | Both 1 and 2 are
true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block | If the JVM doesn't crash
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class | no
additional time
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file | slightly more time
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable | C must have a
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable | B must have a
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething() | private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething() | 2.public, protec
ted
void doSomething(int a, float b) | public...(int a, float b)
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods | 2.declared abstract, may not be
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements | All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries | for (float f:
salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal | When the...x is Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal | Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant | if (x == y)
Suppose you are writing a class that will provide custom deserialization. What a
ccess mode should the readObject() method have | private
Suppose you are writing a class that will provide custom serialization. What acc
ess mode should the writeObject() method have | private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality | Override run()
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods | subclass java.lang.Math
Swing components cannot be combined with AWT components | T
class is the primary class that has the driver information | DriverManager
class is used to implement a pull-down menu that provides a number of items to s
elect from | Menu
The element method alters the contents of a Queue | F
The Swing component classes can be found in the | javax.swing
There are two classes in Java to enable communication using datagrams namely | D
ataPacket and DataSocket
Compilation of Parrot.java fails at line 7 because method getRefCount() is stati
c in the superclass, and static methods may not be overridden to be nonstatic |
dai nhat: nonstatic
Compilation of Nightingale will succeed, but an exception will be thrown at line
10, because method fly() is protected in the superclass | The program...After:
2
void doSomething() throws IOException, EOFException | ngan-dai nhat, throws EOFE
xception
URL referring to databases use the form | protocol:subprotocol:datasoursename
What are the legal types for whatsMyType | There are no possible legal types
What does the following code do | Throws an exception
There is no output because the code throws an exception at line 1 | output is i
= 20
1000 | -1
What happens when you try to compile and run the following application | thrown
at line 9
The code compiles, and prints out >>null<< | out >>null<<
An exception is thrown at line 6 | thrown at line 7
What is -50 >> 2 | -13
What is 7 % -4 | 3
What is -8 % 5 | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion | There is no difference
The code will compile as is. No modification is needed | On line 1, remove
What is the range of values that can be assigned to a variable of type byte | ?2
mu7 through 2mu7 ? 1
What is the range of values that can be assigned to a variable of type short | ?
2mu15 through
The code compiles and executes; afterward, the current working directory contain
s a file called datafile | The code fails to compile
What is the return type of the instanceof operator | A boolean
What method of the java.io.File class can create a file on the hard drive | crea
teNewFile()
The output: value is 99.99 | value is 9.0
The output: b contains 250 | b contains 5
What would be the output from this code fragment | message four
When a byte is added to a char, what is the type of the result | int
When a negative byte is cast to a long, what are the possible values of the resu
lt | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt | All the above
When a short is added to a float, what is the type of the result | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two | writing a line
When does an exception's stack trace get recorded in the exception object | is c
onstructed
When is it appropriate to pass a cause to an exception's constructor | in respon
se to catching
When is it appropriate to write code that constructs and throws an error | Never
When is x & y an int | Sometimes
When the user attempts to close the frame window, _______ event in generated | w
indow closing
When the user selects a menu item, _______ event is generated | Action event
Java programming language, the compiler converts the human-readable source file
into platform-independent code that a Java Virtual Machine can understand | byte
code
Whenever a method does not want to handle exceptions using the try block, the |
throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database | String url =jdbc:odbc
Which class and static method can you use to convert an array to a List | Arrays
.asList
Which is four-step approach to help you organize your GUI thinking | Identify, I
solate, Sketch
Which is the four steps are used in working with JDBC | Connect, Create, Look
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r | sc.useDelimiter("\\d")
Man has the best friend who is a Dog | private Dog bestFriend
Which methods return an enum constant s name | 2.name(), toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state | transient
Which of the following are legal argument types for a switch statement | 3.byte,
int, char
Which of the following are legal enums | 3.ngan-dai nhat, lion int weight
Which of the following are legal import statements | 2.import...Vector, Vector.*
Which of the following are legal loop constructions | for (int k=0, j+k != 10; j
++,k++)
Which of the following are legal loop definitions | None of the above
double d = 1.2d5 | 2.double d = 1.2d, 1.2D
int d = 0XABCD | 2.int c = 0xabcd, dai nhat
char c = 0x1234 | 2.0x.., '\u1234'
Vector <String> theVec = new Vector<String>() | 2.List...<String>(), dai nhat
Which of the following are methods of the java.util.SortedMap interface | headMa
p, tailMap, subMap
Which of the following are methods of the java.util.SortedSet interface | All th
e above
System.out has a println() method | All the above
The JVM runs until there is only one non-daemon thread | are no non-daemon
When an application begins running, there is one non-daemon thread, whose job is
to execute main() | 3.nhat, thread, non-daemon thread
When you declare a block of code inside a method to be synchronized, you can spe
cify the object on whose lock the block should synchronize | 2.the method always
, nhat
An enum definition should declare that it extends java.lang.Enum | 2.contain pub
lic, private
Primitives are passed by reference | 2.by value
An anonymous inner class that implements several interfaces may extend a parent
class other than Object | implement at most, class may extend
Which of the following are valid arguments to the DataInputStream constructor |
FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or | All the above
Which of the following calls may be made from a non-static synchronized method |
All the above
Which of the following classes implement java.util.List | 2.ArrayList, Stack
Which of the following classes implements a FIFO Queue | LinkedList
Which of the following declarations are illegal | 3.ngan-dai nhat, double d
int x = 6; if (!(x > 3)) | 2.dai nhat, x = ~x
String x = "Hello"; int y = 9; if (x == y) | 2.ngan nhat, x=x+y
Which of the following expressions results in a positive value in x | int x = 1;
x = x >>> 5
Which of the following interfaces does not allow duplicate objects | Set
Which of the following is not appropriate situations for assertions | Preconditi
ons of a public method
Which of the following is NOTa valid comment | /* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method | IllegalArgumentException
Readers have methods that can read and return floats and doubles | None of the a
bove
An enum definition may contain the main() method of an application | All the abo
ve
Which of the following may appear on the left-hand side of an instanceof operato
r | A reference
Which of the following may appear on the right-hand side of an instanceof operat
or | 2.A class, An interface
Which of the following may be declared final | 2.Classes, Methods
Which of the following may be statically imported | 2.Static method, Static fiel
d
Which of the following may follow the static keyword | 3.Data, Methods, Code blo
cks
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation | All of
Which of the following may not be synchronized | Classes
Which of the following may override a method whose signature is void xyz(float f
) | 2.void, public void xyz(float f)
Which of the following methods in the Thread class are deprecated | suspend() an
d resume()
Which of the following operations might throw an ArithmeticException | None of
Which of the following operators can perform promotion on their operands | 3.con
g, tru, xap xi
Which of the following restrictions apply to anonymous inner classes | must be d
efined
Which of the following should always be caught | Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application | 2.static void...(String arg[])
Which of the following statements about the wait() and notify() methods is true
| calls wait() goes into
Which of the following statements about threads is true | Threads inherit their
A final class may not contain non-final data fields | may not be extended
An abstract class must declare that it implements an interface | None
An abstract class may not have any final methods | Only statement 2
Only object references are converted automatically; to change the type of a prim
itive, you have to do a cast | Both primitives
Transient methods may not be overridden | variables are not
Object references can be converted in both method calls and assignments, but the
rules governing these conversions are very different | conversions are identica
l
Bytecode characters are all 16 bits | Unicode characters
To change the current working directory, call the changeWorkingDirectory() metho
d of the File class | None
When you construct an instance of File, if you do not use the file-naming semant
ics of the local machine, the constructor will throw an IOException | None
When the application is run, thread hp1 will execute to completion, thread hp2 w
ill execute to completion, then thread hp3 will execute to completion | None of
Compilation succeeds, although the import on line 1 is not necessary. During exe
cution, an exception is thrown at line 3 | fails at line 2
Compilation fails at line 1 because the String constructor must be called explic
itly | succeeds. No exception
Line 4 executes and line 6 does not | Line 6 executes
There will be a compiler error, because class Greebo does not correctly implemen
t the Runnable interface | Runnable interface
The acceptable types for the variable j, as the argument to the switch() constru
ct, could be any of byte, short, int, or long | value is three
The returned value varies depending on the argument | returns 0
Lines 5 and 12 will not compile because the method names and return types are mi
ssing | output x = 3
Line 13 will not compile because it is a static reference to a private variable
| output is x = 104
Which statements about JDBC are NOT true | 2.database system, DBMS
Which two code fragments correctly create and initialize a static array of int
elements | 2.a = { 100,200 }, static
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework | 2.Map, Collection
A new directory called dirname and a new file called filename are created, both
in the current working directory | No directory
protected class Cat extends Owner | public class Cat extends Pet
Date vaccinationDue | 2.boolean, String
What is -15 % -10 | -5
command line on a Windows system | 2.must contain the statement, the file
The string created on line 2 does not become eligible for garbage collection in
this code | After line 3
When the application runs, what are the values of n and w.x after the call to bu
mp() in the main | n is 10, w.x is 11
The addAll() method of that interface takes a single argument, which is a ref
erence to a collection whose elements are compatible with E. What is the declar
ation of the addAll() method | addAll(Collection<? extends E> c)
If you want a vector in which you know you will only store strings, what are the
advantages of using fancyVec rather than plainVec | Attempting to...compiler er
ror
When should objects stored in a Set implement the java.util.Comparable interfac
e | Set is a TreeSet
What relationship does the extends keyword represent | is a
class bbb.Bbb, which extends aaa.AAA, wants to override callMe(). Which access m
odes for callMe() in aaa.AAA will allow this | 2.public, protected
Lemon lem = new Lemon(); Citrus cit = new Citrus() | 3.cit = lem, cit=(Citrus),
lem=(lemon)
it also has a method called chopWoodAndCarryWater(), which just calls the other
two methods | inappropriate cohesion, inappropriate coupling
sharedOb.wait() | 2.aThread.interrupt, sharedOb.notifyAll
line prints double d in a left-justified field that is 20 characters wide, with
15 characters to the right of the decimal point | System.out.format("%-20.15f",
d)
What code at line 3 produces the following output | String delim = \\d+
How do you generate a string representing the value of a float f in a format a
ppropriate for a locale loc | NumberFormat.getInstance(loc)
you want to use a DateFormat to format an instance of Date. What factors influ
ence the string returned by DateFormat s format() method | 2.LONG, or FULL, The lo
cale
you want to create a class that compiles and can be serialized and deserialized
without causing an exception to be thrown. Which statements are true regarding
the class | 2.dai nhat, ngan nhat
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
What interfaces can be implemented in order to create a class that can be serial
ized | 2.dai nhat, ngan nhat
The file contains lines of 8-bit text, and the 8-bit encoding represents the lo
cal character set, as represented by the cur- rent default locale. The lines are
separated by newline characters | FileReader instance
shorty is a short and wrapped is a Short | all
How is IllegalArgumentException used | 2.certain methods, public methods
While testing some code that you are developing, you notice that an ArrayIndexO
utOf- BoundsException is thrown. What is the appropriate reaction | None
Which lines check that x is equal to four? Assume assertions are enabled at com
pile time and runtime | 2.assert x == 4
int[] ages = { 9, 41, 49 }; int sum = 0 | 2.i<ages.length, for (int i:ages)
Which of the following types are legal arguments of a switch statement | enums,
bytes
class A extends java.util.Vector { private A(int x) | does not create a defau
lt
void callMe(String names) | method, names is an array
Given a class with a public variable theTint of type Color, which of the followi
ng methods are consistent with the JavaBeans naming standards | public Color ge
tTheTint()
are valid arguments to the DataInputStream constructor | FileInputStream
are valid mode strings for the RandomAccessFile constructor | r, rw, rws, rwd
method of the java.io.File class can create a file on the hard drive | createNe
wFile()
class A extends Object; Class B extends A; and class C extends B. Of these, only
class C implements java.io.Externalizable | C must have
class A extends Object; class B extends A; and class C extends B. Of these, only
class C implements java.io.Serializable | B must have
you are writing a class that will provide custom deserialization. The class impl
ements java.io.Serializable (not java.io.Externalizable) | private
you are writing a class that will provide custom serialization. The class implem
ents java.io.Serializable (not java.io.Externalizable) | private
How do you use the File class to list the contents of a directory | String[] c
ontents = myFile.list();
call returns true if a1 and a2 have the same length, and a1[i].equals(a2[i]) fo
r every legal index i | java.util.Arrays.equals(a1, a2)
line of code tells a scanner called sc to use a single digit as a delimiter | sc
.useDelimiter( \\d )
you want to write a class that offers static methods to compute hyperbolic trigo
nometric functions. You decide to subclass java.lang.Math and provide the new f
unctionality as a set of static methods | java.lang.Math
Given a string constructed by calling s = new String( xyzzy ), which of the calls mo
difies the string | none
Suppose you want to create a custom thread class by extending java.lang.Thread
in order to provide some special functionality. Which of the following must you
do | Override run()
you prevent shared data from being corrupted in a multithreaded environment | Ac
cess the variables
Is it possible to write code that can execute only if the current thread owns
multiple locks | yes
Which of the following may not be synchronized | Classes
statements about the wait() and notify() methods is true | pool of waiting th
reads
methods in the Thread class are deprecated | suspend() and resume()
A Java monitor must either extend Thread or implement Runnable | F
One of the threads is thr1. How can you notify thr1 so that it alone moves from
the Waiting state to the Ready state | You cannot specify
A thread wants to make a second thread ineligible for execution. To do this,
the first thread can call the yield() method on the second thread | F
Which methods return an enum constant s name | name(), toString()
restrictions apply to anonymous inner classes | inside a code block
A pet has an owner, a registration date, and a vaccination-due date. A cat is a
pet that has a flag indicating whether it has been neutered, and a textual d
escription of its markings | boolean, string
Which of the following are valid declarations? Assume java.util | 1Vector 2Set 3
Map string,string
You can determine all the keys in a Map in which of the following ways | Set ob
ject from the Map
What keyword is used to prevent an object from being serialized | transient
abstract class can contain methods with declared bodies. | E. public, protecte
d, default, private
access modifier allows you to access method calls in libraries not created in J
ava | native
Which of the following statements are true? (Select all that apply.) | object c
annot reassigned
The keyword extends refers to what type of relationship | is a
keywords is used to invoke a method in the parent class | super
What is the value of x after the following operation is performed | 3
method call is used to tell a thread that it has the opportunity | notify()
Assertions are used to enforce all but which | Exceptions
force garbage collection by calling System.gc(). | B. False
Select the valid primitive data type | 1.boolean 2.char 3.float
How many bits does a float contain | 32
What is the value of x after the following line is executed | 32
StringBuffer is slower than a StringBuilder, but a StringBuffer | True
list of primitives ordered in smallest to largest bit size representation | D.
char, int, float, long
Which class provides locale-sensitive text formatting for date and time informat
ion | java.text.DateFormat
int x = 9; byte b = x | False
Which of the following code snippets compile | 1.Integer 2.Integer 3.byte
Java arrays always start at index 1 | False
accurately describes how variables are passed to methods | that are primitive t
ype are passed by value
change the value that is encapsulated by a wrapper class after you have instan
| None of the above.
The class implements java.io.Serializable (and not java.io.Externalizable) | pri
vate readObject
A signed data type has an equal number of non-zero positive and negative value
s | False
signatures are valid for the main() method entry point of an application | publi
c static void main(String[] args)
three top-level elements occur in a source file, they must appear | Package decl
aration, imports, class/interface/enum definitions
int[] x = new int[25] | x[24] is 0 and x.length is 25
How can you force garbage collection of an object | Garbage collection cannot
be forced.
range of values that can be assigned to a variable of type short | -215 through
215 - 1
range of values that can be assigned to a variable of type byte | -27 through 2
7 - 1
How do the imports affect the time required to compile the source file | Compi
lation takes slightly more time
How do the imports affect the time required to load the class? | Class loading
takes no additional time
legal import statements | 1.import java.util.Vector 2.import static java.ut
il.Vector
may be statically imported | 1.Static method names 2.Static field names
int c = 0xabcd and int d = 0XABCD | 2 dap an
double d = 1.2d and double d = 1.2D | 2 dap an
char c = \u1234 | 1 dap an
passed by value and passed by value | 2 dap an
int x = 6; if (!(x > 3)) and int x = 6; x = ~x | 2 dap an
int x = 1; x = x >>> 5 | 1 dap an
int y = 9; x += y; and int y = 9; x = x + y; | 2 dap an
What is -8 % 5 | -3
What is 7 % -4? | 3
ob1 == ob2 | No
When a byte is added to a char | int
When a short is added to a float | float
ArithmeticException | 1.None of these 2./
What is the return type of the instanceof operator | boolean
may appear on the left-hand side of an instanceof operator | reference
may appear on the right-hand side of an instanceof operator | class and interfa
ce
What is -50 >> 1 | -25
default String s ,, abstract double d ,, double hyperbolic | 3 dap an
A final class may not have any abstract methods | true
denote a variable that should not be written out as part of its class s persistent
state | transient
Both primitives and object references can be both converted and cast | dap an
and the rules governing these conversions are identical | dap an
may legally appear as the new type (between the parentheses) in a cast operati
on | All of the above
type of x is a class, and the declared type of y is an interface. When is the as
signment x = y | When the type of x is Object
xarr is an array of XXX, and the type of yarr is an array of YYY | Sometimes
When is x & y an int | Sometimes
negative long is cast to a byte | All of the above
negative byte is cast to a long | Negative
operators can perform promotion on their operands | + - ~(nga)
difference between the rules for method-call conversion and the rules for assign
ment conversion | There is no difference
Which of the following are appropriate situations for assertions | DAP AN SAI :
Preconditions of a public method
appropriate way to handle invalid arguments in a public method | IllegalArgumen
tException
Suppose salaries is an array containing floats | for (float f:salaries)
Suppose a method called finallyTest() consists of a try block | If the JVM does
n t crash and
appropriate to pass a cause to an exception s constructor | thrown in response to
catching of a different exception type
Which of the following should always be caught | Checked exceptions
When does an exception s stack trace get recorded in the exception object | is con
structed
2. You can determine all the keys in a Map in which of the following ways?
| A. By getting a Set object from the Map and iterating through it.
3. What keyword is used to prevent an object from being serialized? | D.
transient
4. An abstract class can contain methods with declared bodies. | A.
True
5. Select the order of access modifiers from least restrictive to most rest
rictive. | E. public, protected, default, private
6. Which access modifier allows you to access method calls in libraries no
t created in Java? | C. native
7. Which of the following statements are true? (Select all that apply.) |
D. A final object cannot be reassigned a new address in memory
8. The keyword extends refers to what type of relationship? | A. is a
9. Which of the following keywords is used to invoke a method in the pare
nt class? | B. super
12. What is the value of x after the following operation is performed? x =
23 % 4; | D. 3
14. What method call is used to tell a thread that it has the opportunity
to run? | B. notify()
16. Assertions are used to enforce all but which of the following? | C.
Exceptions
17. The developer can force garbage collection by calling System.gc(). | B.
False
18. Select the valid primitive data types. (Select all that apply.) | A.
boolean and char and float
19. How many bits does a float contain? | 3
20. What is the value of x after the following line is executed? x = 32 *
(31 - 10 * 3); | A. 32
21. A StringBuffer is slower than a StringBuilder, but a StringBuffer is thr
eadsafe | A. True
22. Select the list of primitives ordered in smallest to largest bit size r
epresentation. | D. char, int, float, long
23. Which class provides locale-sensitive text formatting for date and time
information? | D. java.text.DateFormat
24. The following line of code is valid. int x = 9; byte b = x; | B.
False
27. Java arrays always start at index 1 | B. False
28. Which of the following statements accurately describes how variables a
re passed to methods? | C. Arguments that are primitive type are passed by
value
29. How do you change the value that is encapsulated by a wrapper class af
ter you have instan- tiated it? | D. None of the above
30. Suppose you are writing a class that provides custom deserialization. Th
e class implements java.io.Serializable (and not java.io.Externalizable). What m
ethod should imple- ment the custom deserialization, and what is its access mod
e? | A. private readObject
1. A signed data type has an equal number of non-zero positive and negati
ve values available | B. False
4. If all three top-level elements occur in a source file, they must appear
in which order? | D. Package declaration, imports, class/interface/enum defi
nitions.
8. How can you force garbage collection of an object? | A. Garbage collect
ion cannot be forced.
10. What is the range of values that can be assigned to a variable of type b
yte? | D. -27 through 27 - 1
11. Suppose a source file contains a large number of import statements. How
do the imports affect the time required to compile the source file? | B.
Compilation takes slightly more time
12. Suppose a source file contains a large number of import statements an
d one class definition. How do the imports affect the time required to load th
e class? | A. Class loading takes no additional time
18. Which of the following are legal? | C. char c = \u1234 ;
3. Which of the following expressions results in a positive value in x? |
A. int x = 1; x = x >>> 5;
5. What is -8 % 5? | A. -3
13. When a short is added to a float, what is the type of the result? | C.
float
15. Which of the following operations might throw an ArithmeticException? |
D. None of these
19. Which of the following may appear on the right-hand side of an instanceo
f operator? | B. A class C. An interface
20. What is -50 >> 1? | D. -25
2. Which of the following statements is true? | B. A final class ma
y not have any abstract methods.
4. Which of the following statements is true? | E. Transient variab
les are not serialized.
8. Which modifier or modifiers should be used to denote a variable that sho
uld not be written out as part of its class s persistent state? | D. transien
t
11. Suppose class Supe, in package packagea, has a method called doSomething
(). Suppose class Subby, in package packageb, overrides doSomething(). What ac
cess modes may Subby s version of the method have? | A. public B. protecte
d
13. Suppose interface Inty defines five methods. Suppose class Classy decla
res that it implements Inty but does not provide implementations for any of the
five interface methods. Which is/are true? | C. The class will compile if it is
declared abstract D. The class may not be instantiated.
17. True or false: If class Y extends class X, the two classes are in differ
ent packages, and class X has a protected method called abby(), then any insta
nce of Y may call the abby() method of any other instance of Y. | B. False
18. Which of the following statements are true? | D. A final class ma
y not be extended.
1. Which of the following statements is correct? | D. Both primitives
and object references can be both converted and cast.
6. Which of the following statements is true? | D. Object reference
s can be converted in both method calls and assignments, and the rules govern
ing these conversions are identical.
11. Which of the following may legally appear as the new type (between the
parentheses) in a cast operation? | E. All of the above
12. Which of the following may legally appear as the new type (between the
parentheses) in a cast operation? | D. All of the above
13. Suppose the declared type of x is a class, and the declared type of y is
an interface. When is the assignment x = y; legal? | A. When the type of
x is Object
14. Suppose the type of xarr is an array of XXX, and the type of yarr is an
array of YYY. When is the assignment xarr = yarr; legal? | A. Sometimes
15. When is x & y an int? | B. Sometimes
16. What are the legal types for whatsMyType? short s = 10; whatsMyType = !
s; | C. There are no possible legal types.
17. When a negative long is cast to a byte, what are the possible values of
the result? | D. All of the above
18. When a negative byte is cast to a long, what are the possible values of
the result? | C. Negative
20. What is the difference between the rules for method-call conversion and
the rules for assignment conversion? | A. There is no difference; the rule
s are the same.
11. Which of the following is the most appropriate way to handle invalid arg
uments in a public method? | B. Throw java.lang.IllegalArgumentExceptio
n.
14. Suppose a method called finallyTest() consists of a try block, followed
by a catch block, followed by a finally block. Assuming the JVM doesn t crash and
the code does not execute a System.exit() call, under what circumstances will
the finally block not begin to execute? | D. If the JVM doesn t crash and the c
ode does not execute a System.exit() call, the finally block will always execute
.
17. When is it appropriate to pass a cause to an exception s constructor? | B.
When the exception is being thrown in response to catching of a different excep
tion type
18. Which of the following should always be caught? | B. Checked exceptio
ns
19. When does an exception s stack trace get recorded in the exception objec
t? | A. When the exception is constructed
20. When is it appropriate to write code that constructs and throws an erro
r? | E. Never
14. Suppose x and y are of type TrafficLightState, which is an enum. What is
the best way to test whether x and y refer to the same constant? | A. if (x ==
y)
15. Which of the following restrictions apply to anonymous inner classes? |
A. They must be defined inside a code block.
18. Which methods return an enum constant s name? | B. name() C.
toString()
5. A monitor called mon has 10 threads in its waiting pool; all these waiti
ng threads have the same priority. One of the threads is thr1. How can you not
ify thr1 so that it alone moves from the Waiting state to the Ready state? | E.
You cannot specify which thread will get notified.
8. Which of the following methods in the Thread class are deprecated? | A.
suspend() and resume()
9. Which of the following statements about threads is true? | B.
Threads inherit their priority from their parent thread.
10. Which of the following statements about the wait() and notify() method
s is true? | C. The thread that calls wait() goes into the monitor s poo
l of waiting threads.
11. Which of the following may not be synchronized? | D. Classes
13. How many locks does an object have? | A. One
14. Is it possible to write code that can execute only if the current threa
d owns multiple locks? | A. Yes
16. Which of the following are true? | D. The JVM runs until there are no
non-daemon threads.
17. How do you prevent shared data from being corrupted in a multithreaded e
nvironment? | D. Access the variables only via synchronized methods.
18. How can you ensure that multithreaded code does not deadlock? | D.
A, B, and C do not ensure that multithreaded code does not deadlock.
20. Suppose you want to create a custom thread class by extending java.lan
g.Thread in order to provide some special functionality. Which of the following
must you do? | B. Override run().
3. Suppose you want to write a class that offers static methods to compute
hyperbolic trigonometric functions. You decide to subclass java.lang.Math and p
rovide the new functionality as a set of static methods | D. The strategy fai
ls because you cannot subclass java.lang.Math.
17. Which line of code tells a scanner called sc to use a single digit as a
delimiter? | C. sc.useDelimiter( \\d );
1. Which of the statements below are true? | D. Unicode characters are a
ll 16 bits.
4. How do you use the File class to list the contents of a directory? | A.
String[] contents = myFile.list();
11. Suppose you are writing a class that will provide custom serialization.
The class implements java.io.Serializable (not java.io.Externalizable). What acc
ess mode should the writeObject() method have? | D. private
12. Suppose you are writing a class that will provide custom deserialization
. The class implements java.io.Serializable (not java.io.Externalizable). What
access mode should the readObject() method have? | D. private
13. Suppose class A extends Object; class B extends A; and class C extends B
. Of these, only class C implements java.io.Serializable. Which of the following
must be true in order to avoid an exception during deserialization of an insta
nce of C? | B. B must have a no-args constructor
14. Suppose class A extends Object; Class B extends A; and class C extends B
. Of these, only class C implements java.io.Externalizable. Which of the followi
ng must be true in order to avoid an exception during deserialization of an ins
tance of C? | C. C must have a no-args constructor.
16. What method of the java.io.File class can create a file on the hard dri
ve? | E. createNewFile()
20. Which of the following are valid arguments to the DataInputStream const
ructor? | C. FileInputStream
1. Which statements are true? | E. heights is initialized to a refe
rence to an array with zero elements.
5. Given a class with a public variable theTint of type Color, which of the
following methods are consistent with the JavaBeans naming standards? | C.
public Color getTheTint()
6. Which of the following statements are true regarding the following met
hod? void callMe(String names) { } | B. Within the method, names is an
array containing Strings.
9. Which of the following types are legal arguments of a switch statement?
| A. enums B. bytes
22. Suppose you are writing a class that will provide custom deserialization
. The class implements java.io.Serializable (not java.io.Externalizable). What
access mode should the readObject() method have? | D. private
24. Suppose you want to use a DateFormat to format an instance of Date. Wh
at factors influence the string returned by DateFormat s format() method? | C.
The style, which is one of SHORT, MEDIUM, LONG, or FULL D. The locale
25. How do you generate a string representing the value of a float f in a f
ormat appropriate for a locale loc? | A. NumberFormat nf = NumberFormat
.getInstance(loc); String s = nf.format(f);
27. Which line prints double d in a left-justified field that is 20 characte
rs wide, with 15 characters to the right of the decimal point? | D. System.o
ut.format("%-20.15f", d);
40. When should objects stored in a Set implement the java.util.Comparable
interface? | D. When the Set is a TreeSet
50. What is -15 % -10? | D. -5
1. public class A { 2. public String doit(int x, int y) { 3. return a ; 4.
} 5. 6. public String doit(int... vals) { 7. return b ; 8. } 9. } G
iven: 25. A a=new A(); 26. System.out.println(a.doit(4, 5)); What is the result?
(Choose one.) | Line 26 prints a to System.out.
1. public class A { 2. public void method1() { 3. B b=new B(); 4.
b.method2(); 5. // more code here 6. }7.} 1. public class B { 2. pub
lic void method2() { 3. C c=new C(); 4. c.method3(); 5. // mor
e code here 6. } 7.} 1. public class C { 2. public void method3() { 3.
// more code here 4. } 5.} 25. try { 26. A a=new A(); 27. a.method1
(); 28. }catch (Exception e) { 29. System.out.print( an error occurred ); 30. } W
hich two are true if a NullPointerException is thrown on line 3 of class C? (Cho
ose two.) | The code on line 29 will be executed.The exception will be propagate
d back to line 27.
______ is a set of java API for executing SQL statements. | JDBC
______ method is used to wait for a client to initiate communications.|accept()
___________ drivers that are written partly in the Java programming language and
partly in native code. These drivers use a native client library specific to th
e data source to which they connect. Again, because of the native code, their po
rtability is limited.|Type 2
____________ drivers that are pure Java and implement the network protocol for a
specific data source. The client connects directly to the data source.|Type 4
____________ drivers that use a pure Java client and communicate with a middlewa
re server using a database-independent protocol. The middleware server then comm
unicates the client's requests to the data source.|Type 3
______________ drivers that implement the JDBC API as a mapping to another data
access API, such as ODBC. Drivers of this type are generally |Type 1
1. try { 2. // assume s is previously defined 3. URL u = new URL(s);
4. // in is an ObjectInputStream 5. Object o = in.readObject(); 6.
System.out.println("Success"); 7. } 8. catch (MalformedURLException e) { 9
. System.out.println("Bad URL"); 10. } 11. catch (StreamCorruptedException
e) { 12. System.out.println("Bad file contents"); 13. } 14. catch (Except
ion e) { 15. System.out.println("General exception"); 16. } 17. finally {
18. System.out.println("Doing finally part"); 19. } 20. System.out.println
("Carrying on"); Where: IOException extends Exception StreamCorruptedE
xception extends IOException MalformedURLException extends IOException What
lines are output if the constructor at line 3 throws a MalformedURLException? (
Choose three.)|Bad URL Doing finally part Carrying on
1. try { 2. // assume s is previously defined 3. URL u = new URL(s); 4
. // in is an ObjectInputStream 5. Object o = in.readObject(); 6.
System.out.println("Success"); 7. } 8. catch (MalformedURLException e) { 9.
System.out.println("Bad URL"); 10. } 11. catch (StreamCorruptedException e) {
12. System.out.println("Bad file contents"); 13. } 14. catch (Exception e)
{ 15. System.out.println("General exception"); 16. } 17. finally { 18.
System.out.println("Doing finally part"); 19. } 20. System.out.println("Carryin
g on"); What lines are output if the methods at lines 3 and 5 complete successfu
lly without throwing any exceptions? (Choose three.)|Success Doing finally part
Carrying on
10. interface Foo { 11. int bar(); 12. } 13. 14. public class Beta { 15. 16.
class A implements Foo { 17. public int bar() { return 1; } 18.
} 19. 20. public int fubar( Foo foo) { return foo.bar(); } 21. 22.
public void testFoo() { 23. 24. class A implements Foo { 25.
public int bar() { return 2; } 26. } 27. 28.
System.out.println( fubar( new A())); 29. } 30. 31. public stati
c void main( String[] argv) { 32. new Beta().testFoo(); 33. } 34. }
Which three statements are true? (Choose three.)|The code compiles and the outpu
t is 2. If lines 16, 17 and 18 were removed, the code would compile and the outp
ut would be 2. If lines 24, 25 and 26 were removed, the code would compile and t
he output would be 1.
10. public class ClassA { 11. public void methodA() { 12. ClassB classB
= new ClassB(); 13. classB.getValue();14. } 15.} And:20. class ClassB
{ 21. public ClassC classC; 22. 23. public String getValue() { 24. r
eturn classC.getValue(); 25. }26.} And: 30. class ClassC { 31. public Stri
ng value; 32. 33. public String getValue() { 34. value = ClassB ; 35.
return value; 36. }37.} ClassA a = new ClassA(); a.methodA(); What is the
result? (Choose one.)|An exception is thrown at runtime.
11. public class Bootchy { 12. int bootch; 13. String snootch; 14. 15.
public Bootchy() { 16. this( snootchy ); 17. System.out.print( first ); 18.
} 19. 20. public Bootchy(String snootch) { 21. this(420, snootchy ); 2
2. System.out.print( second ); 23. } 24. 25. public Bootchy(int bootch,
String snootch) { 26. this.bootch = bootch; 27. this.snootch = snoo
tch; 28. System.out.print( third ); 29. } 30. 31. public static void ma
in(String[] args) { 32. Bootchy b = new Bootchy();33. System.out.pri
nt(b.snootch + + b.bootch); 34. } 35. } | third second first snootchy 420
A _____ dialog prevents user input to other windows in the application unitl the
dialog is closed.|Modal
A file is created with the following code: 1. FileOutputStream fos = new FileOut
putStream("datafile"); 2. DataOutputStream dos = new DataOutputStream(fos); 3. f
or (int i=0; i<500; i++) 4. dos.writeInt(i); You would like to write code t
o read back the data from this file. Which solutions will work? (Choose two.) |
Construct a FileInputStream, passing the name of the file. Onto the FileInputStr
eam, chain a DataInputStream, and call its readInt() method. Construct a RandomA
ccessFile, passing the name of the file. Call the random access file s readInt() m
ethod.
A Java monitor must either extend Thread or implement Runnable.|False
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one.)|Y
ou cannot specify which thread will get notified.
A programmer needs to create a logging method that can accept an arbitrary numbe
r of arguments. For example, it may be called in these ways: logIt( log message 1 )
; logIt( log message2 , log message3 ); logIt( log message4 , log message5 , log message6
declaration satisfies this requirement? (Choose one.)|public void logIt(String.
.. msgs)
A signed data type has an equal number of non-zero positive and negative values
available.|False
A thread wants to make a second thread ineligible for execution. To do this, the
first thread can call the yield() method on the second thread.|False
A thread s run() method includes the following lines: 1. try { 2. sleep(100);
3. } catch (InterruptedException e) { } Assuming the thread is not interrupted,
which one of the following statements is correct? | At line 2, the thread will
stop running. It will resume running some time after 100 milliseconds have elaps
ed.
A(n) ___ object is used to submit a query to a database |Statement
A(n) ___ object is uses to obtain a Connection to a Database |DriverManager
After execution of the following code fragment, what are the values of the varia
bles x, a, and b? 1. int x, a = 6, b = 7; 2. x = a++ + b++;|x = 13, a = 7, b = 8
Assume that country is set for each class. Given: 10. public class Money { 11.
private String country, name; 12. public String getCountry() { return count
ry; } 13.} and: 24. class Yen extends Money { 25. public String getCountry() {
return super.country; } 26. } 28. class Euro extends Money { 29. public Strin
g getCountry(String timeZone) { 30. return super.getCountry(); 31. } 32.
} Which two are correct? (Choose two.)|Euro returns correct Country value. Compi
lation fails because of an error at line 25.
Choose the valid identifiers from those listed here. (Choose all that apply.) |
all: $int bytes $1 finalist BigOlLongStringWithMeaninglessName
Class SomeException: 1. public class SomeException { 2. } Class A: 1. public cla
ss A { 2. public void doSomething() { } 3. } Class B: 1. public class B exten
ds A { 2. public void doSomething() throws SomeException { } 3. } Which is tr
ue about the two classes? (Choose one.)|Compilation of class B will fail. Compi
lation of class A will succeed.
Class TestException:1. public class TestException extends Exception { 2. } Class
A: 1. public class A { 2. 3. public String sayHello(String name) throws Te
stException { 4. 5. if(name == null) { 6. throw new TestException
(); 7. } 8. 9. return Hello + name; 10. } 11. 12. } A programmer wan
ts to use this code in an application: 45. A a=new A(); 46. System.out.println(a
.sayHello( John )); Which two are true? (Choose two.) |Line 46 will compile if the e
nclosing method throws a TestException. Line 46 will compile if enclosed in a tr
y block, where TestException is caught.
1. class Q6 {2. public static void main(String args[]) {3. Holder
h = new Holder();4. h.held = 100;5. h.bump(h);6.
System.out.println(h.held);7. }8. }9.10. class Holder {11. public int
held;12. public void bump(Holder theHolder) {13. theHolder.held++
; 14 }15. }15. }What value is printed out at line 6?|101
1. class Q7 { 2. public static void main(String args[]) { 3.
double d = 12.3; 4. Decrementer dec = new Decrementer(); 5.
dec.decrement(d); 6. System.out.println(d); 7. } 8. } 9. 1
0. class Decrementer {11. public void decrement(double decMe) { 12.
decMe = decMe - 1.0; 13. } 14. } What value is printed out at line 6
? |12.3
1. public class Test extends Base { 2. public Test(int j) { 3. } 4
. public Test(int j, int k) { 5. super(j, k); 6. } 7. }
Which of the following are legitimate calls to construct instances of the Test c
lass? (Choose two.) | Test t = new Test(1); Test t = new Test(1, 2);
1. public class Test extends Base { 2. public Test(int j) { 3. } 4.
public Test(int j, int k) { 5. super(j, k); 6. } 7. } Which o
f the following forms of constructor must exist explicitly in the definition of
the Base class? Assume Test and Base are in the same package. (Choose two.) | Ba
se() { } Base(int j, int k) { }
1. class Cruncher { 2. void crunch(int i) { 3. System.out.println
("int version"); 4. } 5. void crunch(String s) { 6. System.o
ut.println("String version"); 7. } 8. 9. public static void main(String
args[]) { 10. Cruncher crun = new Cruncher(); 11. char ch =
"p"; 12. crun.crunch(ch); 13. } 14. } Which of the following sta
tements is true? (Choose one.)| The code will compile and produce the following
output: int version.
1. public class Base { 2. public void method(int i) { 3. Syste
m.out.print( Value is + i); 4. } 5. } 1. public class Sub extends Base { 2.
public void method(int j) { 3. System.out.print( This value is +
j); 4. } 5. public void method(String s) { 6. System.ou
t.print( I was passed + s); 7. } 8. public static void main(String arg
s[]) { 9. Base b1 = new Base(); 10. Base b2 = new Sub(); 1
1. b1.method(5); 12. b2.method(6); 13. } 14. } What out
put results when the main method of the class Sub is run?(Choose one.) | Value i
s 5This value is 6
Which line will not compile? (Choose one.) 1. Object ob = new Object(); 2. Strin
g[] stringarr = new String[50]; 3. Float floater = new Float(3.14f); 4. ob = str
ingarr; 5. ob = stringarr[5]; 6. floater = ob; 7. ob = floater; | Line 6
1. public class Assertification { 2. public static void main(String[] args
) { 3. assert args.length == 0; 4 } 5. } Which of the following c
onditions must be true in order for the code to throw an AssertionError? Assume
you are using release 5.0. (Choose two.) | The args array must have one or more
elements. The application must be run with the -enableassertions flag or another
assertionenabling flag.
1. StringBuffer sbuf = new StringBuffer(); 2. sbuf = null; 3. System.gc(); Cho
ose true statement. (Choose one.) | After line 2 executes, the StringBuffer obje
ct is eligible for garbage collection.
1. Cat sunflower; 2. Washer wawa; 3. SwampThing pogo; 4. 5. sunflower = new Cat
(); 6. wawa = sunflower; 7. pogo = (SwampThing)wawa; Which of the following sta
tements is true? (Choose one.) Where: Mammal extends Animal Cat, SwampTh
ing extends Mammal Cat implements Washer | The code will compile but will thr
ow an exception at line 7, because the runtime class of wawa cannot be converted
to type SwampThing.
1. Dog rover, fido; 2. Animal anim; 3. 4. rover = new Dog(); 5. anim = rover; 6.
fido = (Dog)anim; Where: Mammal extends Animal Dog extends Mammal
Which of the following statements is true? (Choose one.) |The code will compile
and run, but the cast in line 6 is not required and can be eliminated.
1. for (int i = 0; i < 2; i++) { 2. for (int j = 0; j < 3; j++) { 3.
if (i == j) { 4. continue; 5. } 6. System
.out.println("i = " + i + " j = " + j); 7. } 8. } Which lines would be part
of the output? (Choose four.) |0-1 0-2 1-0 1-2
1. outer: for (int i = 0; i < 2; i++) { 2. for (int j = 0; j < 3; j++) { 3
. if (i == j) { 4. continue outer; 5. } 6.
System.out.println("i = " + i + " j = " + j); 7. } 8. } Which line
s would be part of the output? (Choose one.) | i = 1 j = 0
1. Raccoon rocky; 2. SwampThing pogo; 3. Washer w; 4. 5. rocky = new Raccoon();
6. w = rocky; 7. pogo = w; Which of the following statements is true? (Choose
one.) Where: Mammal extends Animal Dog, Raccoon, Swamp Thing extends Mam
mal Raccoon implements Washer | Line 7 will not compile; an explicit cast is
required to convert a Washer to a SwampThing
1. public class Outer { 2. public int a = 1; 3. private int b = 2; 4.
public void method(final int c) { 5. int d = 3, f=10; 6.
class Inner { 7. private void iMethod(int e) { 8. 9.
} 10. } 11. } 12. } Which variables can be referenced at l
ine 8? (Choose four.) | abce
int[] x = new int[25]; After execution, which statements are true? (Choose two
.) |x[24] is 0 x.length is 25
1. public class Test1 { 2. public float aMethod(float a, float b) throws I
OException {.. } 3. } 1. public class Test2 extends Test1 { 2. 3.} Which of th
e following methods would be legal (individually) at line 2 in class Test2? (Cho
ose two) | public int aMethod(int a, int b) throws Exception {...} public float
aMethod(float p, float q) {...}
1. public class Test1 { 2. public float aMethod(float a, float b) { 3.
} 4. 5. } Which of the following methods would be legal if added (individually
) at line 4? (Choose three.) | public int aMethod(int a, int b) { } public float
aMethod(float a, float b, int c) throws Exception { } private float aMethod(int
a, int b, int c) { }
11. public static Iterator reverse(List list) { 12. Collections.reverse(list)
; 13. return list.iterator(); 14. } 15. public static void main(String[] args
) { 16. List list = new ArrayList(); 17. list.add( 1 ); list.add( 2 ); list.add( 3 )
18. for (Object obj: reverse(list)) 19. System.out.print(obj + , ); 20
. } What is the result? (Choose one.) |Compilation fails.
Given a string constructed by calling s = new String("xyzzy"), which of the call
s modifies the string? (Choose one.) |None of the above
Given arrays a1 and a2, which call returns true if a1 and a2 have the same lengt
h, and a1[i].equals(a2[i]) for every legal index i? (Choose one.) |java.util.Arr
ays.equals(a1, a2);
Given the following class: public class Xyz implements java.io.Serializable {
public int iAmPublic; private int iAmPrivate; static int iAmStat
ic; transient int iAmTransient; volatile int iAmVolatile; } A
ssuming the class does not perform custom serialization, which fields are writte
n when an instance of Xyz is serialized? (Choose three.) |iAmPublic iAmPrivate i
AmVolatile
Given the following code, and making no other changes, which combination of acce
ss modifiers (public, protected, or private) can legally be placed before aMetho
d() on line 3 and be placed before aMethod() on line 8? (Choose one.) 1. class S
uperDuper 2. { 3. void aMethod() { } 4. } 5. 6. class Sub extends SuperDupe
r 7. { 8. void aMethod() { } 9. } |line 3: private; line 8: protected
enum Spice { NUTMEG, CINNAMON, CORIANDER, ROSEMARY; }|Spice sp = Spice.NUTMEG; O
bject ob = sp; Spice sp = Spice.NUTMEG; Object ob = (Object)sp;Object ob = new O
bject(); Spice sp = (Spice)ob;
List<String> names = new ArrayList<String>(); which of the following are legal?
(Choose two.)|Iterator<String> iter = names.iterator(); for (String s:names)
11. static class A { 12. void process() throws Exception { throw new Excepti
on(); } 13. } 14. static class B extends A { 15. void process() { System.out.
println( B ); }16. } 17.public static void main(String[] args) { 18. A a=ne
w B(); 19. a.process(); 20. }What is the result? (Choose one.) |Compilat
ion fails line 19.
public class Bar { public static void main(String [] args) {
int x =5; boolean b1 = true; boolean b2 = false;
if((x==4) && !b2) System.out.print("l ");
System.out.print("2 "); if ((b2 = true) && b1)
System.out.print("3"); }}What is the result? (Choose one.)|2 3
1. public interface A { 2. String DEFAULT_GREETING = Hello World ; 3. publi
c void method1(); 4. } A programmer wants to create an interface called B that h
as A as its parent. Which interface declaration is correct? (Choose one.) |publi
c interface B extends A { }
10. abstract public class Employee { 11. protected abstract double getSalesAm
ount(); 12. public double getCommision() { 13. return getSalesAmount()
* 0.15; 14. } 15. } 16. class Sales extends Employee { 17. // insert method h
ere 18. } Which two methods, inserted independently at line 17, correctly comple
te the Sales class? (Choose two.)|public double getSalesAmount() { return 1230.4
5; } protected double getSalesAmount() { return 1230.45; }
10. class MakeFile { 11. public static void main(String[] args) { 12. t
ry { 13. File directory = new File( d ); 14. File file = new File(
directory, f ); 15. if(!file.exists()) { 16. file.createNewFile
(); 17. } 18. }catch (IOException e) { 19. e.printStackT
race ();20. } 21. } 22. } The current directory does NOT contain a dire
ctory named d. Which three are true? (Choose three.) | An exception is thrown at r
untime. Line 13 creates a File object named d. Line 14 creates a File object named
f.
10. class Nav{ 11. public enum Direction { NORTH, SOUTH, EAST, WEST } 12.
} 13. public class Sprite{ 14. // insert code here 15. } Which code, inserted at
line 14, allows the Sprite class to compile? (Choose one.) |Nav.Direction d = N
av.Direction.NORTH;
10. interface Foo { int bar(); } 11. public class Sprite { 12. public int fub
ar( Foo foo) { return foo.bar(); } 13. public void testFoo() { 14. fuba
r( 15. // insert code here 16. ); 17. } 18. } Which code, inserted a
t line 15, allows the class Sprite to compile? (Choose one.) |new Foo() { public
int bar(){return 1; } }
10. public class ClassA { 11. public void count(int i) { 12. count(++i)
; 13. } 14. } And: 20. ClassA a = new ClassA(); 21. a.count(3); Which excepti
on or error should be thrown by the virtual machine? (Choose one.) | StackOverf
lowError
11. public abstract class Shape { 12. int x; 13. int y; 14. public abst
ract void draw(); 15. public void setAnchor(int x, int y) { 16. this.x
= x; 17. this.y = y; 18. } 19. } and a class Circle that extends and fu
lly implements the Shape class. Which is correct? (Choose one.)|Shape s = new Ci
rcle(); s.setAnchor(10,10); s.draw();
11. public static void main(String[] args) { 12. Object obj =new int[] { 1,2,
3 }; 13. int[] someArray = (int[])obj; 14. for (int i: someArray) System.o
ut.print(i +" ");15. } What is the result? (Choose one.)|1 2 3
11. public static void main(String[] args) { 12. try { 13. args=null; 1
4. args[0] = test ; 15. System.out.println(args[0]); 16. }catch (Exc
eption ex) { 17. System.out.println( Exception ); 18. }catch (NullPointerEx
ception npe) { 19. System.out.println( NullPointerException ); 20. } 21. }
What is the result? (Choose one.) | Compilation fails.
11. public static void parse(String str) { 12. try { 13. float f= Float
.parseFloat(str); 14. } catch (NumberFormatException nfe) { 15. f = 0;
16. } finally { 17. System.out.println(f); 18. } 19. } 20. public st
atic void main(String[] args) { 21. parse("invalid"); 22. } What is the resul
t? (Choose one.)|Compilation fails.
11. String test = This is a test ; 12. String[] tokens = test.split( \s ); 13. System.o
ut.println(tokens.length); What is the result? (Choose one.) |Compilation fails
.
12. public class AssertStuff { 14. public static void main(String [] args) {
15. int x= 5; 16. int y= 7; 18. assert (x > y): stuff ; 19.
System.out.println( passed ); 20. } 21. } And these command line invocations: ja
va AssertStuff java -ea AssertStuff What is the result? (Choose one.)|passed An
AssertionError is thrown with the word stuff added to the stack trace.
12. public class Test { 13. public enum Dogs {collie, harrier}; 14. public
static void main(String [] args) { 15. Dogs myDog = Dogs.collie; 16.
switch (myDog) { 17. case collie: 18. System.out.print( col
lie ); 19. case harrier: 20. System.out.print( harrier ); 21.
} 22. } 23. } What is the result? (Choose one.) | collie harrier
13. public class Pass { 14. public static void main(String [] args) { 15.
int x = 5; 16. Pass p = new Pass(); 17. p.doStuff(x); 18.
System.out.print(" main x = "+ x); 19. } 20. 21. void doStuff(int x) { 2
2. System.out.print("doStuff x = "+ x++); 23. } 24. } What is the resu
lt? (Choose one.)|doStuff x = 5 main x = 5
13. public class Pass { 14. public static void main(String [] args) { 15.
int x = 5; 16. Pass p = new Pass(); 17. p.doStuff(x); 18.
System.out.print(" main x = "+ x); 19. } 20. 21. void doStuff(int x) { 2
2. System.out.print("doStuffx = "+ x++); 23. } 24. } What is the resul
t? (Choose one.)|doStuffx = 5 main x = 5
public class Q { public static void main(String argv[]){ int anar[]=new int[]{1,
2,3}; System.out.println(anar[1]); | 2
Which of the following statements is INCORRECT|A method in an interface can acce
ss class level variables
Which of the following is legal?| double d = 1.2d;
Which of the following operations might throw an ArithmeticException?| %
class Base {} class Sub extends Base {} class Sub2 extends Base {} public class
CEx { public static void main(String argv[]) { Base b = new Base();
Sub s = (Sub) b; }}| Compile time Exception
A protected method may only be accessed by classes or interfaces of the same pac
kage or bysubclasses of the class in which it is declared.
Which of the following statements is incorrect| Vector does not allow duplicate
elements
select the most correct statement|a (non-local) inner class may be declared as p
ublic, protected, private, static, final or abstract.
which of the following statements is true about two base protocols used for netw
orking: TCP (Transmissions Control Protocol) and UDP (User Datagram Protocol)?|T
CP is a connection-based protocol and udp is not connection-based protocol
Which of the statements below are true?|To check whether the file denoted by the
abstract pathname is a directory or not, call the isDirectory() method of the F
ile class
public class Main{ public static void main(String argv[]){ String s
= "Hi there"; int pos = s.indexOf(" "); String r = s.substring(0
,pos); String s2 = new String(new char[]{'H','i'}); if (r.equals
(s2)) System.out.println("EQUAL"); else System.
out.println("NOT EQUAL"); System.out.println(""); } }|EQUAL
which of the following methods of the collections class can be used to find the
largest value in a vector?|Collection.max()
select the correct statement which set the layout manager of a given frame to fl
owlayoutmanager|setLayout(new Flowlayout());
public class Bground extends Thread{ public static void main(String argv[]){
Bground b = new Bground(); b.run(); }
public void start(){ for (int i = 0; i <10; i++){
System.out.println("Value of i = " + i); }
} }| Clean compile but no output at runtime
public class EqTest{ public static void main(String argv[]}{ EqTest e = new EqTe
st(); } |if(s.equalsIgnoreCase(s2))
public class Main { public static void main(String Argv[]) { A t =
new A("One"); t.run(); A h = new A("Two"); h.run();
} } class A extends Thread { private String sTname = ""; A(String s)
{ sTname = s; } } public void run(){ for(int i =0;i<2;i++){
try{ sleep(1000); } catch(InterruptedException e){} yield();
System.out.print(sTname+""); } } | Compile time error, class Rpcraven d
oes not import java.lang.Thread
abstract class Base{ abstract public void myfunc(); public void an
other(){ System.out.println("Another method"); }}public class Abs
extends Base{ public static void main(String argv[]){ Abs a = new
Abs(); a.amethod(); } public void myfunc(){
System.out.println("My Func"); } public void amethod(){
myfunc(); }}| The code will compile and run, printing out the
words "My Func"
public class MyMain{ public static void main(String argv){ System.out.pr
intln("Hello cruel world"); } }|The code will compile but will complain
at run time that main is not correctly defined
Which of the following are Java modifiers?|public private transient
class Base{ abstract public void myfunc(); public void another(){
System.out.println("Another method"); }}public class Abs extends B
ase{ public static void main(String argv[]){ Abs a = new Abs();
a.amethod(); } public void myfunc(){ System.ou
t.println("My func"); } public void amethod(){ myf
unc(); }}|The compiler will complain that the Base class is not declared
as abstract.
which of the following methods of java.io.file can be used to create a new file|
There is no such method. Just do File f = new File("filename.txt"), then the new
file, named filename.txt will be created
Why might you define a method as native?|To get to access hardware that Java doe
s not know about To write optimised code for performance in a language such as C
/C++
class Base{ public final void amethod(){ System.out.println("amethod");
} } public class Fin extends Base{ public static void main(String argv[
]){ Base b = new Base(); b.amethod(); } }| Success in co
mpilation and output of "amethod" at run time.
public class Mod{ public static void main(String argv[]){ } public s
tatic native void amethod(); }| Compilation and execution without error
private class Base{} public class Vis{ transient int iVal; publ
ic static void main(String elephant[]){ } }|Compile time error: Base can
not be private
//File P1.java package MyPackage; class P1{ void afancymethod(){ System.
out.println("What a fancy method"); } } //File P2.java public class P2 e
xtends P1{ public static void main(String argv[]){ P2 p2 = new P2();
p2.afancymethod(); }}|P1 compiles cleanly but P2 has an error at compile tim
e
public class MyAr{ public static void main(String argv[]){ int[] i = new
int[5]; System.out.println(i[5]); } }|An error at run time
20. public class CreditCard { 22. private String cardlD; 23. private Integer lim
it; 24. public String ownerName; 26. public void setCardlnformation(String cardl
D, 27. String ownerName, 28. Integer limit) { 29. this.cardlD = cardlD; 30. this
.ownerName = ownerName; 31. this.limit = limit; 32. } 33. } |The ownerName varia
ble breaks encapsulation.
23. Object [] myObjects = { 24. new Integer(12), 25. new String( foo ), 26. new Inte
ger(5), 27.new Boolean(true) 28. }; 29. java.util.Array.sort(myObjects); 30. for
( int i=0; i<myObjects.length; i++) { 31. System.out.print(myObjects[i].toString
()); 32. System.out.print( ); 33. } What is the result? (Choose one.)|Compilation
fails due to an error in line 29.
31. // some code here 32. try { 33. // some code here 34. } catch (SomeException
se) { 35. // some code here 36. } finally { 37. // some code here 38. } Under w
hich three circumstances will the code on line 37 be executed? (Choose three.)|T
he code on line 33 throws an exception. The code on line 35 throws an exception.
The code on line 33 executes successfully.
33. try { 34. // some code here 35. }catch (NullPointerException e1) { 36. Sy
stem.out.print( a ); 37. }catch (RuntimeException e2) { 38. System.out.print( b ); 39
. } finally { 40. System.out.print( c ); 41. } What is the result if a NullPoint
erException occurs on line 34? (Choose one.)|ac
55. int []x= {1, 2,3,4, 5}; 56. int y[] =x; 57. System.out.println(y[2]); Which
is true? (Choose one.)|Line 57 will print the value 3.
8. public class test { 9. public static void main(String [] a) { 10.
assert a.length == 1; 11. } 12.} Which two will produce an AssertionError? (C
hoose two.)|java -ea test, java -ea test file1 file2
1. public class TestString3 { 2. public static void main(String[] args) { 3.
// insert code here 5. System.out.println(s); 6. } 7. } Which two
code fragments, inserted independently at line 3, generate the output 4247? (Ch
oose two.)|StringBuffer s = new StringBuffer( 123456789 ); s.delete(0,3).replace( 1,
3, 24 ).delete(4,6); StringBuilder s = new StringBuilder( 123456789 ); s.delete(0,3).de
lete( 1 ,3).delete(2,5).insert( 1, 24 );
10. class Line { 11. public static class Point { } 12. } 13. 14. class Triang
le { 15. // insert code here 16. } Which code, inserted at line 15, creates an i
nstance of the Point class defined in Line? (Choose one.)|Line.Point p = new Li
ne.Point();
10. public class Bar { 11. static void foo(int...x) { 12. // insert code h
ere 13. } 14. } Which two code fragments, inserted independently at line 12, wil
l allow the class to compile? (Choose two.)|for(int z : x) System.out.println(z)
; for( int i=0; i< x.length; i++ ) System.out.println(x[i]);
11. public interface Status { 12. /* insert code here */ int MY_VALUE = 10; 13.
} Which three are valid on line 12? (Choose three.)|final static public
class A { public void process() { System.out.print("A "); } public static vo
id main(String[] args) { try { ((A)new B()).process(); } catch (Exception e) {
System.out.print("Exception "); } }}class B extends A { public void proces
s() throws RuntimeException { super.process(); if (true) throw new Run
timeException(); System.out.print("B"); }}|A Exception B
How can you ensure that multithreaded code does not deadlock? (Choose one.)|Ther
e is no single technique that can guarantee non-deadlocking code.
How can you force garbage collection of an object? (Choose one.)|Garbage collect
ion cannot be forced.
How do you prevent shared data from being corrupted in a multithreaded environme
nt? (Choose one.)|Access the variables only via synchronized methods.
How do you use the File class to list the contents of a directory? (Choose one.)
|String[] contents = myFile.list();
How many bytes does the following code write to file dest? (Choose one.) 1. try
{ 2. FileOutputStream fos = newFileOutputStream("dest"); 3. DataOutputStream dos
= new DataOutputStream(fos); 4. dos.writeInt(3); 5. dos.writeFloat(0.0001f); 6.
dos.close(); 7. fos.close(); 8. } 9. catch (IOException e) { } |12
How many locks does an object have? (Choose one.)|One
If all three top-level elements occur in a source file, they must appear in whic
h order? (Choose one.)|Package declaration, imports, class/interface/enum defini
tions.
If class Y extends class X, the two classes are in different packages, and class
X has a protected method called abby(), then any instance of Y may call the abb
y() method of any other instance of Y.|False
If you attempt to compile and execute the following application, will it ever pr
int out the message In xxx? 1. class TestThread3 extends Thread { 2. publi
c void run() { 3. System.out.println("Running"); 4. Syst
em.out.println("Done"); 5. } 6. 7. private void xxx() { 8.
System.out.println( In xxx ); 9. } 10. 11. public static void main(Str
ing args[]) { 12. TestThread3 ttt = new TestThread3(); 13.
ttt.xxx(); 14. ttt.start(); 12. } 13. }|Yes
If you need a Set implementation that provides value-ordered iteration, which cl
ass should you use? (Choose one.)|TreeSet
In order for objects in a List to be sorted, those objects must implement which
interface and method? (Choose one.)|Comparable interface and its compareTo meth
od.
In the following code fragment, after execution of line 1, sbuf references an in
stance of the StringBuffer class. After execution of line 2, sbuf still referenc
es the same instance. 1. StringBuffer sbuf = new StringBuffer("FPT"); 2. sbuf.ap
pend("-University");|True
In the following code fragment, after execution of line 1, sbuf references an in
stance of the StringBuffer class. After execution of line 2, sbuf still referenc
es the same instance. 1. StringBuffer sbuf = new StringBuffer("FPT"); 2. sbuf.in
sert(3, "-University");|True
In the following code, what are the possible types for variable result? (Choose
the most complete true answer.) 1. byte b = 11; 2. short s = 13; 3. result = b *
++s;|int, long, float, double
Interface ____ helps manage the connection between a Java program and a database
|Connection
Is it possible to define a class called Thing so that the following method can r
eturn true under certain circumstances? boolean weird(Thing s) { Integer x =
new Integer(5); return s.equals(x); }|Yes
Is it possible to write code that can execute only if the current thread owns mu
ltiple locks?|Yes
JDBC supports ______ and ______ models.|Two-tier and three-tier
MVC is short call of|Model-View-Controller
public class Test{ public static void main(String[] args){ byte b = 2; byte b1 =
3; b = b * b1; System.out.println("b="+b); } } What is the output?|No outpu
t because of compile error at line: b = b * b1;
public class Test{ public static void main(String[] args){ Object ob1= new Objec
t(); Object ob2= new Object(); if(ob1.equals(ob2)) System.out.println("ob1 equal
s ob2"); if(ob1==ob2) System.out.println("ob1==ob2"); System.out.println("Have
a nice day!"); } } What is the output?|Have a nice day!
public class Test{ public static void main(String[] args){ Object ob1= new Objec
t(); Object ob2= ob1; if(ob1.equals(ob2)) System.out.println("ob1 equals ob2");
if(ob1==ob2) System.out.println("ob1==ob2"); System.out.println("Have a nice da
y!"); } } What is the output?|ob1 equals ob2 ob1==ob2 Have a nice day!
public class Test{ public static void main(String[] args){ String s1 = "xyz"; St
ring s2 = "xyz"; if (s1 == s2) System.out.println("Line 4"); if (s1.equals(s2))
System.out.println("Line 6"); } } What is the output?|Line 4 Line 6
public class Test{ public static void main(String[] args){ String s1 = "xyz"; St
ring s2 = new String("xyz"); if (s1 == s2) System.out.println("Line 4"); if (s1.
equals(s2)) System.out.println("Line 6");} } What is the output?|Line 6
public class Test{ public static void main(String[] args){ String s1 = "xyz"; St
ring s2 = new String(s1); s2.intern(); if (s1 == s2) System.out.println("Line 4"
); if (s1.equals(s2)) System.out.println("Line 6");} } What is the output?|Line
6
public class Test{ public static void main(String[] args){ String s
1 = "xyz"; String s2 = new String(s1); s2=s2.intern();
if (s1 == s2) System.out.println("Line 4");
if (s1.equals(s2)) System.out.println("Line 6");
} } What is the output? (choose 1)|Line 4 Line 6
Select correct statement about RMI. (choose 1)|All the above
Select correct statement(s) about remote class.(choose one)|All the others choic
es
Select correct statements about remote interface. (choose 1)|All the others choi
ces
Select INCORRECT statement about serialization. (choose 1)|When an Object Outpu
t Stream serializes an object that contains references to another object, every
referenced object is not serialized along with the original object.
Select INCORRECT statement about deserialize. (choose 1)|We use readObject() met
hod of ObjectOutputStream class to deserialize.
Select incorrect statement about RMI server.(choose 1)|A client accesses a remot
e object by specifying only the server name.
Select incorrect statement about ServerSocket class. (choose 1)|To make the new
object available for client connections, call its accept() method, which returns
an instance of ServerSocket
Select incorrect statement about Socket class. (choose 1)|The java.net.Socket cl
ass contains code that knows how to find and communicate with a server through U
DP
Select the correct statement about JDBC two-tier processing model.|A user's comm
ands are delivered to the database or other data source, and the results of thos
e statements are sent back to the user.
SQL keyword ___ is followed by the selection criteria that specify the rows to s
elect in a query|WHERE
Statement objects return SQL query results as ___ objects|ResultSet
Study the statements: 1)When a JDBC connection is created, it is in auto-commit
mode 2)Once auto-commit mode is disabled, no SQL statements will be committed un
til you call the method commit explicitly|Both 1 and 2 are true
Suppose a method called finallyTest() consists of a try block, followed by a cat
ch block, followed by a finally block. Assuming the JVM doesn t crash and the code
does not execute a System.exit() call, under what circumstances will the finall
y block not begin to execute? (Choose one.)|If the JVM doesn't crash and the cod
e does not execute a System.exit() call, the finally block will always execute.
Suppose a source file contains a large number of import statements and one class
definition. How do the imports affect the time required to load the class? (Cho
ose one.)|Class loading takes no additional time.
Suppose a source file contains a large number of import statements. How do the i
mports affect the time required to compile the source file? (Choose one.)|Compil
ation takes slightly more time.
Suppose class A extends Object; Class B extends A; and class C extends B. Of the
se, only class C implements java.io.Externalizable. Which of the following must
be true in order to avoid an exception during deserialization of an instance of
C? (Choose one.)|C must have a no-args constructor.
Suppose class A extends Object; class B extends A; and class C extends B. Of the
se, only class C implements java.io.Serializable. Which of the following must be
true in order to avoid an exception during deserialization of an instance of C?
(Choose one.)|B must have a no-args constructor.
Suppose class A has a method called doSomething(), with default access. Suppose
class B extends A and overrides doSomething(). Which access modes may not apply
to B s version of doSomething()? (Choose one)|private
Suppose class Supe, in package packagea, has a method called doSomething(). Supp
ose class Subby, in package packageb, overrides doSomething(). What access modes
may Subby s version of the method have? (Choose two.)|public protected
Suppose class X contains the following method: void doSomething(int a, float b)
{ } Which of the following methods may appear in class Y, which extends X? (Choo
se one.)|public void doSomething(int a, float b) { }
Suppose interface Inty defines five methods. Suppose class Classy declares that
it implements Inty but does not provide implementations for any of the five inte
rface methods. Which are true? (Choose two.)|The class will compile if it is dec
lared abstract. The class may not be instantiated.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.)|All the above
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries? (Choose one.)|
for (float f:salaries)
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x = y; legal? (Choose one.)|When the type of x is
Object
Suppose the type of xarr is an array of XXX, and the type of yarr is an array of
YYY. When is the assignment xarr = yarr; legal? (Choose one.)|Sometimes
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.)|if (x ==
y)
Suppose you are writing a class that will provide custom deserialization. The cl
ass implements java.io.Serializable (not java.io.Externalizable). What access mo
de should the readObject() method have? (Choose one.)|private
Suppose you are writing a class that will provide custom serialization. The clas
s implements java.io.Serializable (not java.io.Externalizable). What access mode
should the writeObject() method have? (Choose one.)|private
Suppose you want to create a custom thread class by extending java.lang.Thread i
n order to provide some special functionality. Which of the following must you d
o? (Choose one.)|Override run().
Suppose you want to write a class that offers static methods to compute hyperbol
ic trigonometric functions. You decide to subclass java.lang.Math and provide th
e new functionality as a set of static methods. Which one statement is true abou
t this strategy?|The strategy fails because you cannot subclass java.lang.Math.
Swing components cannot be combined with AWT components.|True
The ______ class is the primary class that has the driver information.|DriverMan
ager
The ______ class is used to implement a pull-down menu that provides a number of
items to select from.|Menu
The border layout resizes the ______ components to fill the remaining centre spa
ce.|Center
public class MyClass1 { public static void main(String argv[]) {} /*Modifier at
XX*/ class MyInner {} } What modifier would be illegal at XX in the above code?|
friend
What will happen when you attempt to compile and run this code? class Base{ abst
ract public void myfunc(); public void another(){ System.out.println("Another me
thod"); }} public class Abs extends Base{ public static void main(String argv[])
{ Abs a = new Abs(); a.amethod(); } public void myfunc(){ System.out.println("My
func"); } public void amethod(){ myfunc(); } }|The compiler will complain that
the Base class is not declared as abstract
Given the following class definition, which if the following methods could be le
gally placed after the comment //Here? (Select two) public class Rid{ public voi
d amethod(int i, String s){} //Here }|public void Amethod(int i, String s){} pub
lic void amethod(String s, int i){}
Select correct statement (1) The Swing's list component(JList) can display text
only (2) The Swing's button(JButton) can not contain an image. (3) The Swing's l
abel(JLabel) can present an image|1 3
What is the output of the following code: class Main{ public static void main(St
ring[] argv){ byte b1 = 10; byte b2 = 9; b1 = (byte)(b1|b2); System.out.println(
b1); }}|11
What is the purpose of the finally clause of a try-catch-finally statement? (Sel
ect correct answer)|The finally clause is used to provide the capability to exec
ute code no matter whether or matter whether or not an exception is throw or cau
ght
Consider the following class:1. class Test {2. void foo(int i) {3.
System.out.println("int version");4. }5. void foo(String s) {6.
System.out.println("String version");7. }8.9. public static void
main(String args[]) {10. Test t = new Test();11. char ch = '
p';12. t.foo(ch);13. }14. }Which of the following statements is t
rue?|The code will compile and produce the following output: int version.
What will happen when you try compiling and running this code? public class Ref{
public static void main(String argv[]){ Ref r = new Ref(); r.amethod(r); } publ
ic void amethod(Ref r){ int i = 99; multi(r); System.out.println(i); } public vo
id multi(Ref r){ r.i = r.i*2; }}|Error at compile time
Which of following Java operations cause compile-time errors? int m=5, n=7; floa
t x=m; //1 double y=n; //2 m = y; //3 n = x; //4|3, 4
Select correct statement(s). (Select one option only) (1) Swing is part of the J
ava Foundation Classes and provides a rich set of GUI components. (2) Before you
think about what your GUI will look like, it's important to think about what it
will.|1, 2
With respect to processing models for database access, in the ... model a Java a
pplication talks directly to the data source|Two-tier
What will happen when you attempt to compile and run the following program (plea
se note that the Object class does not have the foo() method): class A{ void foo
(){ System.out.print("A");}} class B{ void foo(){ System.out.print("B");}} class
C extends A{ void foo(){ System.out.print("C");}} class Main{ public static voi
d main(String[] args){ Object t = new A(); t.foo(); t = new B(); t.foo(); t = ne
w C(); t.foo(); } }|Compile-time error
What is the output of the following code: class Main{ public static void main(St
ring args[]){ int k=11; System.out.print(k>>3); System.out.print(4&3); System.ou
t.print(4|3); System.out.println(); }}|107
Suppose class X contains the following method: void doSomething(int a, float b){
... } Which of the following methods may appear in class Y, which extends X?|pu
blic void doSomething(int a, float b){ ... }
Which of the following should always be caught?|Checked exceptions
int j; for(int i=0; i<14; i++){ if(i<10){ j = 2 + i; } System.out.println("j: "
+ j + "i: " +i); } What is WRONG with the above code?|Integer "j" is not initial
ized.
What is -8%5?|-3
What happens when you try to compile and run the following program? import java.
ulti.*; public class Main{ public static void main(String args[]){ String s = "A
BC 4 5 6 8"; Scanner sc = new Scanner(s); sc.next(); System.out.println(sc.nextI
nt() + sc.nextInt() + sc.nextInt()); }}|The program will have a runtime exceptio
n.
Which is the INCORRECT answer for the following question: What can cause a threa
d to stop executing?|A call to the halt method of the Thread class
Which of the following classes supports developers to get the pointer of a file?
|java.io.RandomAccessFile
Which of the following is Java keyword?|new
With respect to steps in RMI implementation: (1) Create the remote interface (2)
Create the remote object (3) Create the client object (4) Create the Stub The o
rder should be followed:|1, 2, 4, 3
Give the following code, which of the following will not compile? enum Spice{ NU
TMEG, CINNAMON, CORIANDER, ROSEMARY; }|String ob = new String(); Spice sp = ob;
public class Ombersley{ public static void main(String argv[]){boolean b1 = true
;if((b1 ==true) || place(true)){System.out.println("Hello Crowle");}}public stat
ic boolean place(boolean location){if(location==true){System.out.println("Borcet
shire");}System.out.println("Powick");return true;}} What will happen when you a
ttempt to compile and run it?|Output of "Hello Crowle"
Select the correct statement:|An object reference can be cast to an interface re
ference when the object implements the referenced interface.
The default layout manager for every JPane is|FlowLayout
Which of the following is NOT a valid comment|/*comment
Suppose salaries is an array containing floats. Which of the following are valid
loop control statements for processing each element of salaries?|for(float f:sa
laries)
With respect to networking and the client-server model. (1) A server runs on a s
pecific computer and has a socket that is bound to a specific port number. The s
erver just waits, listening to the socket for a client to make a connection requ
est.(2) To connect to the server, the client must know the hostname or IP of the
machine on which the server is running and the port number on which the server
is listening|True, true.
With respect to networking and the client-server model. (1) A socket is one endp
oint (a combination of an IP address and a port number) of a two-way communicati
on link between two programs running on the network..(2) TCP (Transmission Contr
ol Protocol) is a connection-based protocol that provides a reliable flow of dat
a between two computers.(3) UDP (User Datagram Protocol) is a protocol that send
s independent packets of data, called datagrams, from one computer to another wi
th no guarantees about arrival.|True, true, true
How do you change the value of the object k that is encapsulated by a wrapper cl
ass after you have instantiated it?|Use the k.setXXX() method defined for the wr
apper class
What happens when you try to compile and run the following program? import java.
ulti.*; public class Main{ public static void main(String argv[]){ Vector<Intege
r> t = new Vector<Integer>(); t.add(12); t.add(2); t.add(5); t.add(2); Iterator<
Integer> i = t.iterator(); int sum=0; while(i.hasNext()) sum += i.next(); System
.out.println(sum); }}|The program will print out 21
Which of the following are true? (Select two)|System.out has a println() method.
System.out has a format() method.
What will happen when you attempt to compile and run the following program: clas
s Box{ int a,b; Box(){} Box(int x, int y){a=x;b=y;} } class Reg extends Box{ int
c; Reg(){} Reg(int x, int y, int z){ this.c = z; super(x,y); } void display(){
System.out.println(a+b+c); }} class Main{ public static void main(String[] args)
{ Reg t = new Reg(2,3,4); t.display(); }}|Compile time error
What results from running the following code? 1. public class Xor{ 2. public sta
tic void main(String args[]){ 3. byte b = 10; //00001010 binary 4. byte c = 15;
//00001111 binary 5. b = (byte)(b ^ c); 6. System.out.println("b contains " + b)
; 7. } 8. }|The output: b contains 5
Which component can display an image, but cannot get focus?|JLabel
Which of the following is legal loop construction?|int j = 0; for(int k=0; j+k !
= 10; j++, k++){ System.out.println("j=" + j + ", k="+k); }
import java.util.*; public class Main{ public static void main(String argv[]){ S
tring s = "ABCk23k5.9"; Scanner t = new Scanner(s); t.useDelimiter("[k]");//use
the character k as delimiter String u = t.next(); while(t.hasNext()) u += t.next
(); System.out.println(u.substring(2)); }}|C235.9
Which of the following best describes the use of the synchronized keyword?|Ensur
es only one thread at a time may access a method or object
Select the order of access modifiers from least restrictive to most restrictive.
|public, protected, default, private
When is x & y an int?|When neither x nor y is a float, or a double
What will be printed out if this code is run with the following command line? ja
va mypro good morning public class mypro{ public static void main(String argv[])
{ System.out.println(argv[2]); }}|Exception raised "java.lang.ArrayIndexOutOfBou
ndsException: 2"
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant?|if (x == y)
class Test{ public int fun(int x){ int count=1; try{ count += x; foo(count); cou
nt++; } catch(Exception e){ count -= x; } return (count); } public int foo(in
t k){ if(true) throw new ArithmeticException(); return(k);}} class Main{ public
static void main(String[] args){ Test t = new Test(); System.out.println(t.fun(2
)); }}}|1
public int fubar(Foo foo){ return foo.bar(); } public void testFoo(){ class A im
plements Foo{ public int bar(){ return 2; } } System.out.println(fubar(new A()))
; } public static void main(String[] argv){ new Beta().testFoo(); } } Which stat
ement is true?|The code compiles and the output is 2
When is it appropriate to write code that constructs and throws an error?|Never
class Base{ public void Base(){ System.out.println("Base"); } } public class In
extends Base{ public void main(String argv[]){ In i = new In(); } }|Compilation
and no output at runtime
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion?|There is no difference; the rules are the same.
Which of the following are true? (Select two)|Once the thread terminates, it can
not be restarted by calling the function start() again When a thread terminates
its processing, it enters the dead state
Which of the following are true about garbage collection?|Garbage collection doe
s not guarantee that a program will not run out of memory
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation?|All of the above
What will be printed out if you attempt to compile and run the following code? i
nt i=9; switch(i){ default: System.out.println("default"); case 0: System.out.pr
intln("zero"); break; case 1: System.out.println("one"); case 2: System.out.prin
tln("two"); }|default zero
Which of the following is INCORRECT?|char c = \u1234;
Which of the following statements is true?|Constructors are not inherited
public class C{ public void method3(){ //more code here }} try{ A a = new A(); a
.method1(); }catch(Exception e){ System.out.print("an error occurred"); } Which
is true if a NullPointerException is thrown on line 3 of class C?|The code on li
ne 29 will be executed.
Which of the following statements is true?|Given that Inner is a nonstatic class
declared inside a public class Outer and that appropriate constructor forms are
defined, an instance of Inner can be constructed like this: new Outer().new Inn
er()
Which of the following is illegal statement?|float f=1.01;
What will happen when you compile and run the following code? public class Scope
{ private int i; public static void main(String argv[]){ Scope s = new Scope();
s.amethod(); }//End of main public static void amethod(){ System.out.println(i);
}//end of amethod }//End of class|A compile time error
Suppose class X contains the following method:|void doSomething(int a, float b){
... }
Which of the following methods in the Thread class are deprecated?|suspend() and
resume()
Which line contains only legal statements?|String x = "Hello", int y = 9; x = x
+ y;
Which of the following operations might throw an ArithmeticException? (select tw
o)|% /
How do you prevent shared data from being corrupted in a multithreaded environme
nt?|Access the variables only via synchronized methods
Which of the following is true?|The >> operator carries the sign bit when shifti
ng right. The >>> zero-fills bits that have been shifted out
Select the most correct statement:|A protected method may only be accessed by cl
asses or interfaces of the same package or by subclasses of the class in which i
t is declared.
11. public inteface Status{ 12. /*insert code here*/ int MY_VALE = 10; 13. } Whi
ch three are valid in line 12? (select three)|final static public
Consider the following code: 1. Dog rover, fido; 2. Animal anim; 3. 4. rover = n
ew Dog(); 5. anim = rover; 6. fido = (Dog)anim; Where: Mammal extends Animal Dog
extends Mammel Which of the following statements is true?|The code will compile
and run
You want to loop through an array and stop when you come to the last element. Be
ing a good java programmer and forgetting everything you ever knew about C/C++ y
ou know that arrays contain information about their size. Which of the following
can you use?|myarray.length;
import java.awt.*; public class FlowAp extends Frame{ public static void main(St
ring argv[]){ FlowAp fa=new FlowAp(); fa.setSize(400,300); fa.setVis
ible(true); } FlowAp(){ add(new Button("One")); add(new Button
("Two")); add(new Button("Three")); add(new Button("Four"));
}//End of constructor }//End of Application|A Frame with one large button mar
ked Four in the Centre
How do you indicate where a component will be positioned using Flowlayout?|Do no
thing, the FlowLayout will position the component
How do you change the current layout manager for a container|Use the setLayout m
ethod
Which of the following are fields of the GridBagConstraints class?|ipadx fill in
sets
import java.awt.*; public class CompLay extends Frame{ public static void main(S
tring argv[]){ CompLay cl = new CompLay(); } CompLay(){ Panel p = n
ew Panel(); p.setBackground(Color.pink); p.add(new Button("One")); p
.add(new Button("Two")); p.add(new Button("Three")); add("South",p);
setLayout(new FlowLayout()); setSize(300,300); setVisible(true); }
}|The buttons will run from left to right along the top of the frame
Which statements are correct about the anchor field?|It is a field of the GridBa
gConstraints class for controlling component placement A valid settting for the
anchor field is GridBagconstraints.NORTH
public class Bground extends Thread{ public static void main(String argv[]){
Bground b = new Bground(); b.run(); }
public void start(){ for (int i = 0; i <10; i++){
System.out.println("Value of i = " + i); }
} }|Clean compile but no output at runtime
Is the following statement true or false? When using the GridBagLayout manager,
each new component requires a new instance of the GridBagConstraints class.|fals
e
Which most closely matches a description of a Java Map?|An interface that ensure
s that implementing classes cannot contain duplicates
How does the set collection deal with duplicate elements?|The add method returns
false if you attempt to add an element with a duplicate value
What can cause a thread to stop executing?|The program exits via a call to exit(
0); The priority of another thread is increased A call to the stop method of the
Thread class
For a class defined inside a method, what rule governs access to the variables o
f the enclosing method?|The class can only access final variables
Under what circumstances might you use the yield method of the Thread class|To c
all from the currently running thread to allow another thread of the same or hig
her priority to run
public class Hope{ public static void main(String argv[]){ Hope h = new Hop
e(); } protected Hope(){ for(int i =0; i <10; i ++){ Syst
em.out.println(i); } } }|Compilation and running with output 0 to 9
public class MySwitch{ public static void main(String argv[]){ MySwitch ms=
new MySwitch(); ms.amethod(); } public void amethod(){ int k=10;
switch(k){ default: //Put the default at the bottom, not here
System.out.println("This is the default output"); break;
case 10: System.out.println("ten"); case 20:
System.out.println("twenty"); break; } } }|None
of these options
Which of the following is the correct syntax for suggesting that the JVM perform
s garbage collection| System.gc();
public class As{ int i = 10; int j; char z= 1; boolean b; pu
blic static void main(String argv[]){ As a = new As(); a.amethod();
} public void amethod(){ System.out.println(j); System.out.
println(b); } }|Compilation succeeds and at run time an outp
ut of 0 and false
public class Arg{ String[] MyArg; public static void main(String argv[])
{ MyArg=argv; } public void amethod(){
System.out.println(argv[1]); } }|Compile time error
public class StrEq{ public static void main(String argv[]){ StrEq s = ne
w StrEq(); } private StrEq(){ String s = "Marcus
"; String s2 = new String("Marcus"); if(s == s2)
{ System.out.println("we have a match");
}else{ System.out.println("Not equal");
} } }|Output of "Not equal"
Which of the following calls may be made from a non-static synchronized method?
(Choose one.)|All the above
Which of the following classes implement java.util.List? (Choose two.)|ArrayList
+Stack
Which of the following classes implements a FIFO Queue? (Choose one.)|LinkedLis
t
Which of the following declarations are illegal? (Choose three.)|default String
s;abstract double d;abstract final double hyperbolicCosine();
Which of the following expressions are legal? (Choose two.)|int x = 6; if (!(x >
3)) {};int x = 6; x = ~x;
Which of the following expressions are legal? (Choose two.)|String x = "Hello";
int y = 9; x += y;String x = "Hello"; int y = 9; x = x + y;
Which of the following expressions results in a positive value in x? (Choose one
.)|int x = 1; x = x >>> 5;
Which of the following interfaces does not allow duplicate objects? (Choose one
.)|Set
Which of the following is not appropriate situations for assertions? (Choose one
)|Preconditions of a public method
Which of the following is NOTa valid comment:|/* comment
Which of the following is the most appropriate way to handle invalid arguments i
n a public method?|Throw java.lang.IllegalArgumentException.
Which of the following is true? (Choose one.)|None of the above
Which of the following is(are) true? (Choose one.)|All the above
Which of the following may appear on the left-hand side of an instanceof operato
r?|A reference
Which of the following may appear on the right-hand side of an instanceof operat
or? (Choose two.)|A class+An interface
Which of the following may be declared final? (Choose two.)|Classes+Methods
Which of the following may be statically imported? (Choose two.)|Static method n
ames+ Static field names
Which of the following may follow the static keyword? (Choose three.)|Data+Metho
ds+Code blocks enclosed in curly brackets
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.)|All of the others
Which of the following may legally appear as the new type (between the parenthes
es) in a cast operation? (Choose one.)|All of the above
Which of the following may not be synchronized? (Choose one.)|Classes
Which of the following may override a method whose signature is void xyz(float f
)? (Choose two.)|void xyz(float f)+public void xyz(float f)
Which of the following methods in the Thread class are deprecated? (Choose one.)
|suspend() and resume()
Which of the following operations might throw an ArithmeticException? (Choose on
e.)|None of these
Which of the following operations might throw an ArithmeticException? (Choose on
e.)|/
Which of the following operators can perform promotion on their operands? (Choos
e three.)|+,-,~
Which of the following restrictions apply to anonymous inner classes? (Choose on
e.)|They must be defined inside a code block.
Which of the following should always be caught? (Choose one.)|Checked exceptions
Which of the following signatures are valid for the main() method entry point of
an application? (Choose two.)|public static void main(String arg[]),public stat
ic void main(String[] args)
Which of the following statements about the wait() and notify() methods is true?
(Choose one.)|The thread that calls wait() goes into the monitor s pool of waitin
g threads.
Which of the following statements about threads is true? (Choose one.)|Threads i
nherit their priority from their parent thread.
Which of the following statements are true? (Choose one.)|A final class may not
be extended.
Which of the following statements are true? (Choose one.)|Given that Inner is a
nonstatic class declared inside a public class Outer and that appropriate constr
uctor forms are defined, an instance of Inner can be constructed like this: new
Outer().new Inner()
Which of the following statements are true? (Choose one.)|None of the above
Which of the following statements are true? (Choose two.)|StringBuilder is gener
ally faster than StringBuffer.StringBuffer is threadsafe; StringBuilder is not.
Which of the following statements are true?1)An abstract class may not have any
final methods.2)A final class may not have any abstract methods.| Only statement
2
Which of the following statements is correct? (Choose one.)|Both primitives and
object references can be both converted and cast.
Which of the following statements is true? (Choose one.)|Transient variables are
not serialized.
Which of the following statements is true? (Choose one.)|Object references can b
e converted in both method calls and assignments, and the rules governing these
conversions are identical.
Which of the statements below are true? (Choose one.)|Unicode characters are all
16 bits.
Which of the statements below are true? (Choose one.)|None of the above
Which of the statements below are true? (Choose one.)|None of the above.
Which one line in the following code will not compile?1. byte b = 5;2. char c = 5 ;
3. short s = 55;4. int i = 555;5. float f = 555.5f;6. b = s;7. i = c;8. if (f >
b)9. f = i;| Line 6
Which one statement is always true about the following application?1. class HiPr
i extends Thread {2. HiPri() {3. setPriority(10);4. }5.6
. public void run() {7. System.out.println(8.
"Another thread starting up.");9. while (true) { }10. }1
1.12. public static void main(String args[]) {13. HiPri hp1 = n
ew HiPri();14. HiPri hp2 = new HiPri();15. HiPri hp3 = n
ew HiPri();16. hp1.start();17. hp2.start();18.
hp3.start();19. }20. }|None of the above scenarios can be guaranteed to
happen in all cases.
Which one statement is true about the following code fragment? (choose 1)1. impo
rt java.lang.Math;2. Math myMath = new Math();3. System.out.println("cosine of 0
.123 = " + myMath.cos(0.123));| Compilation fails at line 2.
Which one statement is true about the following code fragment?1. String s = "FPT
";2. StringBuffer s1 = new StringBuffer("FPT");3. if (s.equals(s1))4. s1 =
null;5. if (s1.equals(s))6. s = null;| Compilation succeeds. No exception i
s thrown during execution.
Which one statement is true about the following code?1. String s1 = "abc" + "def
";2. String s2 = new String(s1);3. if (s1 == s2)4. System.out.println("== s
ucceeded");5. if (s1.equals(s2))6. System.out.println(".equals() succeeded"
);| Line 6 executes and line 4 does not.
Which one statement is true concerning the following code?1. class Greebo extend
s java.util.Vector implements Runnable {2.3. public void run(String mess
age) {4. System.out.println("in run() method: " + message);5.6.
}7. }8.9. class GreeboTest {10. public static void main
(String args[]) {12. Greebo g = new Greebo();13.
Thread t = new Thread(g);14. t.start();
15. }16. }|There will be a compiler error, because class Greebo
does not correctly implement the Runnable interface.
Which statement is true about the following code fragment? (Choose one.)1. int j
= 2;2. switch (j) {3. case 2:4. System.out.println("value is two
");5. case 2 + 1:6. System.out.println("value is three");7.
break;8. default:9. System.out.println("value is " + j);10.
break;11. }|The output would be the text value is two followed by the te
xt value is three.
Which statement is true about the following method?int selfXor(int i) { retur
n i ^ i;}|It always returns 0.
Which statement is true about this application? (Choose one.)1. class StaticStuf
f2 {3. static int x = 10;4.5. static { x += 5; }6.7. public stati
c void main(String args[])8. {9. System.out.println("x = " + x);1
0. }11.12. static {x /= 5; }13. }|The code compiles and execution produces
the output x = 3.
Which statement is true about this code? (Choose one.)1. class HasStatic2. {3.
private static int x = 100;4.5. public static void main(String args[]
)6. {7. HasStatic hs1 = new HasStatic();8. hs1.x++
;9. HasStatic hs2 = new HasStatic();10. hs2.x++;11.
hs1 = new HasStatic();12. hs1.x++;13. HasStatic.x++;14.
System.out.println("x = " + x);15. }16. }|The program compiles a
nd the output is x = 104.
Which statements about JDBC are NOT true? (choose 2)|JDBC is a Java database sy
stem.,JDBC is a Java API for connecting to any kind of DBMS
Which two code fragments correctly create and initialize a static array of int
elements? (Choose two.)|static final int[] a = { 100,200 };static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
Which two of the following interfaces are at the top of the hierarchies in the J
ava Collections Framework? (Choose two.)|Map+Collection
You execute the following code in an empty directory. What is the result? (Choos
e one.)1. File f1 = new File("dirname");2. File f2 = new File(f1, "filename");|N
o directory is created, and no file is created.
You have been given a design document for a veterinary registration system for i
mplementation in Java. It states:"A pet has an owner, a registration date, and a
vaccination-due date. A cat is a pet that has a flag indicating if it has been
neutered, and a textual description of its markings."Given that the Pet class ha
s already been defined and you expect the Cat class to be used freely throughout
the application, how would you make the opening declaration of the Cat class, u
pto but not including the first opening brace? Use only these words and spaces:
boolean, Cat, class, Date, extends, Object, Owner, Pet, private, protected, publ
ic, String.(Choose one.)|public class Cat extends Pet
You have been given a design document for a veterinary registration system for i
mplementation in Java. It states:"A pet has an owner, a registration date, and a
vaccination-due date. A cat is a pet that has a flag indicating whether it has
been neutered, and a textual description of its markings."Given that the Pet cla
ss has already been defined, which of the following fields would be appropriate
for inclusion in the Cat class as members? (Choose two.)|boolean neutered;String
markings;
The defauft type of the Result et object |TYPE_FORWARD_ONLY
Suppose the declared type of x is a class, and the declared type of y is an inte
rface. When is the assignment x =y, legal?|When the type of x is Object
In RMI implementations, all methods, declared in the remote interface, must thro
w the ...exception| RemoteException
Suppose salaries is an array containning floats. Which of the following are vail
d loop control statements for processing each element of salaries?| for(int i:sa
laries)
How can you force garbage collection of an object|Garbage collection cannot be f
orced
Which of the followings satement is true|FlowLayout is the default layout manage
r for every JFrame
static boolean b1=false; static int i = -1; static double d = 10.1;| b=m; d=i;
public class Abs extends Base { public static void main(String argv[]){ Abs a =
new Abs(); a.amethod();}|The code will compile and run, printinh out the words
Which of the following statements is true about two base protocols used for netw
orking TCP and UDP | TCP and UDP are connection-based protocols
class in the primary class that has the driver information| DriverManager
Which of the following methods of the java.io.File can be used to create a newfi
le| creaeNewFile()
Which of the following statements is INCORRECT about a non-static synchronized m
ethod | It cannot call to a static synchronized method of the current class
The element method alters the contents of a Queue | False
The Swing component classes can be found in the ________________ package.| javax
.swing
There are two classes in Java to enable communication using datagrams namely. |
DataPacket and DataSocket
This question concerns the following class definition:1. package abcde; 2. 3. pu
blic class Bird { 4. protected static int referenceCount = 0; 5. pub
lic Bird() { referenceCount++; } 6. protected void fly() { /* Flap wings,
etc. */ } 7. static int getRefCount() { return referenceCount; } 8. } Whic
h statement is true about class Bird and the following class Parrot? (Choose one
.) 1. package abcde; 2. 3. class Parrot extends abcde.Bird { 4. public voi
d fly() { 5. /* Parrot-specific flight code. */ 6. } 7.
public int getRefCount() { 8. return referenceCount; 9. } 10.
} | Compilation of Parrot.java fails at line 7 because method getRefCount()
This question concerns the following class definition: 1. package abcde; 2. 3. p
ublic class Bird { 4. protected static int referenceCount = 0; 5. publ
ic Bird() { referenceCount++; } 6. protected void fly() { /* Flap wings, et
c. */ } 7. static int getRefCount() { return referenceCount; } 8. } Which s
tatement is true about class Bird and the following class Nightingale? (Choose o
ne.) 1. package singers; 2. 3. class Nightingale extends abcde.Bird { 4. Ni
ghtingale() { referenceCount++; } 5. 6. public static void main(String args
[]) { 7. System.out.print("Before: " + referenceCount); 8. N
ightingale florence = new Nightingale(); 9. System.out.println(" After
: " + referenceCount); 10. florence.fly(); 11. } 12. } | Before: 0
After: 2.
This question involves IOException, AWTException, and EOFException. They are all
checked exception types. IOException and AWTException extend Exception, and EOF
Exception extends OException. uppose class X contains the following method: void
doSomething() throws IOException{ } Which of the following methods may appear
in class Y, which extends X? (Choose three.) | void doSomething() { }
This question involves IOException, AWTException, and EOFException. They are all
checked exception types. IOException and AWTException extend Exception, and EOF
Exception extends OException. uppose class X contains the following method: void
doSomething() throws IOException{ } Which of the following methods may appear
in class Y, which extends X? (Choose three.) | void doSomething() throws EOFExce
ption { }
This question involves IOException, AWTException, and EOFException. They are all
checked exception types. IOException and AWTException extend Exception, and EOF
Exception extends OException. uppose class X contains the following method: void
doSomething() throws IOException{ } Which of the following methods may appear
in class Y, which extends X? (Choose three.) | void doSomething() throws IOExcep
tion, EOFException { }
URL referring to databases use the form: | protocol:subprotocol:datasoursename
What are the legal types for whatsMyType? (Choose one.) short s = 10; whatsMyTy
pe = !s; | There are no possible legal types.
What does the following code do? Integer i = null; if (i != null & i.intValue()
== 5) System.out.println("Value is 5"); | Throws an exception.
What does the following code fragment print out at line 9? (Choose one.) 1. File
OutputStream fos = new FileOutputStream("xx"); 2. for (byte b=10; b<50; b++) 3.
fos.write(b); 4. fos.close(); 5. RandomAccessFile raf = new RandomAccessFil
e("xx", "r"); 6. raf.seek(10); 7. int i = raf.read(); 8. raf.close() 9. System.o
ut.println( i = + i); | The output is i = 20.
What does the following code print? public class A { static int x; p
ublic static void main(String[] args) { A that1 = new A();
A that2 = new A(); that1.x = 5; that2.x = 1000;
x = -1; System.out.println(x); } } | -1
What happens when you try to compile and run the following application? (Choose
one.) 1. import java.io.*; 2. 3. public class Xxx { 4. public static void m
ain(String[] args) { 5. try { 6. File f = new File("xxx
.ser"); 7. FileOutputStream fos = new FileOutputStream(f); 8.
ObjectOutputStream oos = new ObjectOutputStream(fos); 9.
oos.writeObject(new Object()); 10. oos.close(); 11.
fos.close(); 12. } 13. catch (Exception x) { } 14. } 15. }
| An exception is thrown at line 9.
What happens when you try to compile and run the following code? public class Q
{ static String s; public static void main(String[] args) {
System.out.println(">>" + s + "<<"); } } | The code compiles, and prin
ts out >>null<<
What happens when you try to compile and run this application? (Choose one.) 1.
import java.util.*; 2. 3. public class Apple { 4. public static void main(
String[] a) { 5. Set<Apple> set = new TreeSet<Apple>(); 6. s
et.add(new Apple()); 7. set.add(new Apple()); 8. set.add(new
Apple()); 9. } 10. } | An exception is thrown at line 7.
What is -50 >> 2 | -13
What is 7 % -4? | 3
What is -8 % 5? | -3
What is the difference between the rules for method-call conversion and the rule
s for assignment conversion? (Choose one.) | There is no difference; the rules
are the same.
What is the minimal modification that will make this code compile correctly? (Ch
oose one.) 1. final class Aaa 2. { 3. int xxx; 4. void yyy() { xxx =
1; } 5. } 6. 7. 8. class Bbb extends Aaa 9. { 10. final Aaa finalref = ne
w Aaa(); 11. 12. final void yyy() 13. { 14. System.out.p
rintln("In method yyy()"); 15. final ref.xxx = 12345; 16. } 17
. } | On line 1, remove the final modifier.
What is the range of values that can be assigned to a variable of type byte? (Ch
oose one.) | -2^7 through 2^7 - 1
What is the range of values that can be assigned to a variable of type short? (C
hoose one.) | -2^15 through 2^15 - 1
What is the result of attempting to compile and execute the following code fragm
ent? Assume that the code fragment is part of an application that has write perm
ission in the current working directory. Also assume that before execution, the
current working directory does not contain a file called datafile. (Choose one.)
1. try { 2. RandomAccessFile raf = new 3. RandomAccessFile("datafile
" ,"rw"); 4. BufferedOutputStream bos = new BufferedOutputStream(raf); 5.
6. DataOutputStream dos = new DataOutputStream(bos); 7. 8.
dos.writeDouble(Math.PI); 9. dos.close(); 10. bos.close(); 11. raf.clo
se(); 12. } 13. catch (IOException e) { } | The code fails to compile.
What is the return type of the instanceof operator? | A boolean
What method of the java.io.File class can create a file on the hard drive? (Choo
se one.) | createNewFile()
What results from attempting to compile and run the following code? 1. public cl
ass Conditional { 2. public static void main(String args[]) { 3.
int x = 4; 4. System.out.println("value is " + ((x > 4) ? 99.99
: 9)); 5. } 6. } | The output: value is 9.0
What results from running the following code? 1. public class Xor { 2. pub
lic static void main(String args[]) { 3. byte b = 10; // 00001010 bi
nary 4. byte c = 15; // 00001111 binary 5. b = (byte)(b
^ c); 6. System.out.println("b contains " + b); 7. } 8. } | T
he output: b contains 5
What would be the output from this code fragment? 1. int x = 0, y = 4, z = 5; 2
. if (x > 2) { 3. if (y < 5) { 4. System.out.println("message one
"); 5. } 6. else { 7. System.out.println("message two"); 8.
} 9. } 10. else if (z > 5) { 11. System.out.println("message three");
12. } 13. else { 14. System.out.println("message four"); 15. } | message f
our
When a byte is added to a char, what is the type of the result? | int
When a negative byte is cast to a long, what are the possible values of the resu
lt? (Choose one.) | Negative
When a negative long is cast to a byte, what are the possible values of the resu
lt? (Choose one.) | All the above
When a short is added to a float, what is the type of the result? | float
When comparing java.io.BufferedWriter to java.io.FileWriter, which capability ex
ists as a method in only one of the two? (Choose one.) | writing a line separat
or to the stream
When does an exception's stack trace get recorded in the exception object? (Choo
se one.) | When the exception is constructed
When is it appropriate to pass a cause to an exception's constructor? (Choose on
e.) | When the exception is being thrown in response to catching of a different
exception type
When is it appropriate to write code that constructs and throws an error? (Choos
e one.) | Never
When is x & y an int? (Choose one) | Sometimes
When the user attempts to close the frame window, _______ event in generated. |
window closing
When the user selects a menu item, _______ event is generated. | Action event
When you compile a program written in the Java programming language, the compile
r converts the human-readable source file into platform-independent code that a
Java Virtual Machine can understand. What is this platform-independent code call
ed? | bytecode
Whenever a method does not want to handle exceptions using the try block, the __
______ is used. | throws
Which are the correct statements used for getting connection object to connect t
o SQL Server database? | String url ="jdbc:odbc:data_source_name";
Which class and static method can you use to convert an array to a List? (Choos
e one.) | Arrays.asList
Which is four-step approach to help you organize your GUI thinking. (Choose one.
) | Identify needed components Isolate regions of behavior.
Which is the four steps are used in working with JDBC? | 1)Connect to the datab
ase
Which JDBC processing model that requires a JDBC driver that can communicate wi
th the particular data source being accessed? | two-tier
Which line of code tells a scanner called sc to use a single digit as a delimite
r? (Choose one.) | sc.useDelimiter("\\d");
Which Man class properly represents the relationship "Man has the best friend wh
o is a Dog"? (Choose one.)| class Man { private Dog bestFriend; }
Which methods return an enum constant s name? (Choose two.) | name() toString()
Which modifier or modifiers should be used to denote a variable that should not
be written out as part of its class's persistent state? (Choose the shortest pos
sible answer.) | transient
Which of the following are legal argument types for a switch statement? (Choose
three.) | byte int char
Which of the following are legal enums? (Choose three.) | enum Animals { LION, T
IGER, BEAR }
Which of the following are legal enums? (Choose three.) | enum Animals { LION, T
IGER, BEAR; int weight;}
Which of the following are legal enums? (Choose three.) | enum Animals { LION(45
0), TIGER(450), BEAR; int weight; Animals() { } Animals(int w) {weight = w;}}
Which of the following are legal import statements? (Choose two.) | import java
.util.Vector; import static java.util.Vector.*;
Which of the following are legal loop constructions? (Choose one.) | int j = 0;
for
Which of the following are legal loop definitions? (Choose one.) | None of the a
bove
Which of the following are legal? (Choose three.) | for (int i=0, j=1; i<10; i++
, j++)
Which of the following are legal? (Choose three.) | for (int i=0, j=1;; i++, j++
)
Which of the following are legal? (Choose three.) | for (String s = ""; s.length
()<10; s += '!')
Which of the following are legal? (Choose two.) | double d = 1.2d;
Which of the following are legal? (Choose two.) | double d = 1.2D;
Which of the following are legal? (Choose two.) | int c = 0xabcd;
Which of the following are legal? (Choose two.) | int d = 0XABCD;
Which of the following are legal? (Choose two.) | char c = 0x1234;
Which of the following are legal? (Choose two.) | char c = '\u1234';
Which of the following are legal? (Choose two.) | <String>()
Which of the following are methods of the java.util.SortedMap interface? (Choose
three.) | Map
Which of the following are methods of the java.util.SortedSet interface? (Choose
one.) | All the above
Which of the following are true? (Choose one.) | All the above
Which of the following are true? (Choose one.) | The JVM runs until there are n
o non-daemon threads.
Which of the following are true? (Choose three.) | When an application begins ru
nning, there is one non-daemon thread, whose job is to execute main().
Which of the following are true? (Choose three.) | A thread created by a daemon
thread is initially also a daemon thread.
Which of the following are true? (Choose three.) | A thread created by a non-dae
mon thread is initially also a non-daemon thread
Which of the following are true? (Choose two.) | When you declare a method ...
object
Which of the following are true? (Choose two.) | When you declare a block ... s
ynchronize
Which of the following are true? (Choose two.) | An enum may contain public meth
od definitions
Which of the following are true? (Choose two.) | An enum may contain private dat
a
Which of the following are true? (Choose two.) | Primitives are passed by value.
Which of the following are true? (Choose two.) | References are passed by value.
Which of the following are true? (Choose two.) | An anonymous inner class may im
plement at most one interface.
Which of the following are true? (Choose two.) | An anonymous inner class may ex
tend a parent class other than Object.
Which of the following are valid arguments to the DataInputStream constructor? (
Choose one.) | FileInputStream
Which of the following are valid mode strings for the RandomAccessFile construct
or? (Choose one.) | All the above
The readLine() method of the RandomAccessFile class return false when it has rea
ched the end of a file The readLine() method of the RandomAccessFile class retu
rn null when it has reached the end of a file The readLine() method of the Rando
mAccessFile class return true when it has reached the end of a file | return fa
lse
The container can display three completely different components at different tim
es, depending perhaps on user input or program state. Even if the components' si
zes differ. switching from one component to the next shouldn't change the amount
of space devoted to the component. | GridLayout
Assuming any exception handling has been set up, which of the following will cre
ate an instance of the RandomAccessFile class? | ("myfile.txt","rw")
Which of the following statements is INCORRECT about a non-static synchronized m
ethod? | It cannot call to a static synchronized
Which of the following statements is true about two base protocols used for netw
orking: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) |
TCP is a connection-based
Which of the following statements about this code is true? public class Morecomb
e{ public static void main(String argva)( Morecombe m = new MorecombeQ; m.go(new
TuringQ{}); } public void go(Turing t){ t.start(): } } class Turing extends Thr
ead{ public void run(){ for(int i =0: i < 2: i++){ System.out.println(i): } } }
| Compilation and output of 0 followed by 1
Which of the following collections supports accessing elements through keys and
values? | HashSet
What is the difference between a TextArea and a TextField? | TextAreas are used
for displaying graphics
What will be output if you try to compile and run the following code, but there
is no file called Hello.bct in the current directory?. import java.io.*: public
class Mine ( public static void main(String argv0){ Mine m=new Mine(); System.ou
t.println(m.amethod()); } public int amethod() ( try{ FilelnputStream dis=new Fi
lelnputStream("Hello.bd"); }catch (FileNotFoundException fne) { System.outprintl
n("No such file found"); return -1; }catch(10Exception ioe) { } finally{ System.
out.println("Doing finally"); } return 0; | No such file found, Doing finally,
-1
What will happen when you attempt to compile and run the following code? public
class Main{ A ? A public static void main(String argv0){ At= new A("One"); ? B t
rump; A h = new A("Two"); ? C limn(); ? D } } class A extends Thread{ private St
ring sTname=""; A(String s){ sTname = s; I Ned I 1 public void rump{ for(int i =
0; i <2: i-){ try{ sleep(1000); }catch(InterruptedException e){} yield(); System
.outprint(sTname + ""); } } } | Output One two One two
Which of the following statements is true? | the client knows the hostname of th
e machine on which the server is running and the port number on which the server
is listening
What is the output when you try to compile and run the following program? ? A pu
blic class Main{ static void foo(String x) {System.out.println("String");} 1:1 B
static void foo(StringBuffer y) {System.outprintln("StringBuffer);} static void
foo(Integer z) {System.outprintInrInteger");} ? C public static void main(Strin
g argv0){ f(null): ? D System.outprintinQ; ? | No output compile-time error
Which of the followings statements is true? | GridLayout simply makes a bunch of
components equal in size and displays them in the requested number of rows and
columns
Answer RMI applications often comprise two separate programs. a server and a cli
ent and they | Must run in two separate computers
How can you change the current working directory using an instance of the File c
lass called FileName? | The File class does not support directly changing the c
urrent directory
What happens when you try to compile and run the following program? A D A import
java.util.*; B public class Main{ public static void main(String argv[]){ D c V
ector<lnteger> t = new Vector<lnteger>(); t.add(12r; D D t.add(2); t.add(6); t.a
dd(2.4); lterator<lnteger> i = t.iterator(); int sum=0; Next while(i.hasNext())
sum += i.next(); System.out.println(sum); | The program has a compile error
Select correct statement(s): (choose one option) (1) A thread can be an instance
of the java.lang.Thread class. D A (2) A thread can be an instance of a subclas
s of the java.lang.Thread class. D B (3) An instance of a class which implements
the java.lang.Runnable can supply the executable code for a thread object. | 1
2 3
The default type of the ResultSet object is : | TYPE_FORWARD_ONLY
What will be output when the following code is run? class Test 0 A {public int f
un(intx) {int count=1; D 3 try{ count += )c [I C foo(count); count++z D D }catch
(Exception e) { count 0: )c} return(count); D E public int foo(int k) {if(true)
throw new ArithmeticExceptionO; return(k); Next class Main {public static void
main(String [] args) {Testt = new TestO: System.out.println(t.fun(2)); | 1
Which of the following statements is true? | A for state ent can loop infinitely
, for example: for(;;)
Which of the following most closely describes the process of overriding? | A met
hod with the same name but different parameters
Fill the blanks: (1) The java.io. class makes it easier to write platform-indepe
ndent code that examines and manipulates files. D A (2) The Java.io. class makes
it easier to write platform-independent code that examines and manipulates fold
ers. | File, File
What interfaces can be implemented in order to create a class that can be serial
ized? | implements java.io.Serializable, which defines two methods: readObject a
nd writeObject
Answer Select correct statement: E] | Both String and StringBuffer objects are n
ot constants.
What is the output when you try to compile and run the following program? public
class Main{ public static void main(String argvfl){ String s = "Hi there"; int
pos = s.indexof(" ")1 String r= s.substring(0. pos): String s2 = new String(new
char[] {'H'.'i'}): if(r.equals(s2)) System.out.println("EQUAL"): else System.out
println("NOT EQUAL"): System.out.println(): | not equal
Which of the following modifiers does not allow a variable to be modified its va
lue once it was initialized? | final
Which is the first step of four-step approach to help you organize your GUI thin
king? | Identify needed components.
What will happen when you attempt to compile and run the following code? class B
ase{ Base(){ System.out.println("Base"); public class Checket extends Base{ pub
lic static void main(String argv[]){ Checket c = new ChecketO; super(); Checket
o{ Systemoutprintln("Checket"); | runtime error
With respect to networking and the client-server model. (1) A socket is one end
point (a combination of an IP address and a port number) of a two-way communicat
ion link between two programs running on the network.. (2) TOP (Transmission Co
ntrol Protocol) is a connection o based protocol that provides a reliable flow o
fdata between two computers. (3) UDP (User Datagram Protocol) is a protocol tha
t sends independent packets of data. called datagrams. from one computer to anot
her with no guarantees about arrival. | True. true. true
Which of the following is NOT an example of a data type. | button
Which of the following is true? | The Iterator interface is used to step throug
h the elements of a Collection
What will happen when you compile and run the following code? public class Scope
{ private int i; public static void main(String argv[]){ Scope s = new ScopeO: s
.amethodo: End of main public static void amethodo{ System.out.println(i); end
of a method End of class | A compile time error
Which statement is true of the following code? 10. public class Agg{ 11. publi
c static void main(String argvfl){ 12. A99 a = new A990: 13. a.go(): 14. 15.
public void goO{ 16. DSRoss ds1 = new DSRoss("one"); 17. ds1.starto: 18. 19
. 20. class DSRoss extends Thread{ 21. private String sTname="": 22. DSRoss(S
tring s){ 23. sTname = s: | Runtime error. an exception will be thrown
What will happen when you attempt to compile and run the following code? public
class Agg{ static public long i=10; public static void main(String argv[]){ swit
ch(i){ default System.out.println("no value given"); case 1: System.out.prin
tln("one"); case 10: System.outprintln("ten"); case 5: System.outprintln("fi
ve"): | Compile time error
Which of the following statements is true? | To be overriden method must have th
e same name. parameter and return types
With respect to JDBC. which statement is NOT CORRECT? | In the three-tier mode
l. a "middle tier" of services is let
Which of the following statements is true? | Interfaces are the Java approach t
o addressing
Select an incorrect identifier in Java. | &x
Consider the following code developed in NetBeans. What does the thread t do? |
It wiII show a full of formatted current date in the jLabeI1
Which of the following is a method of the Runnable interface? | run
Which of the following is valid method?| static native void amethod
Select an operation which may cause an unchecked exception. | ControIIing the st
ate of a running thread
Which of the following is true? | An enum may contain public method definitions
.
Which of the following layout manager will present components with the same size
. | java.awt.GridLayout
What will happen when you attempt to compile and run the following program: 10.
abstract class A{ 11. int x=5: 12. void foo() 13. System.out.print("x = " + x
); 14. 15. 16. class Main 17. static void foo(lnteger x){ 18. System.out.p
rint(x); 19. 20. public static void main(String[] args){ 21. At: newAo{ 22. p
ublic void fooO{ 23. System.outprint("Hello"); 24. 25. 26. tfooO: 27. 28
. | The output is Hello
What will happen when you attempt to compile and run the following code int Outp
ut=10: boolean b1 =false: if((b1==true) 8.8. ((Output+=10)==20)){ System.out.pri
ntln("We are equal "+Output); else System.out.println("Not equal! "+Output);
| Compilation and output of "Not equal! 10"
is applied in a class. is applied in a class hierarchy. | Method generalizatio
n. method specification
What will happen when you attempt to compile and run the following code import j
ava.io.*;class Base{ public void amethod()throws FileNotFoundException{}}publ
ic class ExcepDemo extends Base{ public static void main(String argv[]){
ExcepDemo e = new ExcepDemo(); } public void amethod(){} protected Exce
pDemo(){ try{ DataInputStream din = new DataInputStream(System.in)
; System.out.println("Pausing"); din.readByte(); Syst
em.out.println("Continuing"); this.amethod(); }catch(IOException ioe)
{} }}|Compile and run with output of "Pausing" and "Continuing" after a key i
s hit
What will happen when you attempt to compile and run this programpublic class Ou
ter{public String name = "Outer";public static void main(String argv[]){
Inner i = new Inner(); i.showName(); }//End of main private cla
ss Inner{ String name =new String("Inner"); void showName(
){ System.out.println(name); } }//E
nd of Inner class}|Compile time error because of the line creating the instance
of Inner
What will happen when you attempt to compile and run this code//Demonstration of
event handling import java.awt.*;import java.awt.event.*;public class MyWc exte
nds 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|Error at compile time
Which option most fully describes will happen when you attempt to compile and ru
n the following code public class MyAr{ public static void main(String argv[]
) { MyAr m = new MyAr(); m.amethod(); } public void amethod(
){ static int i; System.out.println(i); }}|Compile time error
Which of the following will compile correctly|int z = 015;
Which of the following are Java key words|double + instanceof
What will be output by the following line?System.out.println(Math.floor(-2.1));|
-3.0
Given the following main method in a class called Cycle and a command line ofjav
a Cycle one twowhat will be output?public static void main(String bicycle[]){
System.out.println(bicycle[0]);}|one
Which of the following statements are true?|The Set is designed for unique eleme
nts.
Which of the following statements are correct?|If multiple listeners are added t
o a component the events will be processed for all but with no guarantee in the
order,You may remove as well add listeners to a component.
Given the following code class Base{}public class MyCast extends Base{ static
boolean b1=false; static int i = -1; static double d = 10.1; public st
atic void main(String argv[]){ MyCast m = new MyCast(); Base b = n
ew Base(); //Here }}Which of the following, if inserted at the comment
//Here will allow the code to compile and run without error| 1) b=m;3) d =i;
Which of the following statements about threading are true|You can obtain a mutu
ally exclusive lock on any object, A thread can obtain a mutually exclusive lock
on an object by calling a synchronized method on that object. ,Thread schedulin
g algorithms are platform dependent
Your chief Software designer has shown you a sketch of the new Computer parts sy
stem she is about to create. At the top of the hierarchy is a Class called Compu
ter and under this are two child classes. One is called LinuxPC and one is calle
d WindowsPC.The main difference between the two is that one runs the Linux opera
ting System and the other runs the Windows System (of course another difference
is that one needs constant re-booting and the other runs reliably). Under the Wi
ndowsPC are two Sub classes one called Server and one Called Workstation. How mi
ght you appraise your designers work?|Ask for a re-design of the hierarchy with
changing the Operating System to a field rather than Class type
Which of the following statements are true|An inner class may be defined as stat
ic + An inner class may extend another class
What will happen when you attempt to compile and run the following code int Outp
ut=10;boolean b1 = false;if((b1==true) && ((Output+=10)==20)){ System.out.pri
ntln("We are equal "+Output); }else { System.out.println("Not equal! "+
Output);}|Compilation and output of "Not equal! 10"
Given the following variables which of the following lines will compile without
error?String s = "Hello";long l = 99;double d = 1.11;int i = 1;int j = 0;
1) j= i <<s;
2) j= i<<j;
3) j=i<<d;4)j=i<<l;|j= i<<j;j=i<<l;
What will be output by the following line of code?System.out.println(010|4);|12
Given the following variables char c = 'c';int i = 10;double d = 10;long l = 1;S
tring s = "Hello";Which of the following will compile without error?|s+=i;
Which of the following will compile without error?| File f = new File("/","autoe
xec.bat");DataInputStream d = new DataInputStream(System.in);OutputStreamWriter
o = new OutputStreamWriter(System.out);
Given the following classes which of the following will compile without error?in
terface IFace{}class CFace implements IFace{}class Base{}public class ObRef exte
nds Base{ public static void main(String argv[]){ ObRef ob = new ObRef
(); Base b = new Base(); Object o1 = new Object(); IFace o2
= new CFace(); }}|o1=o2;b=ob;o1=b;
Given the following code what will be the output?class ValHold{ public in
t i = 10;}public class ObParm{public static void main(String argv[]){ ObP
arm o = new ObParm(); o.amethod(); } public void amethod(){
int i = 99; ValHold v = new ValHold();
v.i=30; another(v,i); System.out.print( v.i )
; }//End of amethod public void another(ValHold v, int i){
i=0; v.i = 20; ValHold vh = new ValHold();
v = vh; System.out.print(v.i); System.out
.print(i); }//End of another}|10020
Given the following class definition, which of the following methods could be le
gally placed after the comment//Here public class Rid{ public void ametho
d(int i, String s){} //Here}|public void amethod(String s, int i){} + pu
blic void Amethod(int i, String s) {}
Given the following class definition which of the following can be legally place
d after the comment line//Here ?class Base{public Base(int i){}}public class MyO
ver extends Base{public static void main(String arg[]){ MyOver m
= new MyOver(10); } MyOver(int i){ super(i)
; } MyOver(String s, int i){ this(i);
//Here }}|Base b = new Base(10);
Given the following class definition, which of the following statements would be
legal after the comment //Here class InOut{String s= new String("Between");
public void amethod(final int iArgs){ int iam; class Bicy
cle{ public void sayHello(){ //Here
} }//End of bicycle class }//End o
f amethod public void another(){ int iOther; }}|System.out.pri
ntln(s);System.out.println(iArgs);
Which of the following are methods of the Thread class?|yield()+sleep+stop()
Which of the following methods are members of the Vector class and allow you to
input a new element| addElement
Which of the following statements are true?|A inner class may under some circums
tances be defined with the protected modifier + An interface cannot be instantia
ted
Which of the following are correct event handling methods|mousePressed(MouseEven
t e){} + componentAdded(ContainerEvent e){}
Which of the following are methods of the Collection interface?|iterator + isEmp
ty + toArray
Which of the following best describes the use of the synchronized keyword?|Ensur
es only one thread at a time may access a method or object
... exist within a ... Every ... has at least one...|Threads, process, process,
thread
Multithreaded execution is an essential feature of the Java platform. Every appl
ication has at least ... thread(s).|None of the others
An application that creates an instance of Thread must provide the code that wil
l run in that thread. Select a correct way to do this.|Provide a Runnable object
. The Runnable object is passed to the Thread constructor.
if an object is visible to more than one thread, all reads or writes to that obj
ect's variables should be done through ... methods.|None of the others
Select correct statement(s).(1) A process has a self-contained execution environ
ment.(2) A sub-thread has a self-contained execution environment.(3) Programmers
can schedule sub-threads of a program. |1
Two sub-threads of a program may not need synchronized if |They do not access any
common resource.
(1) An object having synchronized methods is called a( an ) .(2) The technique can b
applied with a hope that a deadlock situation may not occur in a program .(3) T
he sleep( ) method of the java.lang.Thread class accepts a argument that specifie
s a( an ) . |Monitor, wait-notify, specific period of time.
As soon as a Java thread is created, it enters the .. state.|ready
Thread synchronization should be implemented if .....|Threads access common reso
urces.
Which of the following statements is correct about Thread?|During its lifetime,
a thread spends some time executing and some time in any of non-executing states
.
Which of the following statement is correct about Thread?|When the run() method
of a thread returns, that thread is put into ready state.
Which method is NOT a member the Object class?|waitAll()
When a thread begins waiting an IO operation, it enters the .. state.|blocked
In multi-processing system,|Each process usually accesses its own data.
_____ exist within a ____ - every _____ has at least one.|Theads, process, proce
ss.
Multithreaded execution is an essential feature of the Java platform. Every appl
ication has at least _____ thread(s).|one
An application that creates an instance of Thread must provide the code that wil
l run in that thread. Select a correct way to do this.|Provide a Runnable object
. The Runnable object is passed to the Thread constructor.
if an object is visible to more than one thread, all reads or writes to that obj
ect's variables should be done through ____ methods.|synchronized
Select a correct statement.|Deadlock describes a situation where two or more thr
eads are blocked forever, waiting for each other.
Which of the following statements is true?|A thread must obtain the lock of the
object it is trying to invoke a synchronized method.
Which of the following methods causes a thread to release the lock of the object
that it is currently holding?|wait()
The muti-threaded programming is used .|when some tasks must be performed concurre
ntly.
The muti-threaded programming is used .|when a task must be performed at un-predic
table time.
Race condition may happen when:|More than one threads access the shared data of
the application.
To create a thread in Java, we can:|Create a subclass of the java.lang.Thread cl
ass and override the method run().
Select correct priority values of a thread (Integer values only):|From 1 to 10
Which of the following options is not a thread state?|Indelayed
With respect to threads in Java, select a correct statement.|The main method (en
try point of a Java program) is a default thread.
if an object may be accessed by some threads. These accesses should be done thro
ugh ____ methods.|Synchronized
Select the best choice.|Deadlock describes a situation where two or more threads
are blocked forever, waiting for each other.
Race condition may happen if:|There is more than one threads access the shared d
ata of the application.
Which of the following options is not a valid thread priority property?|AVERAGE_
PRIORITY
When is a thread considered as a dead thread?|When the run() method terminates.
When is a thread started running?|The Scheduler decides when a thread is started
running.
The Java Collection framework is implemented in the ...package.|None of the othe
rs.
In order to use the TreeSet class, the class that describes elements must implem
ent the ... interface.|java.lang.Comparable
All of the numeric wrapper classes in the java.lang package are subclasses of th
e abstract class ...|java.lang.Number
String S= "Hello"; String S2= new String("Java Program"); The String class descr
ibes an immutable chain of Unicode characters. Select a statement that causes an
error.|None of the others.
Study the following code was implemented in the Hello class:static void print(In
teger obj){ System.out.println(obj); } And it is used as:Integer obj= new Intege
r(5); int n= obj; //(1) Hello.print( n ); //(2) A .. operation is carried out
at the code line (1)A .. operation is carried out at the code line (2)|Unboxing,
boxing
The top interface of the Java Collection Framework is .|Collection
If we want to store a group of different elements in ascending order, the java.u
til. class should be used.|SortedSet
An instance of the java.util.Scanner class can read data from the keyboard (1),
a file (2), a string of characters (3).(1) is ., (2) is ., and (3) is ..|true, true,
ue
Given a string constructed by calling s = new String( "xyzzy" ), which of the ca
lls modifies the string? (Choose one.)|None of the others.
Which one statement is true about the following code?1. String s1 = "abc" + "def
";2. String s2 = new String(s1);3. if (s1 == s2)4. System.out.println("== succee
ded");5. if (s1.equals(s2))6. System.out.println(".equals() succeeded");|Line 6
executes and line 4 does not.
Which one statement is true about the following code fragment? (choose 1)1. impo
rt java.lang.Math;2. Math myMath = new Math();3. System.out.println("cosine of 0
.123 = " + myMath.cos( 0.123 ) ); |Compilation fails at line 2.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.) prim = wrapped; wrapped = prim;prim = new Int
eger( 9 ); wrapped = 9;|All the others.
Suppose that obj1 and obj2 are objects and they belong to the same class. Study
the semantics of following statements: (1) if (obj1==obj2) { } (2) if (obj1.equa
ls( obj2 )) { }|(1) and (2) are different.
A characteristic of generic technique is ......|It adds stability to the code by
making more of bugs detectable at compile time.
Suppose that obj1 and obj2 are reference variables. The expression obj1==obj2 wi
ll execute |a swallow comparison.
One of the difference about Lists and Sets:|A list can contain duplicate items b
ut a set can not.
Study the following Java statements: String s1= Hello ; String s2= Hello ; String s3= H
ello ;|There is only one string is stored in memory of the program.
Study the following Java statements: String S= William, Bill is ill. ; int index1=
S.indexOf( ill ); int index2= S.lastIndexOf( ill ); The value of index1 is .. and index2
is |1, 17
To traverse elements in a set, one after one element, the java.util. .interface mus
t be use|Iterator
The _____ class is the ultimate ancestor of all Java classes.|Object
The Java Collection framework is implemented in the ______ package.|java.util
In order to use the TreeSet class, the class that describes elements must implem
ent the ______ interface.|java.lang.Comparable
All of the numeric wrapper classes are subclasses of the abstract class ______.|
Number
String S= Hello ;String S2= new String( Hello );The String class describes an immutable
chain of Unicode characters. Select a statement that causes an error.|None of t
he others.
When invoking Math.random(), which of the following options might be the result?
|The result is less than 1.0
Which of the following statements is true about Object class?|By default, the eq
uals() method simply performs the == operator
Suppose that:- Your application has to read and write a string a lot of times. -
Your application does not need to have multi threaded supports.- Performance is
important.Which of the following classes will you choose to deal with string dat
a type to achieve the above requirements?|StringBuilder
Suppose that a homogenous collection of objects, that belong the same type, are
managed. Which of the following delarations is the best choice?|java.util.ArrayL
ist list;
Which of the following options is correct?|Values stored in TreeSet are not allo
wed duplication
Which of the following options is not a method of the Scanner class?|nextValue()
Which of the following collection cannot be used with Iterator class to traverse
through elements?|Array
Which of the following options is not a method of java.lang.Math Class?|None of
the others
Which of the following classes is the ultimate ancestor of all Java classes?|Non
e of the others
In Java Collection framework, which of the following pre-defined classes allow a
n element can be accessed through its index?|java.util.ArrayList
In which situation are generic collections used?|The collection contains homogen
ous elements.
Which of the following Java lists that allows data is stored in sorted order, an
d also, no duplicate data is allowed?|TreeSet
You are required to build a Java application. Your application uses Vector to st
ore data. Each time elements, taken from the vector, should be displayed to user
s in a random order. Which of the following methods can be used to achieve the a
bove task?|Collections.shuffle()
You are required to validate an email string taken from users. A valid email for
m should be email@address.com. Select a correct pattern that can be used to vali
date email input:|"^\w+@\w+[.]\w+$"
If we use Math.random() method to random a number, which of the following number
s will never be appeared?|1.0
An I/O Stream represents an input source or an output destination. A stream can
represent...| An I/O Stream represents an input source or an output destination.
A stream can represent...
The java.io.ObjectInputStream class is a subclass of the ...class.|java.io.Input
Stream
DataInputStream, DataOutputStream are binary streams, PrintWriter, BufferedReade
r are not binary streams ,ObjectInputStream, ObjectOutputStream are not text str
eams. |All of the others.
When reading objects from an object stream,|we usually use an explicit casting.
Select correct statement(s). (1) All byte stream classes are descended from the
InputStream andOutputStream classes . (2) All character stream classes are desce
nded from the Reader and Writer classes . (3) All byte stream classes are descen
ded from the Reader and Writer classes .(4) All character stream classes are des
cended from the InputStream andOutputStream classes .| 1, 2
To read data from a text file using the line-by-line accessing. The right order
of object creations is: | File FileReader - BufferedReader
To write objects to an object file. The right order of object creations is: | Fi
leOutputStream- ObjectOutputStream
(1) The java.io . class makes it easier to write platform-independent code that ex
amines and manipulates files. (2) The java.io. . class makes it easier to write pl
atform-independent code that examines and manipulates folders. |File, File
How do you use the File class to list the contents of a directory? (Choose one.)
|String[] contents = myFile.list();
Which of the following is true? (Choose one.) Readers have methods that can read
and return floats and doubles. Readers have methods that can read and return fl
oats. Readers have methods that can read and return doubles.| None of the others
Given the following class: public class Xyz implements java.io.Serializable { pu
blic int iAmPublic ; private int iAmPrivate ; static int iAmStatic ; transient
int iAmTransient ; } Assuming the class does not perform custom serialization,
which fields are written when an instance of Xyz is serialized?|iAmPublic, iAmPr
ivate
Which of the following are true? System.out has a println() method. System.out h
as a format() method.System.err has a println() method.System.err has a format (
) method.| All of the others.
When we access a file or directory metadata such as name, path, last modified ti
me, We should use the ........... class.|java.io.File
Suppose that you want reading some records stored in a text file, classes in the
java.io package can be used: (1) File, (2) FileInputStream, (3) RandomAccessFi
le, (4) FileReader (5) BufferedReader, (6) PrintWriter | (1), (4), (5)
Consider the following declaration: RandomAccessFile(File file, String mode) I
f the mode is declared as rws , what does it mean? | It means the file can be opene
d for both reading and writing, and any changes to the file s content or metadata
will take place immediately.
Two topmost abstract classes for character streams are ... and .|java.io.Reader, ja
va.io.Writer
The . class makes utilities to write platform-independent code that examines and m
anipulates folders.|java.io.File
To read/write objects from/to a file as object streams, the class declaration of
these objects must implement the marker interface ..|java.io.Serializable
An I/O Stream represents an input source or an output destination. A stream can
represent |All of the others
In _____ binary streams, a read/write data unit is _______.|low-level, general-f
ormat data
The ObjectInputStream is a subclass of the _____ class.|InputStream
Select a correct statement.DataInputStream, DataOutputStream are binary streams.
PrintWriter, BufferedReader are text streams. ObjectInputStream, ObjectOutputSt
ream are binary streams.|All of the others.
When reading objects from an object stream, we usually use _____.|an explicit cl
ass casting
Which of the following options is not a valid declaration of the RandomAccessFil
eclass?|RandomAccessFile r = new RandomAccessFile( file.txt , w );
In order to allow an object can be serialized into a file, which of the followin
g interfaces needs to be implemented?|java.io.Serializable
You are required to write a program that stores data retrieved from users to a t
ext file. The data must be stored line by line and in Unicode format. Which of t
he following classes is the best choice for storing tasks?|java.io.PrintWriter
Which of the following classes is not an abstract class?|None of the others.
We have the constructor of the java.io.RandomAccessFile class as follows: Rando
mAccessFile(String file, String mode) Which of the following options is not a va
lid value for the mode option? | w
Which of the following classes do not directly read from/write to input/output d
evices such as disk files or sockets; rather, they read from/write to other stre
ams? |DataInputStream/ DataOutputStream
Which of the following classes can be used to serialize an object into a file?|O
bjectOutputStream
Which of the following methods of the File class can be used to get the size of
a given file?|length()
A stream can represent .|All of the others.
The ObjectInputStream is a subclass of the . class.|None of the other.
When accessing objects in an object stream, we must .|Access them using a suitable
program.
Which of the following features is not supported by java.io.RandomAccessFile cla
ss?|Reading and writing data from and to a socket
You use java.io.RandomAccessFile to manipulate a file name myFile.txt. Which of
the following statements is valid if you want to open the file myFile.txt in a w
riting-only mode?|There is no writing-only mode in java.io.RandomAccessFile clas
s.
Which of the following classes are exclusively designed for writing and reading
Unicode characters?|FileReader/ FileWriter
Which of the following classes can be used for writing and reading objects (seri
alizing/de-serializing) from and to a file?|ObjectInputStream/ObjectOutputStream
Which method do you use to enable or disable components such as JButtons?|None o
f the others
A component that lets the user pick a color.|JColorChooser
The container has one component that should take up as much space as possible. W
hich layouts that easily deal with this situation should be selected?|GridLayout
Which component can display an image, but cannot get focus?|JLabel
Select correct statement(s). (1) Swing is part of the Java Foundation Classes an
d provides a rich set of GUI components. (2) Before you think about what your GU
I will look like , it s important to think about what it will |1, 2
Select correct statement(s).(1) The Swing's list component (JList) can display t
ext only. (2) The Swing s button (JButton) can not contain an image. (3) The Swing s
label (JLabel) can present an image. | 3
Which of the following layout manager will present components with the same size
. |java.awt.GridLayout
Select correct statement(s). (1) 12 buttons can not be added to a container whic
h is assigned to a grid layout 2x5.(2) If 2 components are added to the center r
egion of a border-layout container, they will be seen by user as side-by-side co
mponents. |None of the others.
Which is four-step approach to help you organize your GUI thinking. (Choose one.
)|Identify needed components. Isolate regions of behavior. Sketch the GUI. Choos
e layout managers
The Swing component classes can be found in the ________________ package.|javax.
swing
A _____ dialog prevents user input to other windows in the application unitl the
dialog is closed.|Modal
The border layout resizes the ______ components to fill the remaining centre spa
ce.|Center
The container can display three completely different components at different tim
es, depending perhaps on user input or program state. Even if the components size
s differ, switching from one component to the next shouldn t change the amount of
space devoted to the component.|CardLayout
Select incorrect statement about FlowLayout. (choose 1)|It is the default layout
manager type for JFrame.
In a complex GUI containing a lot of components and user must be select some dat
a in a group of specific data, the component should be used is .......|combo box
We can replace a card layout of a container with ..........|tabbed pane
Select an incorrect statement.|A combobox can contain strings only.
In Swing, what is the role of the component s model?|It is responsible for the dat
a that the component presents to the users.
Suppose that we have a combobox that contains a list of data. The combobox can o
nly display to the user one item at a time. In term of Model-View-Controller, wh
ich of the following statement is correct?|The list of data of the combobox can
be considered as a representative of the Model.
Which of the following statements is correct about Flow layout?|The Flow layout
arranges frames in horizontal rows.
Which of the following statement is correct about Card layout?|Card layout arran
ges components in time rather than in space.
Which method do you use to enable and disable components such as JButton s?|setE
nable
A component that lets the user pick a color.|color chooser
The container has one component that should take up as much space as possible. W
hich layouts that easily deal with this situation should be selected?|BorderLayo
ut or GridLayout
The container has a row of components that should all be displayed at the same s
ize, filling the container s entire area. Which layout is the best choice for this
purpose?|GridLayout
A component that displays an icon, but that doesn t react to user clicks|label
In JTree control, which of the following classes represents for one node?|Defaul
tMutableTreeNode
Which of the following layout managers will make all its components the same siz
e?|GridLayout
You are required to build a GUI application. The application has a main window w
hich displays: - A tool bar at the top - A status bar at the bottom - A menu on
the left - An information table on the right - A news board at the middle of the
window Which of the following layout managers would you choose to achieve the a
bove tasks?|BorderLayout
Suppose that the layout of the frame f is BorderLayout. Study the following stat
ement:g.getContentPane().add ( new JButton( B )); The button B will be let at the . r
egion of the frame. |None of the others.
Suppose you are building an application that connects to the database to store a
nd retreive data. Your application is built based on Model-View-Controller patte
rn. Which of the following components is responsible for connecting to the data
base?| Model.
Which of the following options is a method that you need to override when implem
enting the ActionListener interface?|actionPerformed()
You are building a table model class that extends the AbstractTableModel class.
Which of the following methods is not required to re-implement?|getColumnName()
Which of the following statements is not correct about JTree control?|Leaf nodes
are those that can have children.
Leaf nodes are those that can have children.|Textfield.requestFocus()
A swing container that groups some common components in a complex GUI.| JPanel
To make the background color of a label different with the color of its containe
r, we need to use the .. method of the JLabel class first. |setOpaque(true)
The default layout manager used by JPanel is:|FlowLayout
Which of the following layout classes is in java.awt package?|All of the others.
Which of the following layout managers arranges components in horizontal rows (l
eft to right in the order they were added to their container), starting new rows
if necessary?|Flow Layout
Which of the following layout managers subdivides its territory into a matrix of
rows and columns?|Grid Layout
With respect to the Java socket. (1) A socket contains two binary streams for se
nding and receiving data. (2) A socket contains two text streams for sending and
receiving data. (3) Developers must implement background operations for sending
and receiving data. | True, false, false
In a client-server application model, which sides will initiate a connection? |
Client
With respect to networking and the client-server model. (1) A server runs on a s
pecific computer and has a socket that is bound to a specific port number. The s
erver just waits, listening to the socket for a client to make a connection requ
est. (2) To connect to the server, the client must know the hostname or IP of th
e machine on which the server is running and the port number on which the server
is listening | True, true
In Windows systems, the program helps creating the Stub of a RMI server and the pr
ogram will work as a RMI container (RMI registry). | rmic.exe, rmiregistry.exe
Two streams are packed in a socket are ......... | InputStream and OutputStream
To implement RMI, classes need to be implemented: (1) Remote interface, (2) Serv
er object, (3) Server program, (4) Client program, (5) Stub object, (6) Transpor
t Object, (7) Remote reference Object | 1, 2, 3, 4, 5
Which of the following statement is correct about object serialization? | Transi
ent fields are not serialized
What is the role of RMI registry? | The RMI registry is a program that associate
s names with RMI services
Select correct statement. In RMI implementations, | The remote class must implem
ent the remote inteface
In Java Network programming using sockets, five steps are usually used: | 1, 2,
3, 4, 5
In a client-server application model, which side will wait for a connection? | s
erver
Suppose you are building a client server based application using TCP socket tech
nique. Assume at the same time, 5 clients are connecting to the server, and then
the server needs to send data to the client number 2. How can the server make s
ure that it sends the data exactly to the 2nd client, rather than mistakenly to
other clients? | The server creates a separate InputStream and OutputStream
Which of the following statements is correct? | Basically, RMI technology uses t
raditional sockets but socket classes are created invisibly to developers.
Which of the following protocols is a reliable protocol? | TCP
Two streams in a Java socket are . | Binary streams
A(An) ... . is one endpoint of a two-way communication link between two programs r
unning on the network. | socket
In RMI Architecture, which of the following components is reponsible for storing
a mapping between a specific name and a remote object? | RMI registry
You are building an rmi application. Which of the following interfaces you must
extend for your remote interface? | java.rmi.Remote
Which of the following options is a valid method that is used to bind a name to
an object in RMI model? | Naming.rebind(name, object)
With respect to the Java RMI, a server and a client program . | can run in two sep
arate virtual machines
Select correct statement. In RMI implementations, | the remote class must implem
ent the remote inteface.
In a client-server application model, which side will initialize a connection? |
Client
Consider the following url address: | http is protocol, 192.168.2.2:12 is socket
.
You are trying to look up obj1 object on the server 192.168.12.1 using RMI techn
ology with default port | Naming.lookup("rmi://192.168.12.1/obj1") ;
Select a correct statement about TCP and UDP protocol: | TCP (Transmission Contr
ol Protocol) is a connection-based protocol that provides a reliable flow of dat
a between two computers.
A/An is bound to a port number so that the TCP layer can identify the application
having network comunication | socket
The ... object contains not just an SQL statement, but an SQL statement that has
been precompiled. | PreparedStatement
With respect to JDBC, (1) In the two-tier model, a Java application talks direct
ly to the data source. (2) In the three-tier model, a "middle tier" of services
is let between a Java program and the data source. (3) The JDBC API supports two
-tier processing model for database access only. | True, true, false
The correct order in which database -accessing objects should be created: | Conn
ection Statement- ResultSet ResultSetMetaData
With respect to the java.sql.Statement interface, | executeQuery( ), executeUpdate
( )
The Java program can | not directly access data in a database file that is manag
ed by a database management system.
The first in the most common objects are used in a database Java program: (1) ja
va.sql.Connection (2) java.sql.Statement (3) java.sql.ResultSet (4) java.sql.Res
ultSetMetaData | (1) java.sql.Connection
Which of the following statements is correct regarding Type 4 JDBC driver (Nativ
e Protocol)? | It helps the Java applications communicate directly with the data
base using Java sockets.
Suppose that the current position of a ResultSet, named rs, is at the last recor
d, the statement rs.next() will return | false
The JDBC API supports processing models for database access | two-tier model
The _____ object contains not just an SQL statement, but an SQL statement that h
as been precompiled. | PreparedStatement
If you want execute a SQL statement many times, the ____ object should be used.
| PreparedStatement
You are required to build an application that can connect to database to display
data to end users. The requirement for the database connectivity is that it mus
t provide a performance as fast as possible. Suppose that all types of drivers a
re available. Which type should you choose to satisfy the requirement? | type 2
One of the benefits of Type 1 driver (JDBC ODBC Bridge) is that it can provide c
onnection to a database when Java driver is not available for that database. Whi
ch of the following options is another advantage of the Type 1 driver? | None of
the others
Suppose that you will insert a lot of rows into a database table row-by-row. Whi
ch of the following interfaces should be used? | PreparedStatement
In a JDBC application, suppose that the Connection, named con, was created. Stud
y the following code: | The above code will throw an exception.
In JDBC model, which driver types provide access to database through native code
libraries C/C++? | Type 2-driver
You are required to build an application that connects to database to store and
retrieve data. Your application must be independent with the underlying database
. Which driver types should you use? | Type 3-driver
You are going to execute an insert statement to add some data into the database.
Which of the following methods should you use? | executeUpdate()
In JDBC, which of the following class/interface should be used to call a store p
rocedure? | CallableStatement
The . method of the class helps loading a JDBC driver. | forName( ), java.lang.Class
The next() method of the java.sql.ResultSet class return | a boolean value
When you want to delete some rows in a table of a database, the method of the jav
a.sql.Statement interface must be used. | executeUpdate()
In JDBC API, which of the following statements can be used to call a stored proc
edure? | CallableStatement
Which of the following is NOT a benefit of using JDBC? | JDBC programs are tight
ly integrated with the server operating system.
In which layer of the JDBC architecture does the JDBC-ODBC bridge reside? | It r
esides in the JDBC layer.
For what reason does the following JSP fail to translate and compile?<html><body
><%!intx%><%=x;%></body></html> | Error in JSP Expression.
Study the statements:1) URL rewriting may be used when a browser is disabled coo
kies. 2) In URL encoding the session id is included as part of the URL. | Both
1 and 2 are true
JavaBeans component has the following field: | a. public void set Enabled(boolea
n enabled) public boolean getEnabled()
You have declared a useBean tag as: <jsp:useBean id="man" class="animal.Human" s
cope="application"/> In which type of object will this bean be kept? | Applicat
ionContext
What gets printed when the following code snippet is compiled? select the one co
rrect answer. <%int y=0;%> <%int z=0;%> <%for(int x=0;x<3;x++){%> <%z++;y;%> <%}
%> <%if(z<y){%> <%=z%> <%}else{%> <%=z-1%> <%}%> | a. 2
What is the result of attempting to access the following JSP page? <html> <body>
<%!public String methodA(){ return methodB();} %> <%!public String methodB(){ r
eturn "JAD Final Test"; } %> <h2><%= methodA() %></h2> </body> </html> | a. "JAD
Final Test" is output to the resultring web page.
What is output to the web page on the second access to the same instance of the
following JSP? <html> <body> <%int x=0;%> <%= x++ %> </body> </html> | a. 0
The requirement for an online shopping application are: It must support milions
of customers. The invocations must be transactional. The shopping cart must be p
ersistent. Which technology is required to support these requirements? | a. EJB
Which of the following lines of code are correct? | a. @Entity public class Empl
oyees{..}
Study the statements about web.xml file: 1)The deployment descriptor file is cal
led web.xml, and it must be located in the WEB-INF directory. 2)web.xml is in XM
L (extended markup language) format. Its root element is <web>. | a. Only statem
ent 1 is true
Study the statements:1)URL rewritng may be used when a brower is disabled. 2)In
URL encoding the session id is included as part of the URL. | a. Both 1 and 2 ar
e true
What gets printed when the following JSP code is invoked in a brower. Select the
one correct answer. <%= if(Math.random() < 0.5 %> hello <%= }else{ %> hi <%= }
%> | a. The JSP file will not compile.
A programmer is designing a class to encapsulate the information about an invent
ory item. A JavaBeans component is needed to do this. The InventoryItem class ha
s private instance variables to store the item information: 10. private int item
Id; 11. private String name; 12. private String description; Which method signat
ure follows the JavaBeans naming standards for modifying the itemId instance var
iable? (Choose one.) | a. setItemId(int itemId)
Which of the following correctly represents the following JSP statement. Select
the one correct answer | a. <jsp: expression>x</jsp: expression>
Which of the following methods can be used to add cookies to a servlet reponse?
| a. HttpServletResponse.addCookie(Cookie cookie)
Create() method of entity home interface returns ________ | a. Remote object
Which of these is a correct fragment within the web-app element of deployment de
scriptor? Select the two correct answers. | <error-page><error-code>404</error-c
ode><location>?error.jsp</location></error-page>
A ______________has a name, a single value, and optional attributes such as a co
mment, path and domain qualifiers, a maximum age, and a version number. | Cookie
In EJB2.0, ejb-jar.xml deployment descriptor file must be placed in ____________
__folder | META-INF
Study the statements: The special directory/WEB-INF/lib contains Java class file
s-servlets and supporting code. The special directory/WEB-INF/class contains JAR
files with supporting libraries of code. | Both1 and 2 a not true
Which of the following files is the correct name and location of deployment desc
riptor of a web application? Assume that the web application is rooted at\doc-ro
ot. Select the one correct answer | \doc-root\WEB-INF\web.xml
Which of these are legal return types of the doAfterBody method defined in a cla
ss that extends TagSupport class. Select two correct answers | a. EVAL_BODY_AGAI
N b. SKIP_BODY
Which of these is legal return types of the doEndTag method defined in a class t
hat extends TagSupport class? Select two correct answers. | a. EVAL_PAGE b. SKIP
_BODY
Name the class that includes the getSession method that is used to get the HttpS
ession object. | HttpServletRequest
To send text output in a response. The following method of HttpServletResponse m
ay be used to get the appropriate Writer/Stream object. Select the one correct a
nswer | a. getOutputStream
What is the result of attempting to access the following JSP page? (Choose one.)
<html> <body> <%!public String method(){ Return JAD Final Test ; } %> <h2><%=method()
%></h2> </body> </html> | oeJAD final test is output to the resulting web page.
Which of the following statements are correct about the status of the Http respo
nse? Select the one correct answer | A status of 200 to 299 signifies that the r
equest was successful.
A bean with a property color is loader using the following statement <jsp:usebea
n id= fruit class= Fruit /> Which of the following statements may be user to print the
e of color property of the bean? Select the one correct answer. | a. <jsp:getPro
perty name= fruit property= color />
The _________________ supplies business components, of enterprise beans | Bean p
rovider
Which of the following are potentially legal lines of JSP cource?(Choose two.) |
a. <jsp:useBean id= beanName1 class= a.b.myBean type= a.b.Myinterface /> b. <isp:s
me= beanName1 property= soleProp value= <%=myValue%> />
Which of the following represents the XML equivalent of this statement <%@ inclu
de file= a.jsp %>. Select the one correct statement. | a. <jsp:directive.include file= a
jsp />
Which of the following direcrories are legal locations for the deployment descri
ptor file? Note that all paths are shown as from the root of the machine or driv
er.(Choose one.) | /appserverIntallDirectory/webapps/webappName/WEB-INF/xml
Which are EJB containers? (choose three) | a. JBoss b. IBM WebSphere c. BEA s WebLog
ic
Study the statements: URL rewriting may be used when a browser is disabled. In U
RL encoding the session id is included as part of the URL. | a. Both 1 and 2 are
true
ejbCreate() method of entuty bean class returns ________________ | primary key
Name the implicit variable to JSP pages that may be used to access all the other
implicit objects | pageContext
Study the statements about web.xml file: The deployment descriptor file is calle
d web.xml, and it must be located in the WEB_INF directory . Web.xml is in XML (
extended markup language) fomat. Its root element is <web>. | Only statement 1 i
s true.
A java bean with a property color is loaded using the following statement <jsp:u
sebean id= fruit class= Fruit /> What is the effect of the following statement <jsp:se
perty name= fruit property= color /> Select the one correct answer. | If there is a no
l request parameter with name color then its value gets assigned to color proper
ty of Java Bean fruit
In ejb-jar.xml file. <persistence-type> element value is ________________ | Bean
or Container
Which of the following statements are true for <jsp:usebean>. Select the two cor
rect answers | a. The id attribute must be defined for <jsp:usebean> b. The <jsp
:usebean> must include either type or class attribute or both
When a web server responds to a request from a browser or other Web client the r
esponse typically consists of. (choose one) | A status line, some response heade
rs, a blank line, and the document.
Message-driven beans are clsses that implement 02 interfaces: | a. Javax.ejb.mes
sageDrivenBean b. Javax.jms.MessagerListener
Which of these is a correct example of specifying a listener element resented by
MyClass class? Assume myServlet element is defined correctly. Select the one co
rrect answer | a. <listener><listerner-class>MyClass</listener-class></listener>
A bean with a property color is loaded using the following statement <jsp:usebea
n id= fruit class= Fruit /> What happen when the following statement is executes. Sele
e one correct answer. <jsp:setPropety name= fruit property= /> | a. All the propertie
the fruit bean are assignet the values of input parameters of the JSP page that
have the same name.
A ______________ session bean is a bean that holds conversations that span a sin
gle method call | Stateless
The top three value of EJB are (choose 3) | a. It is agreed upon by the industry
. b. Portability is easier c. Rapid application development
Which of the HTTP methods below is not considered to be oeidempotent ? (Choose one.)
| a. POST
Which of the HTTP methods below are likely to change state on the web server? (C
hoose three.) | a. DELETE b. POST c. PUT
Which of the following are valid servlet methods that match up with HTTP methods
? (Choose four.) | a. doGet() b. doPost() c. doOptions() d. doHead()
What is the likely effect of calling a servlet with the POST HTTP method if that
servlet does not have a doPost() method? (Choose one.) | a. 405 response code:
SC_METHOD_NOT_ALLOWED.
What is the likely effect of calling a servlet with the HEAD HTTP method if that
servlet does not have a doHead() method? (Choose one.) | a. 200 response code:
SC_OK
What will be the result of pressing the submit button in the following HTML form
? (Choose two.) | a. A request is sent with the HTTP method GET. b. The paramete
rs fullName and sbmButton are passed to the web server in the request URL.
Consider the following form and servlet code. Assuming the user changes none of
the default settings and presses submit, what will the servlet output in the res
ponse? (Choose one.) <form action="PrintParams?param1=First" method="post"> <inp
ut type="hidden" name="param1" value="First" /> <input type="text" name="param1"
value="Second" /> <input type="radio" name="param1" value="Third" /> <input typ
e="submit" /> </form> protected void doPost HttpServletRequest request, HttpServ
letResponse response) throws ServletException, IOException { response.setContent
Type("text/html"); PrintWriter out = response.getWriter(); out.write("<html>\n<h
ead>\n<title>Print Parameters</title>\n</head>\n<body>"); String[] param1 = requ
est.getParameterValues("param1"); for (int i = 0; i < param1.length; i++) out.w
rite(param1[i] + ":"); } out.write("\n</body>\n</html>"); out.close(); } | a. Fi
rst:First:Second
What is the maximum number of parameter values that can be forwarded to the serv
let from the following HTML form? (Choose one.) <html> <body> <h1>Chapter 1 Ques
tion 9</h1> <form action="ParamsServlet" method="get"> <select name="Languages"
size="3" multiple> <option value="JAVA" selected>Java</option> <option value="CS
HARP">C#</option> <option value="C" selected>C</option> <option value="CPLUSPLUS
">C++</option> <option value="PASCAL">Pascal</option> <option value="ADA">Ada</o
ption> </select> <input type="submit" name="button" /> </form> </body> </html> |
a. 7
What request header must be set for parameter data to be decoded from a form? (C
hoose one.) | a. Content-Type: application /x-www-form-urlencoded
Which of the following are likely to found as request header fields? (Choose thr
ee.) | a. Accept b. Accept-Language c. From
What is the most likely outcome of running the following servlet code? (Choose o
ne.) long date = request.getDateHeader("Host"); response.setContentType("text/pl
ain"); response.getWriter().write("" + date); | a. IllegalArgumentException
What is the likely outcome of attempting to run the following servlet code? Stri
ng[] values = request.getHeaders("BogusHeader"); response.setContentType("text/p
lain"); response.getWriter().write(values[0]); | a. Won t run: 2 compilation errors
What is the likely outcome of attempting to compile and run the following servle
t code, assuming there is one cookie attached to the incoming request? 11 Cookie
[] cookies = request.getCookies(); 12 Cookie cookie1 = cookies[0]; 13 response.s
etContentType("text/plain"); 14 String attributes = cookie1.getName(); 15 attrib
utes += cookie1.getValue(); 16 attributes += cookie1.getDomain(); 17 attributes
+= cookie1.getPath(); 18 response.getWriter().write(attributes); | a. Output to
the response including at least the name and value
Under what circumstances can the HttpServletRequest.getHeaders(String name) meth
od return null? (Choose one.) | a. If the container disallows access to the head
er information
Which of the following methods can be used to add cookies to a servlet response?
(Choose two.) | a. HttpServletResponse.addCookie(Cookie cookie) b. HttpServletR
esponse.addHeader(String name, String value)
What is the outcome of running the following servlet code? (Choose two.) public
void doGet( HttpServletRequest request, HttpServletResponse response) throws Ser
vletException, IOException { response.setContentType("text/plain;charset-UTF-8")
; PrintWriter out = response.getWriter(); out.flush(); out.close(); System.out.p
rintln(response.isCommitted()); response.setContentType("illegal/value"); } | a.
A blank page is returned to the client b. oetrue is output on the server s console.
What will be the outcome of executing the following code? (Choose one.) public v
oid doGet( HttpServletRequest request, HttpServletResponse response) throws Serv
letException, IOException { response.setContentType("text/plain"); response.setC
ontentLength(4); PrintWriter out = response.getWriter(); out.write("What will be
the response? "); out.write("" + response.isCommitted());} | a. oeWhat is returned t
o the client.
Which of the approaches below will correctly cause a client to redirect to an al
ternative URL?
In the code fragments below, consider that oeresponse is an instance of HttpServletR
esponse.) (Choose two.) | a. response.sendRedirect("index.jsp"); b. response.set
Status(HttpServletResponse.SC_TEMPORARY_REDIRECT);
Identify statements that are always true about threads running through the servi
ce() method of a servlet with the following class declaration. (Choose two.) | a
. There could be anything from zero to many threads running through the service(
) method during the time the servlet is loaded. b. D. If the init() method for t
he servlet hasn t run, no threads have yet been able to run through the service() me
thod.
Under which of the following circumstances are servlets most likely to be instan
tiated? (Choose four.) | a. During web application startup b. On a client first
requesting the servlet c. At some arbitrary point in the web application or appl
ication server lifetime d. After the time specified on an UnavailableException h
as expired
Which of the following are true statements about servlet availability? (Choose t
wo.) | a. If a servlet is removed from service, then any requests to the servlet
should result in an HTTP 404 (SC_NOT_FOUND) error. b. If a servlet is deemed te
mporarily unavailable; a container may return an HTTP 503 (SC_SERVICE_UNAVAILABL
E) message on receiving requests to the servlet during its time of unavailabilit
y.
Under what circumstances will a servlet instance s destroy() method never be called?
(Choose two.) | a. When init() has not run to completion successfully b. After
destroy() has already been called
Given the following servlet code, identify the outputs that could not or should
not occur during the lifetime of the web application housing the servlet. | a. d
estroy:service: b. init:service:init:service:
Which of the following directories are legal locations for the deployment descri
ptor file? Note that all paths are shown as from the root of the machine or driv
e. (Choose two.) | a. / WEB-INF b. /appserverInstallDirectory/webapps/webappName
/ WEB-INF
What would be the best directory in which to store a supporting JAR fi le for a
web application? Note that in the list below, all directories begin from the con
text root. (Choose one.) | / WEB-INF/lib
What s the likely outcome of a user entering the following URL in her browser? You c
an assume that index.html does exist in /WEB-INF/html, where /WEB-INF/html is a
directory off the context root, and that the server, port, and context details a
re specified correctly. (Choose one.) | An HTTP response code of 404 returned to
indicate that the requested resource has not been found.
Identify which of the following are true statements about web applications. (Cho
ose three.) | Server-side code has access to all resources in the web applicatio
n. Clients of web applications can t directly access resources in / WEB-INF/tld. A g
ood place to keep a .tld (tag library fi le) is directly in the / WEB-INF direct
ory See the extract from web.xml below: <servlet-mapping> <servlet-name>ServletA
</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping
> <servlet-name>ServletB</servlet-name> <url-pattern>/bservlet.html</url-pattern
> </servlet-mapping> <servlet-mapping> <servlet-name>ServletC</servlet-name> <ur
l-pattern>*.servletC</url-pattern> </servlet-mapping> <servlet-mapping> <servlet
-name>ServletD</servlet-name> <url-pattern>/dservlet/*</url-pattern> </servlet-m
apping> Given that a user enters the following into her browser, which (if any)
of the mapped servlets will execute? (Choose one.) | ServletA
What is the parent tag for <welcome-file-list>? (Choose one.) | <web-app>
Which of the following are true statements about the deployment descriptor for a
web application? (Choose two.) | <welcome-file> is a child element of <welcome
-file-list>. At least one element must be present.
What of the following represents a correct declaration of a servlet in the deplo
yment descriptor? (Choose one.) | <servlet> <description>MyServlet</description>
<servlet-name>MyServlet</servlet-name> <servlet-class>MyServlet</servlet-class>
</servlet>
Given five servlets with <load-on-startup> value set as follows, and declared in
the following order in the deployment descriptor, ServletA: 1 ServletB: 0 Servlet
: 1 ServletD: 1 ServletE: no value set for <load-on-startup> Identify true stateme
nts from the list below. (Choose one.) | ServletB will load before ServletC.
What will be the outcome of compiling and deploying the servlet code below? (You
can assume that correct import statements are provided and that the servlet liv
es in the default package. Line numbers are for ease of reference and are not pa
rt of the code.) 11 public class NameServlet extends HttpServlet { 12 protected
void doGet(HttpServletRequest request, 13 HttpServletResponse response) { 14 out
.write(getServletName()); 15 } 16 } | Will not compile for some other reason
Assume that there is a fi le called secure.txt, located at / WEB-INF/securefi le
s, whose contents are oePassword=WebCert. What statements are false about the result
of compiling and running the following code? 11 public class CodeTestServlet ex
tends HttpServlet { 12 protected void doGet(HttpServletRequest request, 13 HttpS
ervletResponse response) throws IOException { 14 ServletContext sc = getServletC
ontext(); 15 InputStream is = sc.getResourceAsStream("/WEB-" + 16 "INF/securefil
es/secure.txt"); 17 BufferedReader br = new BufferedReader(new InputStreamReader
(is)); 18 System.out.println(br.readLine());19 }20 } | A, B, C, and D above.
Given the following deployment descriptor: <web-app> <servlet> <servlet-name>Ini
tParams</servlet-name> <servlet-class>com.osborne.c02.InitParamsServlet</servlet
-class> <init-param> <param-name>initParm</param-name> <param-value>question14</
param-value> </init-param> </servlet> </web-app> What is the outcome of running
the following servlet? (Choose one.) | oeInitialization Parameter is: null returned
to the requester
Which of the following methods derive from the ServletConfig interface? (Choose
three.) | ServletContext getServletContext(). String getInitParameter(String nam
e) . String getServletName()
Which of the following is a valid way to set up a mime mapping in the deployment
descriptor? (Choose one.) | <mime-mapping> <extension>txt</extension> <mime-typ
e>text/plain</mime-type> <mime-mapping>
Which of the following servlet methods can return null? (Choose one.) | getInitP
arameter(String name)
Identify correct statements about the META-INF directory from the list below. (C
hoose three.) | META-INF is a suitable location for storing digital certifi cate
s. The MANIFEST.MF file is found in the META-INF directory. META-INF is not dire
ctly accessible to clients.
Identify correct statements about WAR files from the list below. (Choose three.)
| A META-INF directory will be present in the WAR file. A WEB-INF directory wil
l be present in the WAR file. A WAR file is in ZIP file format.
Consider the following list of files in a web application, where myApp is the co
ntext path: /devDir/myapp/index.jsp /devDir/myapp/WEB-INF/web.xml /devDir/myapp/
WEB-INF/classes/webcert/ch02/SomeServlet.class Which of the following sets of in
structions will build a correctly formed web archive file?(Choose one.) | Change
directory to /devDir/myApp; execute jar cvf someapp.war *.*
What is the result of loading the web-app with the following deployment descript
or and attempting to execute the following servlet? (Choose two.) <web-app> <con
text-param><paramname>author</paramname> <paramvalue>Elmore Leonard</paramvalue>
</context-param> </web-app> public class ContextInitParms extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html"); Pri
ntWriter out = response.getWriter(); out.write("<HTML><HEAD></HEAD><BODY>"); Ser
vletContext sc = getServletContext(); out.write(sc.getInitParameter("auther"));
out.close();}}| An application failure occurs. A 404 error occurs in the browser
What results from a call to the getInitParameterNames() method on ServletContext
when there are no context parameters set up in the deployment descriptor? (Choo
se two.) | An empty Enumeration object is returned. No exceptions are thrown.
Identify true statements about context parameters from the list below. (Choose o
ne.) | None of the above.
Given a servlet containing the following code, what is the outcome of attempting
to compile and run the servlet? (Choose one.) | The servlet won t compile
What is the likely result from attempting to compile and execute the following s
ervlet code? (Choose one.) HttpSession session = getSession(); String s = sessio
n.getAttribute("javax.servlet.session.tempdir"); | Won t compile for more than one r
eason.
Identify true statements from the list below. (Choose two.) | You cannot remove
request parameters. Attributes can be set by the web container or by application
code.
What is result of attempting to run the following code? (Choose one.) public voi
d doGet(HttpServletRequest request, HttpServletResponse response) throws Servlet
Exception, IOException { request.setAttribute("a", "request"); System.out.print(
request.getAttribute("a"));request.setAttribute("a", "2nd request"); System.out.
print(","); System.out.print(request.getAttribute("a")); request.removeAttribute
("a"); request.removeAttribute("a"); System.out.print(","); Object o = request.g
etAttribute("a"); System.out.print(o);} | oerequest, 2nd request, null written to st
andard output
From the following list, what is a probable outcome from a call to the ServletCo
ntext.getAttributeNames() method? (Choose one.) | A nonempty Enumeration is retu
rned.
Identify true statements about scope from the following list. (Choose two.) | Se
ssion scope can span JVMs. Requests can span web apps
What is the outcome of executing ServletA? You can assume that (1) ServletB has
a mapping of oe/ServletB and a name of oeServletB, and (2) imports have been omitted
the code for breity; the code will compile successfully. (Choose one.) public c
lass ServletA extends HttpServlet { public void doGet(HttpServletRequest req, Ht
tpServletResponse resp) throws ServletException, IOException { RequestDispatcher
rd = getServletContext().getNamedDispatcher( "ServletB"); rd.forward(req, resp)
;}} public class ServletB { public void doGet(HttpServletRequest req, HttpServle
tResponse resp) throws ServletException, IOException { String attr = (String) re
q.getAttribute("javax.servlet.forward.servlet_path"); PrintWriter out = resp.get
Writer(); out.write("Attribute value: " + attr); }} | oeAttribute value: null output
to the web page
Identify which of the following are names of special attributes associated with
the dispatching mechanism. (Choose two.) | javax.servlet.include.servlet_path. j
avax.servlet.include.path_info
What are possible outcomes from executing the doGet method in ServletC below? (C
hoose two.) public class ServletC extends HttpServlet {public void doGet(HttpSer
vletRequest req, HttpServletResponse resp) throws ServletException, IOException
{ RequestDispatcher rd = getServletContext().getRequestDispatcher("ServletB");rd
.forward(req, resp);}} | HTTP 500 error (error in 500s). Some other exception.
What is the web page output from executing ServletD with the URL below? (Choose
one.) http://localhost:8080/myapp/ServletD?fruit=orange public class ServletD ex
tends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException { RequestDispatcher rd = getServletC
ontext().getRequestDispatcher("/ServletE?fruit=pear");rd.forward(req, resp);}}pu
blic class ServletE extends HttpServlet {public void doGet(HttpServletRequest re
quest, HttpServletResponse response)throws ServletException, IOException {respon
se.setContentType("text/plain");PrintWriter out = response.getWriter();String[]
valueArray = request.getParameterValues("fruit");for (int i = 0; i < valueArray.
length; i++) {if (i > 0) {out.write(", ");}out.write(valueArray[i]);}String quer
yString = (String) request.getAttribute("javax.servlet.forward.query_string");in
t pos = queryString.indexOf("=") + 1;String values = queryString.substring(pos);
out.write(", " + values);}} | pear, orange, orange
ServletA forwards to ServletB, which includes Servlet C, which forwards to Servl
etD, which includes ServletE. When ServletA is requested, which servlets might c
ontribute to the final response? (Choose one.) | ServletD and ServletE
Identify true statements about fi lters. (Choose one.) | You cannot work directl
y with the request object that is passed as a parameter to the filter.
Which of the following is a legal filter mapping declaration in the deployment d
escriptor? (Choose one.) | <filter-mapping> <filter-name>MicroPaymentFilter</fil
ter-name> <servlet-name>MicroPaymentServlet</servlet-name> <dispatcher>REQUEST</
dispatcher> </filter-mapping>
From the available options, what is the likely outcome from running the code bel
ow? (Choose one.) protected void doGet(HttpServletRequest request, HttpServletRe
sponse response) throws ServletException, IOException { RequestDispatcher dispat
cher =getServletContext().getNamedDispatcher("/ServletB"); dispatcher.forward(re
quest, response);} | NullPointerException.
Given the following deployment descriptor, identify the sequence of fi lters tha
t execute on a direct client request for ServletA. (Choose one.) <filter-mapping
> <filter-name>LogFilter</filter-name> <servlet-name>ServletA</servlet-name> </f
ilter-mapping> <filter-mapping> <filter-name>AuditFilter</filter-name><url-patte
rn>/ServletA</url-pattern> <dispatcher>FORWARD</dispatcher></filter-mapping><fil
ter-mapping><filter-name>EncryptionFilter</filter-name><url-pattern>/*</url-patt
ern></filter-mapping><servlet-mapping><servlet-name>ServletA</servlet-name><url-
pattern>/ServletA</url-pattern></servlet-mapping> | EncryptionFilter, LogFilter
What is the outcome of attempting to compile, deploy, and run the following serv
let code? Line numbers are for reference only and should not be considered part
of the code. (Choose one.) 10 import java.io.*;11 import javax.servlet.*;12 impo
rt javax.servlet.http.*;13 public class Question2 extends HttpServlet {14 protec
ted void doGet(ServletRequest request,15 ServletResponse response) throws Servle
tException, IOException {16 HttpSession session = request.getSession(false);17 s
ession.invalidate();18 session.setAttribute("illegal", "exception thrown"");19 }
20 } | Won t compile
Identify the two equivalent method calls in the list below. (Choose two.) | Http
ServletRequest.getSession(). HttpServletRequest.getSession(true)
Identify true statements about sessions from the list below. (Choose two.) | Ses
sions can be cloned across JVMs. Sessions can be set to never time out.
Which of the following mechanisms will guarantee that every session in a web app
lication will expire after 1 minute? You can assume that for each answer below,
this is the only session timeout mechanism in force for the web application. (Ch
oose two.) | In the deployment descriptor:<session-config><session-timeout>1</se
ssion-timeout></session-config> b. In the doFilter() method of a fi lter that ha
s the following <url-pattern> mapping in the deployment descriptor: oe/. request is
an instance of HttpServletRequest, cast from the ServletRequest parameter passed
to the method. HttpSession session = request.getSession();session.setMaxInactiv
eInterval(60);
Identify the default mechanism for session management from the list below. (Choo
se one.) | Cookies
Identify correct statements about session management from the list below. (Choos
e two.) | The unique identifi er for a session may be passed back and forward th
rough a name/value. pair in the URL. The name is jsessionid.
Session management is usually dependent on a hidden form field called JSessionId
. | The rules for rewriting URLs for links may be different from those for rewri
ting URLs for redirection.
Given the following servlet code called with this URL -http://127.0.0.1:8080/ ex
amp0402/Q9-and also given that URL rewriting is the session mechanism in force,
identify the likely output from the servlet from the choices below. (Choose one.
) PrintWriter out = response.getWriter();response.setContentType("text/html");ou
t.write("<HTML><HEAD>");out.write("<TITLE>Encoding URLs</TITLE>");out.write("</H
EAD><BODY>");HttpSession session = request.getSession();out.write("\n<P>Session
id is <B>"+ session.getId() + "</B>.</P>");String URL1 = response.encodeURL("Q9"
);String URL2 = response.encodeURL("http://127.0.0.1:8080/examp0401/Q1");out.wri
te("\n<P>URL1: " + URL1 + "</P>");out.write("\n<P>URL2: " + URL2 + "</P>");out.w
rite("</BODY></HTML>"); | Output: Session ID is 4EDF861942E3539B1F3C101B71636C1A
.URL1: Q9;jsessionid=4EDF861942E3539B1F3C101B71636C1A. URL2: http://127.0.0.1:80
80/examp0401/Q1
Which of the following statements contain accurate advice for web developers? (C
hoose two.) | Because the client determines whether cookies are permitted or not
, it s a good idea always to encode URLs as a fallback session mechanism. Static pag
es in your web application can disrupt session management. Request and Context L
isteners
Identify actions that won t fi x a potential problem in the following ServletRequest
Listener code.(Choose two.)01 public void requestDestroyed(ServletRequestEvent
reqEvent) {02 HttpServletRequest request = (HttpServletRequest) 03 reqEvent.getS
ervletRequest(); 04 HttpSession session = request.getSession(); 05 session.setAt
tribute("name","value");06 } | Ensure that any servlet in your web application o
btains a session. Take no action, for the code will work in all circumstances.
What is the outcome of attempting to compile and run the servlet code below? (Ch
oose one.) import java.io.*; import javax.servlet.*;import javax.servlet.http.*;
public class Question12 extends HttpServlet {protected void doGet(HttpServletReq
uest request,HttpServletResponse response)throws ServletException, IOException {
ServletContext context = getServletContext();context.addAttribute("mutable", "fi
rstvalue");context.replaceAttribute("mutable", "secondvalue");context.removeAttr
ibute("mutable");context.removeAttribute("mutable");}} | None of the above.
Identify true statements about listener interfaces and related classes from the
list below. (Choose three.) | It is possible to add context attributes in the co
ntextDestroyed() method. You can access the current session from methods in clas
ses implementing the Servlet RequestListener interface. It is unwise to change r
equest attributes in the attributeReplaced() method of a class implementing the
ServletRequestAttributeListener interface
Identify the number and nature of the errors in the code below, which is taken f
rom a class implementing the ServletRequestAttributeListener interface. (Choose
one.)01 public void attributeAdded(ServletRequestAttributeEvent event) {02 HttpS
ervletRequest request = event.getServletRequest();03 Object o = event.getSource(
);04 System.out.println("Source of event is: "05 + o.getClass().getName());06 St
ring name = event.getName();07 String value = event.getValue();08 System.out.pri
ntln("In ServletRequestAttributeListener."09 + "attributeAdded() with name: "10
+ name + ", value; " + value);11 } | Two compilation errors
If a request attribute has been replaced, which of the following techniques will
not obtain the current (new) value of the attribute? (Choose two.) | Use the Se
rvletRequestAttributeEvent.getValue() method anywhere in the attributeReplaced()
method of a class implementing ServletRequestAttributeListener. Use the Servlet
RequestAttributeEvent.getValue() method anywhere in the attributeUpdated() metho
d of a class implementing ServletRequestAttributeListener
The code below is from a class implementing the HttpSessionListener interface (y
ou can assume that the whole class compiles successfully). What will happen when
the class is deployed in a web application and servlet code requests a session?
(Choose one.) public void sessionInitialized(HttpSessionEvent event) { System.o
ut.println("Session Initialized..."); HttpSession session = event.getSession();
Boolean loginOK = (Boolean) session.getAttribute("login"); if (loginOK == null |
| !loginOK.booleanValue()) {session.invalidate();}} | Can t determine what will happ
en.
The code below shows code for the class MySessionAttribute (Listing A). An insta
nce of this class is attached to an HttpSession (Listing B). From the list below
, pick out the things that will happen when this session is migrated from a sour
ce JVM to a target JVM. (Choose four.) LISTING A import java.io.*;import javax.s
ervlet.http.*;public class MySessionAttribute implements HttpSessionActivationLi
stener, Serializable { private static String data; public String getData() { ret
urn data; } public void setData(String newData) { data = newData;}public void se
ssionWillPassivate(HttpSessionEvent arg0) {System.out.println(data);}public void
sessionDidActivate(HttpSessionEvent arg0) {System.out.println(data);}} ..... |
sessionWillPassivate() method called in the source JVM. sessionDidActivate() met
hod called in the target JVM. oeMy data written to the source JVM s web server consol
My data not written to the source JVM s web server console
Pick out true statements from the list below. (Choose two.) | More than one sess
ion listener interface may take effect from the same deployment descriptor decla
ration. An HttpSessionListener s sessionDestroyed() method will be called as a resul
t of a client refusing to join a session.
A web application houses an HttpSessionAttributeListener and an object (SessionA
ttrObject) that implements HttpSessionBindingListener. Pick out the correct sequ
ence of listener method calls that follows from executing l the servlet code bel
ow inside this web application.(Choose one.)import java.io.*;import javax.servle
t.*;import javax.servlet.http.*;public class Question20 extends HttpServlet {pro
tected void doGet(HttpServletRequest request,HttpServletResponse response) throw
s ServletException, IOException {HttpSession session = request.getSession();sess
ion.invalidate();HttpSession newSession = request.getSession();SessionAttrObject
boundObject = new SessionAttrObject("value");newSession.setAttribute("name", bo
undObject);newSession.setAttribute("name", "value");newSession.setAttribute("nam
e", null);} } | valueBound(), attributeAdded(), valueUnbound(), attributeReplace
d(),attributeRemoved()
Which security mechanism proves that data has not been tampered with during its
transit through the network? (Choose one.) | Data integrity
Which security mechanism limits access to the availability of resources to permi
tted groups of users or programs? (Choose one.) | Authorization
Which of the following deployment descriptor elements play some part in the auth
entication process? (Choose three.) | <login-config>. <auth-method>. <form-error
-page>
In a custom security environment, for which security mechanisms would a fi lter
be incapable of playing any useful part? (Choose one.) | None of the above
Review the following scenario; then identify which security mechanisms would be
important to fulfill the requirement. (Choose two.) | Authorization. Authenticat
ion
Identify which choices in the list below show immediate subelements for <securit
yconstraint> in the correct order. (Choose two.) | <web-resource-collection>,<au
th-constraint>,<user-data-constraint>. <web-resource-collection>,<auth-constrain
t>
Identify valid confi gurations for the <transport-guarantee> element in the depl
oyment descriptor. (Choose four.) | <transport-guarantee>CONFIDENTIAL</transport
-guarantee>b. Absent altogether from the deployment descriptor c. <transport-gua
rantee>NONE</transport-guarantee> d. <transport-guarantee>INTEGRAL</transport-gu
arantee>
Given the following incomplete extract from a deployment descriptor, what are po
ssible ways of accessing the protected resource named TheCheckedServlet? (Choose
three.)<security-constraint><web-resource-collection><web-resource-name>TheChec
kedServlet</web-resource-name><url-pattern>/CheckedServlet</url-pattern></web-re
source-collection><auth-constraint /></security-constraint><security-constraint>
<web-resource-collection><web-resource-name>TheCheckedServlet</web-resource-name
><url-pattern>/CheckedServlet</url-pattern><http-method>GET</http-method></web-r
esource-collection><auth-constraint><role-name>bigwig</role-name></auth-constrai
nt></security-constraint> | Via another URL pattern (if one is set up elsewhere
within the deployment descriptor). Via RequestDispatcher.include(). Via RequestD
ispatcher.forward().
Which of the following might a web server consider important in ensuring a trans
port guarantee of CONFIDENTIAL? (Choose four.) | Server-side digital certifi cat
es. Symmetric keys. Asymmetric (public/private keys). SSL
The following web page is defined as the custom form login page for authenticati
on. Assuming that you have attempted to access a protected resource and been red
irected to this web page, what is the result of fi lling in the user name and pa
ssword fi elds and pressingsubmit? (Choose one.)<html><head><title>Login Form</t
itle></head><body><form action="jsecuritycheck" method="POST"><br />Name: <input
type="text" name="jusername" /><br />Password: <input type="password" name="jpa
ssword" /><br /><input type="submit" value="Log In" /></form></body></html> | Th
e page is redisplayed.
What is the result of the following login configuration? (Choose one.) <login-co
nfig><auth-method>FORM</auth-method><form-login-config><form-login-page>login.ht
ml</form-login-page><form-error-page>error.html</form-error-page></form-login-co
nfig></login-config> | Application fails to start.
Which of the following sub elements might you expect to fi nd in the <login-conf
ig> for BASIC authorization? (Choose two.) | <auth-method>. <realm-name>
Which of the following sub elements would you not expect to fi nd in the <login-
config> for CLIENT-CERT authorization? (Choose four.) | <auth-constraint>. <role
-name>. <form-login-page>. <realm-name>
What will be the most likely outcome of attempting to access the following JSP f
or the second time? (Choose one.) <%@ page language="java" %> <%@ page import="j
ava.util.*" %><html><head><title>Chapter 6 Question 1</title></head><body><h1>Ch
apter 6 Question 1</h1><%!public void jspInit() {System.out.println("First half
of jspInit()");%><%> new Date() %><%!System.out.println("Second half of jspInit(
)");}%></body></html> | Web page returned showing a heading and the current date
What is output to the web page on the second access to the same instance of the
following JSP?(Choose one.)<%@ page language="java" %><html><head><title>Chapter
6 Question 2</title></head><body><h1>Chapter 6 Question 2</h1><%! int x = 0; %>
<%!public void jspInit() {System.out.println(x++);}%><%= x++ %><% System.out.pri
ntln(x); %><% jspInit(); %></body></html> | 3
For what reason does the following JSP fail to translate and compile? (Choose on
e.) <%@ page language="java" %><html><head><title>Chapter 6 Question 3</title></
head><body><h1>Chapter 6 Question 3</h1><%! int x; %><%!public void jspDestroy()
{System.out.println("self-destructing");} %><%!public void jspInit() {System.ou
t.println(<%= x %>);}%></body></html> | Expression embedded in declaration.
Which of the following are true statements about the JavaServer Page life cycle?
(Choose two.) | The _jspService() method is called from the generated servlet s ser
vice() method. All servlet methods are accessible from the jspInit() method
What is the consequence of attempting to access the following JSP page? (Choose
two.)<%@ page language="java" %><html><head><title>Chapter 6 Question 5</title><
/head><body><h1>Chapter 6 Question 5</h1><%!public void _jspService(HttpServletR
equest request,HttpServletResponse response) {out.write("A");} %><% out.write("B
"); %></body></html> | Cannot resolve symbol compilation error. Duplicate method
compilation error.
What is the result of attempting to access the following JSP page? (Choose one.)
<html><head><title>Chapter 6 Question 6</title></head><body><h1>Chapter 6 Quest
ion 6</h1><%! public String methodA() {return methodB();}%><%! public String met
hodB() {return methodC();}%><% public String methodC() {return "Question 6 Text"
;}%><h2><%= methodA() %></h2></body></html> | A translation error occurs.
What true statements can you make about the following JSP page source? The line
numbers are for reference only and should not be considered part of the source.(
Choose two.)01 <%@ page import="java.io.*" %>02 <html>03 <head><title>Chapter 6
Question 8</title></head> 04 <body> 05 <% 06 PrintWriter out = response.getWrite
r(); 07 out.write("P"); 08 %> 09 <% out.write("Q"); %> 10 </body> 11 </html> | I
n JSP technology, it s a bad idea to get hold of the PrintWriter directly from the r
esponse. The page has a compilation error for other reasons
Which of the following are false statements to make about JSP scripting elements
?(Choose three.) | It is legal to embed a <%--style comment inside another comme
nt. It is legal to embed an expression inside a declaration. It is legal to embe
d an expression inside a directive
What is the result of attempting to access the following JSP page source? (Choos
e one.) <% <%-- for (int i = 0; i < 10; i++) {<%-- if(i==3) System.out.println("
i is 3!");--%>System.out.println("i squared is " + i * i);} %> --%> | The JSP pa
ge would compile if one of the percent (%) signs were removed
Which of the following constitute valid ways of importing Java classes into JSP
page source? (Choose two.) | <%@ page import='java.util.*, java.io.PrintStream'
b. <%@page import = " java.util.* "%>
What is the outcome of accessing the fi rst JSP page, includer12.jsp, shown belo
w?(Choose one.)<%-- file includer12.jsp begins here --%><% for (int i = 0; i < 1
0; i ++) { %><%@ include file="included12.jsp" %><% } %><%-- End of file include
r12.jsp --%><%-- Beginning of file included12.jsp --%><html><head><title>Chapter
6 Question 12</title></head><body><h1>Chapter 6 Question 12</h1>For the <%=i%>t
h time<br /></body></html><%-- End of file included12.jsp --%> | An ill-formed H
TML page will be the output
What statements are true about the following two JSP page sources, given the int
ention of always requesting includer13.jsp? (Choose two.) <%-- file includer13.j
sp begins here --%> <%@ page import="java.util.*" contentType="text/html" sessio
n="true"%> <html> <head><title>Chapter 6 Question 13</title></head><body><h1>Cha
pter 6 Question 13</h1><%ArrayList al = new ArrayList();al.add("Jack Russell");a
l.add("Labrador");al.add("Great Dane");%><%@ include file="included13.jsp" %></b
ody></html><%-- file includer13.jsp ends here --%><%-- file included13.jsp begin
s here --%><%@ page import="java.util.*" contentType="text/html" %><table><%for
(int i = 0; i < al.size(); i++) {%><tr><td><%= al.get(i) %></td></tr><%}%></tabl
e><%-- file included13.jsp ends here --%> | Removing the Session attribute from
includer13.jsp will make no difference to the generated servlet code. The order
of the import and contentType attributes in both JSP page sources is immaterial.
Which of the following are invalid directives? (Choose three.) | <%@page isELign
ored = oefalse %> b. <%@ page session=the oe/ is okay true %> c. <%@include uri=
Given the beginning of the JSP page source below, which set of lines should be u
sed to complete the JSP page source in order to print out all the song lyrics? (
Choose one.)<%! static String[] suedeShoes = new String[4];static { suedeShoes[0
] = "One for the Money,";suedeShoes[1] = "Two for the Show,";suedeShoes[2] = "Th
ree to Get Ready,";suedeShoes[3] = "And Go, Cat, Go!";} %><% pageContext.setAttr
ibute("line1", suedeShoes[0]);request.setAttribute("line2", suedeShoes[1]);sessi
on.setAttribute("line3", suedeShoes[2]);config.getServletContext().setAttribute(
"line4", suedeShoes[3]);%><%@ page contentType="text/plain" info="Blue Suede Sho
es" session="false" %><%for (int i = 0; i < suedeShoes.length; i++) {String song
Line = (String) pageContext.findAttribute("line" + (i + 1));%><%= songLine %><%}
%> | <%@ page contentType="text/plain" info="Blue Suede Shoes" session="true" %>
<%for (int i = 0; i < suedeShoes.length; i++) {String songLine = (String) pageCo
ntext.findAttribute("line" + (i + 1));%><%= songLine %><%}%>
Which of the following techniques is likely to return an initialization paramete
r for a JSP page? (Choose two.) | <% String s = getInitParameter( oemyParm ); %> b. <%
= config.getInitParameter( oemyParm ); %>
What is the result of requesting errorProvoker.jsp for the fi rst time? Assume t
hat neither of the JSP pages below has yet been translated. (Choose one.)<%--Beg
inning of errorProvoker.jsp page source --%><%@ page errorPage="/errorDisplayer.
jsp" %><% request.setAttribute("divisor", new Integer(0)); %><html><head><% int
i = ((Integer) request.getAttribute("divisor")).intValue(); %><title>Page Which
Terminates In Error</title></head><body><%= 1.0 / i %></body></html><%-- End of
errorProvoker.jsp page source --%><%-- Beginning of errorDisplayer.jsp page sour
ce --%><%@ page isErrorPage="true" %><%@ page import="java.io.*" %><html><head><
title>Divide by Zero Error</title></head><body><h1>Don't divide by zero!</h1><pr
e><% exception.printStackTrace(new PrintWriter(out)); %></pre></body></html><%--
End of errorDisplayer.jsp page source --%> | errorDisplayer.jsp will not be tra
nslated. errorProvoker.jsp displays output.
Which of the following are false statements about implicit objects and scope? (C
hoose four.) | out is of type java.io.PrintWriter. config can be used to return
context initialization parameters. application can t be used to access other web ap
plication resources.
What is the result of attempting to access attributeFinder.jsp below, typing tex
t into the input field, and pressing the submit button? (Choose one.)<%-- Beginn
ing of attributeFinder.jsp page source --%><%@ include file="fieldSetter.jsp" %>
<html><head><title>Echo Input</title></head><body><h5>Type in the field below an
d press the button to echoinput...</h5><form><input type="text" name="<%= sessio
n.getAttribute("echoFieldName")%>" /><input type="submit" /></form><h3>Echoed Te
xt: <%= request.getAttribute("echoInput") %></h3></body></html><%-- End of attri
buteFinder.jsp page source --%><%-- Beginning of fieldSetter.jsp page source --%
><% session.setAttribute("echoFieldName", "echoInput"); %><%-- End of fieldSette
r.jsp page source --%> | null is displayed for the echoed text.
Which of the following are potentially legal lines of JSP source? (Choose two.)
| <jsp:useBean id="beanName1" class="a.b.MyBean" type="a.b.MyInterface" /> b. <%
String myValue = "myValue"; %> <jsp:setProperty name="beanName1" property="sole
Prop" value="<%=myValue%>" />
Which of the following are false statements about <jsp:useBean> standard action
attributes? (Choose three.) | If the type attribute is used, the class attribute
must be present. If both are used, class and type attributes must have differen
t values. If both are used, class and type attributes must have the same value.
Given a NameBean with a oename property and an AddressBean with an oeaddress proper
at happens when the following JSP is requested with the following URL? (Choose o
ne.)Calling URL:http://localhost:8080/examp0701/Question4.jsp?name=David%20Bridg
ewater&address=Leeds%20UKJSP page source:<jsp:useBean id="name" class="webcert.c
h07.examp0701.NameBean" /><jsp:useBean id="address" class="webcert.ch07.examp070
1.AddressBean" /><jsp:setProperty name="name" property="name" /><jsp:setProperty
name="address" param="*" /><jsp:getProperty name="name" property="name" /><jsp:
getProperty name="address" property="address" /> | A translation time error occu
rs
What is the outcome of making the HTTP GET request shown to params.jsp (source f
ollows)?(Choose one.) The HTTP request is in this form: http://localhost:8080/ex
amp0702/params.jsp?X=1&Y=2&Z=3 Source of params.jsp: <jsp:include page="included
.jsp"> <jsp:param name="X" value="4" /><jsp:param name="X" value="5" /><jsp:para
m name="Y" value="6" /></jsp:include>${param.X}<%=request.getParameter("Y")%>Sou
rce of included.jsp:${param.X} ${param.Y}<% String[] x = request.getParameterVal
ues("X");for (int i = 0; i < x.length; i++) {out.write(x[i]);}%> | 4 6 451 1 2
Which of the following are helpful statements about the include standard action
and the include directive? (Choose three.) | The include standard action is usef
ul when soft-coding the page to include. Given the same page to include, the inc
lude directive may be more effi cient than the include standard action at reques
t time. The body of the include standard action can infl uence existing request
parameters
What will be the result of requesting the JSP page represented by the following
source? Assume that oeforwardedTo.jsp is an empty file. (Choose one.)<%@ page import
="java.util.*,java.text.*" %><%! private String returnTimeStamp(PageContext page
Context) {DateFormat df = DateFormat.getDateTimeInstance();String s = df.format(
new Date());pageContext.setAttribute("timestamp", s);return s;} %><jsp:forward p
age="forwardedTo.jsp" /><%=returnTimeStamp(pageContext)%><%System.out.println(pa
geContext.getAttribute("timestamp"));%> | None of the above.
What is the outcome of making the HTTP GET request shown to params.jsp (source f
ollows)?(Choose one.)The HTTP request is in this form:http://localhost:8080/exam
p0702/params.jsp?X=1&Y=2&Z=3Source of params.jsp:<jsp:forward page="included.jsp
"><jsp:param name="X" value="4" /><jsp:param name="X" value="5" /><jsp:param nam
e="Y" value="6" /><jsp:forward/>${param.X}<%=request.getParameter("Y")%>Source o
f included.jsp:${param.X}${param.Y}<% String[] x = request.getParameterValues("X
");for (int i = 0; i < x.length; i++) {out.write(x[i]);}%> | None of the above
What is the outcome of accessing the following page, defi ned as a JSP document
in a web application? The line numbers are for reference only and should not be
considered part of the JSP page source. (Choose one.)01 <html xmlns:jsp="http://
java.sun.com/JSP/Page">02 <jsp:directive.page contentType="text/html" />03 <jsp:
declaration>04 public int squared(int value) {05 return value * value;06 }07 </j
sp:declaration>08 <jsp:scriptlet>09 int value = Integer.parseInt10 (request.getP
arameter("number"));11 int squared = squared(value);12 out.write(value + " squar
ed is " + squared);13 if (squared < 100) {14 out.write("; try a bigger number.")
;15 }16 </jsp:scriptlet>17 </html> | Translation error at line 13
Which of the following techniques will cause JSP page source to be treated as a
JSP document by the JSP container? (Choose two.) | Using a .jspx extension with
a version 2.4 deployment descriptor. Using <jsp:root> as the root element of you
r source
Which of the following tags will successfully complete the following JSP page ex
tract, at the points marked <jsp:???> and </jsp:???> ? (Choose one.)<html xmlns:
jsp="http://java.sun.com/JSP/Page" ><jsp:directive.page contentType="text/html"
/><head><title>Question 15</title></head><jsp:???><![CDATA[<img src="]]></jsp:??
?><jsp:expression>session.getAttribute("theImage")</jsp:expression><jsp:???><![C
DATA[" />]]></jsp:???></html> | <jsp:text> and </jsp:text>
Which of the following are implicit variables in EL? (Choose two.) | param. para
mValues
Which of the following EL expressions will return a <servlet-name> associated wi
th the JSP executing the expression? (Choose one.) | ${pageContext.servletConfig
.servletName}
Which of the following XML fragments, if placed below the root element in the de
ployment descriptor, will deactivate the scripting language for all fi les in th
e web application with a .jsp extension? (Choose one.) | <jsp-config><jsp-proper
ty-group><url-pattern>*.jsp</url-pattern><scripting-invalid>true</scripting-inva
lid></jsp-property-group></jsp-config>
Which of the following deployment descriptors will successfully and legally deac
tivate Expression Language for an entire web application? (Choose two) | a. <?xm
l version="1.0" ?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web A
pplication 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app></web-app>
b. <?xml version="1.0" ?><web-app version="2.4" xmlns="http://java.sun.com/xml/
ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
"><jsp-config><jsp-property-group><url-pattern>/*</url-pattern><el-ignored>true<
/el-ignored></jsp-property-group></jsp-config></web-app>
From the following use of the tag <mytags:convert>, what statements must be true
about its setup and use? You can assume that the tag translates and executes co
rrectly. (Choose three.) <mytags:convert currency="${param.cur}"><%= amount %></
mytags:convert> | The taglib declaration has a prefi x of oemytags. . In the TLD, the
tag s body content element has a value of JSP. In the TLD, the tag s currency attribut
has the rtexprvalue element set to true.
Which of the following characters are not converted by the <c:out> action when t
he attribute escapeXml is set to false? (Choose one.) | All of the above
Which of the following are invalid uses of the <c:set> action? (Choose three.) |
a. <c:set scope="page">value</c:set> b. <c:set value="value" var="${myVar}" />
c. <c:set var="myVar" scope="${scope}">value</c:set>
What is the result of attempting to access the following JSP page source? You ca
n assume that the file countries.txt exists in the location specifi ed. (Choose
one.)<html xmlns:mytags="http://www.osborne.com/taglibs/mytags"xmlns:jsp="http:/
/java.sun.com/JSP/Page"xmlns:c="http://java.sun.com/jsp/jstl/core" ><jsp:output
omit-xml-declaration="true" /><jsp:directive.page contentType="text/html" /><jsp
:directive.page import= oejava.io.*" /><head><title>Question 9</title></head><body>
<c:import url="/countries.txt" varReader="myReader" /><jsp:scriptlet>Reader r =
(Reader) pageContext.getAttribute("myReader");out.write(r.read());</jsp:scriptle
t></body></html> | The first character of the fi le countries.txt is sent to pag
e output.
What is the minimum number of attributes that must be specified in the <c:forEac
h> action? (Choose one.) | 1-items
Which of the following characteristics must a Java class have if it contains one
or more EL functions? (Choose three.) | A method that is public. A method that
is static. A main method (signature: public static void main(String[] args))
Which of the following represents a correct function declaration in the tag libr
ary descriptor?(Choose one.) | <function><description>Taxation Function</descrip
tion><name>netincome</name><function-class>webcert.ch08.ex0803.Taxation.class</f
unction-class><function-signature>java.lang.String calcNetIncome(double, double,
double, java.lang.String)</function-signature></function>
What is the result of attempting to access the following JSP? You can assume tha
t the EL functions are legally defi ned, that the EL function mytags:divide divi
des the fi rst parameter by the second parameter, and that the EL function mytag
s:round rounds the result from the first parameter to the number of decimal plac
es expressed by the second parameter.(Choose one.)<html><%@ taglib prefix="mytag
s" uri="http://www.osborne.com/taglibs/mytags" %><head><title>Question 13</title
></head><body><p>${mytags:round(${mytags:divide(arg1, arg2)}, 2)}</p></body></ht
ml> | Translation error (in code generation).
Where in JSP page source can EL functions be used? (Choose two.) | In the body o
f a tag where body-content is set to scriptless. In the body of a tag where body
-content is set to JSP
Consider these pairings of Java method signatures and EL function method signatu
res for a TLD file. Which pairings go together and will work? (Choose two.) | Ja
va: public static String getNameForId(int id) TLD: java.lang.String getNameForId
(int) b. Java: public static java.lang.String getNameForId(java.lang.String id)
TLD: java.lang.String getNameForId(java.lang.String)
Which of the following are valid statements relating to the <body-content> eleme
nt in the tag library descriptor? (Choose two.) | To permit EL but not JSP expre
ssions, <body-content> should be set to scriptless. b. JSP expressions are legal
in the body of a custom action whose <body-content> is set to tagdependent, but
they will not be translated.
For the given interfaces, which of the following are valid sequences of method c
alls according to custom tag life cycle? (Choose three.) | Tag: setPageContext,
setParent, doStartTag, doEndTag. IterationTag: doStartTag, doAfterBody, doAfterB
ody, doAfterBody. BodyTag: doStartTag, setBodyContent, doInitBody, doAfterBody
Given the following JSP and tag handler code, what is the result of accessing th
e JSP? (Choose one.) JSP Page Source<%@ taglib prefix="mytags" uri="http://www.o
sborne.com/taglibs/mytags" %><html><head><title>Questions</title></head><body><p
><% session.setAttribute("first", "first"); %><mytags:question01 />${second}</p>
</body></html>Tag Handler Code for <mytags:question01 />(imports missing, but as
sume they are correct)public class Question01 extends TagSupport {public int doS
tartTag() throws JspException {Writer out = pageContext.getOut();try {out.write(
"" + pageContext.getAttribute("first"));} catch (IOException e) {e.printStackTra
ce();}pageContext.setAttribute("second", "second", PageContext.SESSION_SCOPE);re
turn super.doStartTag();}} | null second
Which of the following snippets of code, if inserted into the doStartTag() metho
d of a tag handler class extending TagSupport, would compile? (Choose three.) |
pageContext.getSession().getId(); b. pageContext.getException().getStackTrace();
c. pageContext.getExpressionEvaluator();
Identify true statements about the exception implicit object in tag handler code
.(Choose two.) | It can be obtained through the page context s getError() method. Th
e JSP page housing the tag must have page directive isErrorPage set to true for
exception to be non-null in the tag handler code.
Which of the following methods are available in the java.servlet.jspPageContext
class? (Choose three.) | getServletConfig b. include c. getErrorData
For a tag implementing the SimpleTag interface, which of the following method se
quences might be called by the JSP container? (Choose two.) | setJspContext, set
AnAttribute, doTag. setJspContext, setParent, doTag
Which of the following techniques causes the JSP container to skip the rest of t
he page after processing a custom action implementing the SimpleTag interface? (
Choose one.) | Throwing a SkipPageException within the doTag() method
Consider the following JSP page code and SimpleTag code. What is the output from
tag<mytags:question08> to the requesting JSP page? You can assume that all nece
ssary deployment descriptor and tag library descriptor elements are set up corre
ctly. (Choose one.)JSP Page Code:<%@ taglib prefix="mytags" uri="http://www.osbo
rne.com/taglibs/mytags"%><html><head><title>Question08</title></head><body><p><m
ytags:question08>a</mytags:question08></body></html>SimpleTag Tag Handler Code f
or <mytags:question08>:import java.io.IOException;import java.io.StringWriter;im
port javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;public class Question08 extends
SimpleTagSupport {public void doTag() throws JspException, IOException {JspFrag
ment fragment = getJspBody();StringWriter sw = new StringWriter();for (int i = 0
; i < 3; i++) {fragment.invoke(sw);String s = "b" + sw;sw.write(s);fragment.invo
ke(null);}}} | aaa
Identify true statements about tag declarations in tag library descriptors from
the following list. (Choose three.) | a. A tag whose <body-content> is declared
as JSP must follow the classic tag model.b. Simple tags are commonly declared wi
th a <body-content> of scriptless.c. If a simple tag is declared with a <body-co
ntent> of oeempty, the JSP container makes one less method call on the simple tag ha
ndler class.
Consider the following JSP page code and SimpleTag code. What is the output from
tag<mytags:question08> to the requesting JSP page? You can assume that all nece
ssary deployment descriptor and tag library descriptor elements are set up corre
ctly. (Choose one.) JSP Page Code:<%@ taglib prefix="mytags" uri="http://www.osb
orne.com/taglibs/mytags"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jst
l/core" %><html><head><title>Question 10</title></head><c:set var="counter">1</c
:set><body><p><mytags:question10><c:forEach begin="${counter}" end="3">${counter
}</c:forEach></mytags:question10></p></body></html>SimpleTag Tag Handler Code fo
r <mytags:question08>:package webcert.ch09.questions09;import java.io.IOExceptio
n;import javax.servlet.jsp.JspContext;import javax.servlet.jsp.JspException;impo
rt javax.servlet.jsp.tagext.SimpleTagSupport;public class Question10 extends Sim
pleTagSupport {public void doTag() throws JspException, IOException {JspContext
context = ....for (; i < 4; i++) { | 111 22 3
From the list, identify correct techniques to make tag fi les available in a JSP
page or JSP document. (Choose two.) | a. <html xmlns:mytags="urn:jsptagdir:/WEB
-INF/tags/"> b. <%@ taglib prefix="mytags" tagdir="/WEB-INF/tags" %>
What is the result of accessing the following tag fi le? (Line numbers are for r
eference only and should not be considered part of the tag fi le source.) (Choos
e one.)01 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>02 <c:
set var="character">65</c:set>03 <c:forEach begin="1" end="10" varStatus="loopCo
unt" >04 <% char c = (char)Integer.parseInt(pageContext.getAttribute("character"
).toString());05 pageContext.setAttribute("displayCharacter", new Character(c));
07 %>08 ${displayCharacter}09 <c:set var="character">${character + 1}</c:set>10
</c:forEach> | Translation error at line 4
Which of the following are directives you might find in a tag file? (Choose thre
e.) page | a. tag b. variable c. attribute
Consider the following hierarchy of actions. <c:if> is from the JSTL core librar
y, and <a: tagA> and <a:tagB> are classic custom actions.<a:tagA><c:if test="${t
rue}"><a:tagB /></c:if></a:tagA>What options does tagB have for obtaining the en
closing instance of tagA? | a. Use TagSupport.findAncestorWithClass() b. Invoke
getParent().getParent(). c. Use SimpleTagSupport.findAncestorWithClass()
Which of the following could not be returned by either of the getParent() method
s in the JSP class libraries? (Choose two.) | a. An instance of an HTML tag b. A
n instance of an XML template tag in a JSP document
What methods can you execute on the reference myAncestor at ??? in the code snip
pet below? (Choose two.) JspTag myAncestor = SimpleTagSupport.findAncestorWithCl
ass(MyTagClass); myAncestor.??? | a. notifyAll() b. hashCode()
What strategies might a parent tag use to get hold of a child tag handler instan
ce?(Choose two.) | a. Classic model: Child gets hold of parent and provides the
parent with its own reference to the child. Parent uses the reference in doAfter
Body() method. b. Simple model: Child gets hold of parent and provides the paren
t with its own reference to the child. Parent uses the reference after a call to
JspFragment.invoke().
Which of the following patterns can reduce network overhead? (Choose one.) | a.
Business Delegate b. Service Locator c. Transfer Object d. B, C, and D above ANS
: D
Which pattern insulates the presentation client code from volatility in business
APIs?(Choose one.) | a. Business Delegate
A company has a message queuing system, accessible with complex Java APIs. The c
ompany wants a new web application but also wants to minimize the specialized kn
owledge required to write business code that accesses the queuing system. Which
J2EE patterns might best help the company with this problem? (Choose two.) | a.
Service Locator b. Business Delegate
From the following list, choose benefits that are usually conferred by the Trans
fer Object pattern. (Choose two.) | a. Reduces network traffic b. Packages data
into an accessible form
A company wants to structure its development department on specialist lines so t
hat web designers can concentrate on page layout and Java developers can concent
rate on business API development. Which pattern should the company use in applic
ation development to best support its organizational aims? (Choose one.) | a. Mo
del View Controller
From the following list, choose benefits that are usually conferred by the Servi
ce Locator pattern. (Choose two.) | a. Reduces strain on the Business Delegate p
attern b. Encapsulates naming service code
Which of the following patterns might best be used to reject requests from a hos
t machine with oeuk in its domain name? (Choose one.) | a. Intercepting Filter
From the following list, choose benefi ts that are usually conferred by the Mode
l View Controller pattern. (Choose two.) | a. Separation of concerns b. Better p
roject management
Which of the following patterns might be used to dispatch a view containing an a
pplicationfriendly error message? (Choose one.) | a. Front Controller
From the following list, choose benefi ts that are usually conferred by the Busi
ness Delegate pattern. (Choose two.) | a. Presentation code stability b. Better
network performance
Which scenario below could best use Transfer Object as a solution? (Choose one.)
| a. An application appears to have hit a bottleneck when using some EJBs. On a
nalysis, it appears that there are numerous method calls to retrieve individual
attributes.
From the following list, choose benefi ts that are usually conferred by the Fron
t Controller pattern. (Choose three.) | a. Acts a gateway for requests to the sy
stem b. Centralizes control of navigation c. Reduces complexity of links in JSPs
Which of the patterns below will defi nitely reduce the lines of code in an appl
ication? (Choose one.) | a. None of the above
From the following list, choose reasonable applications for the Intercepting Fil
ter pattern. (Choose one.) | a. All of the above
Which of the patterns below might reduce the lines of code in an application? (C
hoose one.) | a. All of the above
Message-driven beans are classes that implement 2 interfaces : | a. javax.ejb.Me
ssageDrivenBean b. javax.jms.MessageListener
Which are the types of messaging domains ? (choose 2) | a. Publish/Subcribe b. P
oint-to-Point
Select the correct JMS programming model | a. Locate the JMS Driver ->Create a J
MS connection ->Create a JMS session ->Create a JMS producer or a JMS consumer -
> Send or receive message
Message-driven beans do not have any return value | a. False
Select the word to replace ??? to make the diagram about messaging domain correc
t | a. Topic
A ____ subscription to a topic means that a JMS subscriber receives all message
even if the subscriber is inactive | a. Durable
In ejb-jar.xml file, <persistence-type> element value is __________ | a. Bean or
Container
Entity bean is ______ | a. a persistent data component
ejbCreate() method of entity bean class returns ______ | a. primary key
create() method of entity home interface returns _________ | a. null
select CORRECT statement (choose 2) | a. Entity beans represent persistent state
objects (things that don't go away when user goes away) b. Session beans model
a process or workflow (actions that are started by the user and that do away whe
n user goes away)
The _______ class makes every entity bean different | a. primary key
The top three values of EJB are (choose 3): | a. Portability is easier b. Rapid
Application Development c. It is agreed upon by the industry
Which is not the players in the EJB Ecosystem? (choose 1): | a. End User
The ______ is the overall application architect .This party is responsible for u
nderstanding how various components fit together and writes the application that
combine components. | a. Application Assembler
which is not the role of EJB Deployer? | a. Write the code that calls on compone
nts supplied by bean providers
The ________ supplies business components,or enterprise beans | a. Bean provider
Is the statement true or false. The deployment descriptor of a web application m
ust have the name web.xml.In the same way the tag library descriptor file must b
e called taglib.xml | a. False
Given the following JSP and Tag handler code,what is the result of accessing the
JSP ? JSP Page Source <html> <body><%@taglib uri = "test_taglib" prefix = "myTa
g"%><% session.setAttribute("first", "first");%><myTag:TestTag/><br><%=session.g
etAttribute("second")%></body></html>Tag Handler Code for <myTag:TestTag/>pakage
examples;import java.io.*;import javax.servlet.jsp.*;import javax.servlet.jsp.t
agext.*;public class TestTag extends TagSupport{private PageContext pageContext;
public void setPage(PageContextpage){this.pageContext=page;}public int doStartTa
g() throws JspException {try{String first = pageContext.getSession().getAttribut
e("first").toString();pageContext.getOut().write(first);pageContext.setAttribute
("second", "second", PageContext.PAGE_SCOPE);}catch(IOException){throw new JspEx
ception(i.getMessage());}return SKIP_BODY;}public int doEndTag() throws JspExcep
tion{return EVAL_PAGE;}public void release(){}}Assume *.tld and web.xml files ar
e correct. | a. SKIP_PAGE
A JSP file that uses a tag library must declare the tag library first. The tag l
ibrary is defined using the taglib directive <%@taglib uri = "..." prefix="..."%
> Which of the following specifies the correct purpose of prefix attribute.SELEC
T the one correct answer. | a. The prefix attribute is used in front of a tag de
fined within the tag library
A programmer is designing a class to encapsulate the information about an invent
ory item. A JavaBeans component is need to do this. The InventoryItem has privat
e instance variables to store the item information:10.private int itemld;11.priv
ate String name;12.private String description;Which method signature follows the
JavaBeans naming standards for modifying the itemld instance variable? (choose
one) | a. setItemld(int itemld)
Name the class that includes the SetSession method that is used to get the httpS
ession object | a. HttpSevletRequest
Which of the following are potential legal of JSP source ? (choose 2) | a. <jsp:
useBean id = "beanName1" class="a.b.MyBean"type="a.b.Myinterface"/> b. <% String
myValue = "myValue";%> <jsp:setProperty name ="beanName1" property="soleProp" v
alue ' "<%=myValue%>"/>
<html><body><form action="loginPage.jsp">Login ID:<input type = "text " name = "
loginID"><br>Password:<input type = "password" name = "password"><br><input type
="submit" value="Login"><input type="reset" value =Reset"></form></body></html>S
tudy the above html code: Assume that user clicks button Reset.What is the corre
ct statement ? (choose 1) | a. Nothing changes
Which syntax is correct for JSP Declarations : | a. <% code %>
Review the following scenario,then identify which security mechanisms would be i
mportant to fulfill the requirement (choose 2) An online magazine company wishes
to protect part of its web site content,to make that part avalaible only to use
rs who pay a monthly subcription.The company wants to keep client, network and s
erver processing overheads down: Theft of content is unlikely to be an issue,as
is abuse of user IDs and passwords through network snooping. | a. Authentication
b. Authorization
Which security mechanism limits access to the availability of permitted groups o
f users or programs ? (choose one) | a. Authorization
Which security mechanism proves that data has not been tampered with during its
transit through the network ? (choose 1) | a. Data integrity
The following web is defined as the custom form login page for authentication. A
ssuming that you have attempted to access a protected resource and been redirect
ed to this web page, what is the result of filling in the user name and password
fields and pressing submit (choose 1)<html><head><title>login Form</title></hea
d><body><form action="jsecuritycheck" method="POST"><br /> Name:<input type = "t
ext" name = jusername" /><br /> Password:<input type = "pasword" name = jpasswor
d" /><br /><input type = "submit" value = "Log In" /></form></body></html> | a.
The page is redisplay
Which is correct JDBC-ODBC driver name? | a. sun.jdbc.odbc.JdbcOdbcDriver
Choose three correct statements in JDBC | a. getObject b. getText c. getInt d. g
etString
Which is correct sequence for a JDBC execution? | a. Load Driver -> Connection -
> Statement -> ResultSet
Which are the correct statements of Connection object? (Choose two) | a. createS
tatement(int, int); b. createStatement();
Which are the correct statements of ResultSet object? (Choose three) | a. execut
eQueries() b. execute() c. executeUpdate()
To send text outptut in a response, the following method of HttpServletResponse
may be used to get the appropriate Writer/Stream object. Select the one correct
answer. | a. getWriter
Which of these is true about deployment descriptors. Select the one correct answ
er | a. The order of elements in deployment descriptor is important. The element
s must follow a specific order
The exception-type element specifies an exception type and is used to handle exc
eptions generated from a servlet. Which element of the deployment descriptor inc
ludes the exception-type as a sub-element. Do not include the element in enclosi
ng parenthesis | a. error-page
______ is a set of java API for executing SQL statements. | a. JDBC
JDBC supports ______ and ______ models. | a. Two-tier and three-tier
URL referring to databases use the form: | a. jdbc:odbc:datasoursename
Study the statements:1)When a JDBC connection is created, it is in auto-commit m
ode 2)Once auto-commit mode is disabled, no SQL statements will be committed unt
il you call the method commit explicitly | a. Both 1 and 2 are true
The ______ class is the primary class that has the driver information. | a. Driv
erManager
The method getWriter returns an object of type PrintWriter. This class has print
ln methods to generate output. Which of these classes define the getWriter metho
d? Select the one correct answer. | a. HttpServletResponse
Name the method defined in the HttpServletResponse class that may be used to set
the content type. Select the one correct answer. | a. setContent
Which of the following statement is correct. Select the one correct answer. | a.
The HttpServletResponse defines constants like SC_NOT_FOUND that may be used as
a parameter to setStatus method.
The sendError method defined in the HttpServlet class is equivalent to invoking
the setStatus method with the following parameter. Select the one correct answer
. | a. SC_NOT_FOUND
To send binary output in a response, the following method of HttpServletResponse
may be used to get the appropriate Writer/Stream object. Select the one correct
answer. | a. getOutputStream
To send text output in a response, the following method of HttpServletResponse m
ay be used to get the appropriate Writer/Stream object. Select the one correct a
nswer. | a. getWriter
Is the following statement true or false. URL rewriting may be used when a brows
er is disabled. In URL encoding the session id is included as part of the URL. |
a. True
Which of the following are correct statements? Select the two correct answers. |
a. The getRequestDispatcher method of ServletContext class takes the full path
of the servlet, whereas the getRequestDispatcher method of HttpServletRequest cl
ass takes the path of the servlet relative to the ServletContext. b. The getRequ
estDispatcher(String URL) is defined in both ServletContext and HttpServletReque
st method
A user types the URL http://www.javaprepare.com/scwd/index.html . Which HTTP req
uest gets generated. Select the one correct answer. | a. GET method
Which HTTP method gets invoked when a user clicks on a link? Select the one corr
ect answer. | a. GET method
When using HTML forms which of the folowing is true for POST method? Select the
one correct answer. | a. POST method sends data in the body of the request.
Which of the following is not a valid HTTP/1.1 method. Select the one correct an
swer. | a. COMPARE method
Name the http method used to send resources to the server. Select the one correc
t answer. | a. PUT method
Name the http method that sends the same response as the request. Select the one
correct answer. | a. TRACE method
Which three digit error codes represent an error in request from client? Select
the one correct answer. | a. Codes starting from 400
Name the location of compiled class files within a war file? Select the one corr
ect answer. | a. /WEB-INF/classes
Which of the following is legal JSP syntax to print the value of i. Select the o
ne correct answer | a. <%int i = 1;%> <%= i %>
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/test.jsp? name="John". The test.jsp contains the following code.<%! Stri
ng myName=request.getParameter();%><% String test= "welcome" + myName; %><%= tes
t%> | a. The program gives a syntax error because of the statement <%! String my
Name=request.getParameter();%>
Which of the following correctly represents the following JSP statement. Select
the one correct answer.<%=x%> | a. <jsp:expression>x</jsp:expression>
Which of the following correctly represents the following JSP statement. Select
the one correct answer. <%x=1;%> | a. <jsp:scriptlet>x=1;</jsp:scriptlet>
What gets printed when the following JSP code is invoked in a browser. Select th
e one correct answer.<%= if(Math.random() < 0.5) %> hello<%= } else { %>hi<%= }
%> | a. The JSP file will not compile.
Which of the following are correct. Select the one correct answer. | a. To use t
he character %> inside a scriptlet, you may use %\> instead.
What gets printed when the following is compiled. Select the one correct answer.
<% int y = 0; %><% int z = 0; %><% for(int x=0;x<3;x++) { %><% z++;++y;%><% }%>
<% if(z<y) {%><%= z%><% } else {%><%= z - 1%><% }%> | a. 2
Which of the following JSP variables are not available within a JSP expression.
Select the one correct answer. | a. httpsession
A bean with a property color is loaded using the following statement <jsp:usebea
n id="fruit" class="Fruit"/> Which of the following statements may be used to se
t the of color property of the bean. Select the one correct answer. | a. <jsp:se
tProperty name="fruit" property="color" value="white"/>
A bean with a property color is loaded using the following statement<jsp:usebean
id="fruit" class="Fruit"/>What happens when the following statement is executed
. Select the one correct answer.<jsp:setProperty name="fruit" property="*"/> | a
. All the properties of the fruit bean are assigned the values of input paramete
rs of the JSP page that have the same name.
Is the following statement true or false. If the isThreadSafe attribute of the p
age directive is false, then the generated servlet implements the SingleThreadMo
del interface. | a. True
Which of the following represents a correct syntax for usebean. Select the two c
orrect answers. | a. <jsp:usebean id="fruit type ="String"/> b. <jsp:usebean id=
"fruit type ="String" beanName="Fruit"/>
Name the default value of the scope atribute of <jsp:usebean>. | a. page
Which of these are legal attributes of page directive. Select the two correct an
swers. | a. errorPage b. session
Which of the following represents the XML equivalent of this statement <%@ inclu
de file="a.jsp"%>. Select the one correct statement | a. <jsp:directive.include
file="a.jsp"/>
Assume that you need to write a JSP page that adds numbers from one to ten, and
then print the output. <% int sum = 0;for(j = 0; j < 10; j++) { %>// XXX --- Add
j to sum<% } %>// YYY --- Display ths sum Which statement when placed at the lo
cation XXX can be used to compute the sum. Select the one correct statement | a.
<% sum = sum + j; %>
Now consider the same JSP example as last question. What must be added at the lo
cation YYY to print the sum of ten numbers. Select the one correct statement | a
. <%= sum %>
JSP pages have access to implicit objects that are exposed automatically. One su
ch object that is available is request. The request object is an instance of whi
ch class? | a. HttpServletRequest
JSP pages have access to implicit objects that are exposed automatically. Name t
he implicit object that is of type HttpSession. | a. session
A Java bean with a property color is loaded using the following statement <jsp:u
sebean id="fruit" class="Fruit"/> What is the effect of the following statement.
<jsp:setproperty name="fruit" property="color"/>Select the one correct answer.
| a. If there is a non-null request parameter with name color, then its value ge
ts assigned to color property of Java Bean fruit.
The page directive is used to convey information about the page to JSP container
. Which of these are legal syntax of page directive. Select the two correct stat
ement | a. <%@ page info="test page" session="false"%> b. <%@ page session="true
" %>
Is the following JSP code legal? Select the one correct statement. <%@page info=
"test page" session="false"%> <%@page session="false"%> | a. No. This code will
generate syntax errors.
A JSP page needs to generate an XML file. Which attribute of page directive may
be used to specify that the JSP page is generating an XML file. | a. contentType
A JSP page uses the java.util.ArrayList class many times. Instead of referring t
he class by its complete package name each time, we want to just use ArrayList.
Which attribute of page directive must be specified to achieve this. Select the
one correct answer. | a. import
Which of these are true. Select the two correct answers. | a. The default value
of isThreadSafe attribute of page directive is true. b. When isThreadSafe attrib
ute of page directive is set to true, a thread is created for each request for t
he page.
Which of the following are examples of JSP directive. Select the two correct ans
wers. | a. include b. page
Which of these is true about include directive. Select the one correct answer. |
a. When using the include directive, the JSP container treats the file to be in
cluded as if it was part of the original file.
Name the implicit variable available to JSP pages that may be used to access all
the other implicit objects. | a. pageContext
When implementing a tag, if the tag just includes the body verbatim, or if it do
es not include the body, then the tag handler class must extend the BodyTagSuppo
rt class. Is this statement true of false. | a. False
Fill in the blanks. A tag handler class must implement the javax.servlet.jsp.tag
ext.Tag interface. This is accomplished by extending the class TagSupport or ano
ther class named in one of the options below. Select the one correct answer. | a
. BodyTagSupport
Is this statement true or false. The deployment descriptor of a web application
must have the name web.xml . In the same way the tag library descriptor file mus
t be called taglib.xml . | a. False
A JSP file that uses a tag library must declare the tag library first. The tag l
ibrary is defined using the taglib directive - <%= taglib uri="..." prefix="..."
%> Which of the following specifies the correct purpose of prefix attribute. Sel
ect the one correct answer. | a. The prefix attribute is used in front of a tagn
ame of a tag defined within the tag library.
A JSP file uses a tag as <myTaglib:myTag>. The myTag element here should be defi
ned in the tag library descriptor file in the tag element using which element. S
elect the one correct answer. | a. name
Which of the elements defined within the taglib element of taglib descriptor fil
e are required. Select the two correct answers. | a. tlib-version b. short-name
Name the element within the tag element that defines the name of the class that
implements the functionality of tag. Select the one correct answer. | a. tag-cla
ss
Which of these are legal return types of the doStartTag method defined in a clas
s that extends TagSupport class. Select the two correct answers. | a. EVAL_BODY_
INCLUDE b. SKIP_BODY
Which of these are legal return types of the doAfterBody method defined in a cla
ss that extends TagSupport class. Select the two correct answers. | a. EVAL_BODY
_AGAIN b. SKIP_BODY
Which of these are legal return types of the doEndTag method defined in a class
that extends TagSupport class. Select the two correct answers. | a. EVAL_PAGE b.
SKIP_PAGE
Which element of the servlet element in the deployment descriptor is used to spe
cify the parameters for the ServletConfig object. Select the one correct answer.
| a. init-param
Which of these is true about deployment descriptors. Select the one correct answ
er. | a. The order of elements in deployment descriptor is not important. The el
ements can follow any order.
The exception-type element specifies an exception type and is used to handle exc
eptions generated from a servlet. Which element of the deployment descriptor inc
ludes the exception-type as a sub-element. Select the one correct answer. | a. e
rror-page
Which of these is a correct fragment within the web-app element of deployment de
scriptor. Select the one correct answer. | a. <error-page><exception-type> mypac
kage.MyException</exception-type><location> /error.jsp</location></error-page>
Which element of the deployment descriptor of a web application includes the wel
come-file-list element as a subelement. Select the one correct answer. | a. web-
app
Which of these is a correct fragment within the web-app element of deployment de
scriptor. Select the two correct answer. | a. <error-page><error-code>404</error
-code><location>/error.jsp</location></error-page> b. <error-page><exception-typ
e>mypackage.MyException</exception-type><location>/error.jsp</location></error-p
age>
Which of these is a correct example of specifying a listener element resented by
MyClass class. Assume myServlet element is defined correctly. Select the one co
rrect answer. | a. <listener><listener-class>MyClass</listener-class></listener>
The root of the deployment descriptor is named as | a. web-app
With in a context-param element of deployment descriptor, which of the following
element is required? | a. param-name
Which of these is not a valid top level element in web-app | a. param-name
Which of the follwing are mandatory elements within the filter element. Select t
wo correct answers. | a. filter-name b. filter-class
Which of these is not a valid value for dispatcher element of filter-mapping. Se
lect the one correct answer. | a. RESPONSE
Which of these is not correct about the filter-mapping element of web-app. Selec
t the one correct answer. | a. dispatcher element can be declared zero to three
times in the filter-mapping element.
What gets printed when the following expression is evaluated? Select the one cor
rect answer. {4 div 5} | a. 0.8
What gets printed when the following expression is evaluated? Select the one cor
rect answer.${12 % 4} | a. 0
What is the effect of executing the following JSP statement, assuming a class wi
th name Employee exists in classes package. <%@ page import = "classes.Employee"
%><jsp:useBean id="employee" class="classes.Employee" scope="session"/><jsp:set
Property name="employee" property="*"/> | a. The code sets the values of all pro
perties of employee bean to matrching parameters in request object.
What is the effect of evaluation of following expression? Select the one correct
answer. ${(5*5) ne 25} | a. false
What is the effect of evaluation of following expression? Select the one correct
answer. ${'cat' gt 'cap'} | a. true
How many numbers are printed, when the following JSTL code fragment is executed?
Select the one correct answer. <%@ taglib uri="http://java.sun.com/jsp/jstl/cor
e" prefix="c" %> <c:forEach var="item" begin="0" end="10" step="2">${item}</c:fo
rEach> | a. 6
What gets printed when the following JSTL code fragment is executed? Select the
one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><c:set var="item" value="2"/><c:if test="${var==1}" var="result" scope="sessi
on"><c:out value="${result}"/></c:if> | a. Nothing gets printed.
What gets printed when the following JSTL code fragment is executed? Select the
one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><c:set var="item" value="2"/><c:forEach var="item" begin="0" end="0" step="2"
><c:out value="${item}" default="abc"/></c:forEach> | a. 0
Which numbers gets printed when the following JSTL code fragment is executed? Se
lect the two correct answers.<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %><c:set var="j" value="4,3,2,1"/><c:forEach items="${j}" var="item"
begin="1" end="2"><c:out value="${item}" default="abc"/></c:forEach> | a. 2 b. 3
Which of these represent the correct path for the core JSTL library in JSTL vers
ion 1.1? Select the one correct answer. | a. http://java.sun.com/jsp/jstl/core
Which statement is true about java server page life cycle: | a. All serverlet me
thods are accessible from the jsp(init() method. b. Jsp Service() method is call
ed from the generate Servlet s Service() method.
http Sesision object live on the server | a. True
Whenever a method does not want to handle exception using the try block, the ___
__ is used? | a. Throws
_____ has a name, single value, optional such as comment maximum age, version na
me | a. Cookie
A<servlet> element can include to many <init-parent> elements: these action pass
ing initialization parameter Infomation from the deployment descriptor to all se
rvlet? | a. True
A ____ dialogs prevent user input in the other windows in the application unit d
ialog is close | a. Modal
Session death can come about through an explicit call(in servlet) to http sessio
n invalidate() | True
A class should extends httpServlet and override doGet(), doPost() depend on whet
her the data is being sent by get or post | a. True
To be a serverlet, a class should extend Http Serverlet and override doGet or do
Post,depending on whether the data is being sent by GET on by Post | a. True
Swing components can t be combine with AWT | a. False
How many sesssion (Http Serverlet Request) time out mechanisms | a. 3
The special directory /WEB-INF/ class contain JAR files with supporting librarie
s of code | a. False
Class implement FIFO queue | a. Link list
Which of the following are valid iteration mechanisms in jsp? | a. <% int i = 0;
for(;i<5; i++){ %>"Hello World";<% i++;}%>
Which of the following methods will be invoked if the doStartTag() method of a t
ag returns Tag.SKIP_BODY? | a. doEndTag()
Select the BEST case to use message-driven bean?(Choose one) | a. Need to avoid
tying up server resources andneed the applications to process messages asynchron
ously
Which of the following method can be used to add cookies to a servlet response?
| a. HttpServletResponse.addCookie(Cookie cookie)
The page directive is used to convey information about the page to JSP container
. Which statement is legal page directive. Select one correct statement | a. <%@
page info="test page" session="false"%>
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/Final/test.jsp?name=John. The test.jsp contains the following code. <% S
tring myName=request.getParameter("name");%> <% String test= "Welcome " + myName
; %> <%=test%> What is the output? | a. The page display "Welcome John"
What will happen when a servlet makes the following call within its doGet() meth
od? getServletContext().setAttribute("userid", userid); | a. The userid attribut
e is placed in application scope.
Which of the following is true statement about the JavaServer Page life cycle? (
Choose one) | a. The _jspService() method is called from the generated servlet s ser
vice() method.
Which is NOT the main type of JSP constructs that you embed in a page? | a. acti
ons
Which statement(s) about Servlet Life Cycle is(are) correct? (Choose one) | a. A
ll the others
_______________ sends a request to an object and includes the result in a JSP fi
le. | a. <jsp:include>
Which syntax is correct for JSP Declarations? | a. <%! code %>
Which statement is correct about Container-managed persistent (CMP)? | a. Contai
ner-managed persistent persisted by the Enterprise Java Beans container
Your jsp page uses classes from java.util package. Which of the following statem
ent would allow you to import the package? (Choose one) | a. <%@ page import="ja
va.util.*"%>
Which of the following is a valid standard action that can be used by a jsp page
to import content generated by another JSP file named another.jsp? | a. <jsp:in
clude page='another.jsp'/>
Which class that includes the getSession method that is used to get the HttpSess
ion object? | a. HttpServletRequest
Which of the following statement correctly store an object associated with a nam
e at a place where all the servlets/jsps of the same webapp participating in a s
ession can access it? Assume that request, response, name, value etc. are refere
nces to objects of appropriate types. (Choose one) | a. request.getSession().set
Attribute(name, value);
If a ______________is being used then all the operations need to be written by t
he developer to a persistent API. | a. Bean-Managed persistent entity bean
Which is the CORRECT statement? | a. Entity beans represent persistent state obj
ects (things that don t go away when the user goes away).
Study the statements:1) URL rewriting may be used when a browser is disabled coo
kies.2) In URL encoding the session id is included as part of the URL.Which is t
he correct option? | a. Both 1 and 2 are true
A ___________________________ in EJB is an object that is deploy on any EJB Serv
er | a. Component
A .. manages the threading for the servlets and JSPs and provides the nec
Web server. | a. Web Container
create() method of entity bean home interface returns _____________ | a. null
The _________________ is the overall application architect. This party is respon
sible for understanding how various components fit together and writes the appli
cations that combine components. | a. Application Assembler
Identify correct statement about a WAR file.(Choose one) | a. It contains web co
mponents such as servlets as well as EJBs.
Which of the following statement is correct? (choose one) | a. Authorization mea
ns determining whether one has access to a particular resource or not.
A session bean being used by a client can also be used by another client. | a. F
alse
Which of the following is example of JSP directive? Select one correct answer. |
a. include
Which interface and method should be used to retrieve a servlet initialization p
arameter value?(Choose one) | a. ServletConfig : getInitParameter(String name)
Which of the following classes define the methods setStatus(...) and sendError(.
..) used to send an HTTP error back to the browser? | a. Both are defined in Htt
pServletResponse.
Which is NOT EJB container? | a. Apache Tomcat 5.5
Which of the statements regarding the following code are correct? public void do
Post(HttpServletRequestreq, HttpServletResponse res) throws IOException, Servlet
Exception{res.getWriter().print("Hello ");RequestDispatcherrd = getServletContex
t().getRequestDispatcher("/test.jsp");rd.include(req, res);res.getWriter().print
("World");} | a. "Hello" and "World" both will be a part of the output.
Which statement is true? | a. When isThreadSafe attribute of page directive is s
et to true, a thread is created for each request for the page
Which of the following elements are used for error handling and are child elemen
ts of <web-app> of a deployment descriptor? | a. <error_page>
Message-driven beans do not have any return value. | a. True
Given the following deployment descriptor:<web-app>context-param><param-name>jdb
cDriver</param-name><param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value></con
text-param><servlet><servlet-name>InitParams</servlet-name><servlet-class>InitPa
ramsServlet</servlet-class></servlet>.. </web-app>What is the outcome of running
the following servlet? (Choose one.)public class InitParamsServlet extends Http
Servlet {protected void doGet(HttpServletRequest request, HttpServletResponse re
sponse) throwsServletException, IOException {ServletContextsc = this.getServletC
ontext();PrintWriter out = response.getWriter();out.write("Initialization Parame
ter is: " + sc.getInitParameter("jdbcDriver"));}} | "Initialization Parameter is
: null" returned to the requester
Consider the contents of 2 jsp files:<!-- In File : test.jsp --><html><body><% S
tring s = "Hello"; %>//1 insert LOC here.<%=s%></body></html><!-- In File : test
2.jsp --><% s = s+" world"; %>What can be inserted at //1 so that it prints "Hel
lo world" when test.jsp is requested? | a. <jsp:include page="test2.jsp"/>
Which of the following is true about Data Integrity? | a. The information/data i
s not tampered with, in transit from host to client.
To be a servlet, a class should extend HttpServlet and override doGet or doPost,
depending on whether the data is being sent by GET or by POST. | a. True
Name the default value of the scope attribute of <jsp:useBean> | a. page
The properties that characterize transactions are known as ACID properties. | a.
True
A web application is located in "helloapp" directory. Which directory should it'
s deployment descriptor be in? | a. helloapp/WEB-INF
Which statement is correct about Message-Driven Beans exception handling? | a. M
essage-Driven Beans cannot send any exceptions back to clients
Which statement is correct about Bean-managed persistent (BMP)? | a. Bean-manage
d persistent persisted by the developer, who write the code for the database acc
ess calls
Regarding URL rewriting for session support, which of the following is true? | a
. Every URL that the client uses must include jsessionid.
Which syntax is correct for JSP Scriptlets? | a. <% code %>
What is output to the web page on the second access to the same instance of the
following JSP?<html><body><%! int x = 0; %><%= x++ %></body></html> | a. 0
Which of these is legal return type of the doStartTag method defined in a class
that extends TagSupport class? | a. EVAL_BODY
Select the correct JMS programming model. | a. Locate the JMS Driver->Create a J
MS connection->Create a JMS session->Locate the JMS destination->Create a JMS pr
oducer or a JMS consumer->Send or receive message.
___________________ includes a static file in a JSP file, parsing the file's JSP
elements | a. include directive
Which of the following JSP variable is not available within a JSP expression? Se
lect one correct answer | a. httpsession
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with the following parameter and a Location header in th
e URL. Select one correct answer. | a. SC_MOVED_TEMPORARILY
You do not want the user to see the data and the format being passed to your ser
ver when the user tries to submit the information for registering with your site
. Which HTTP method would you use? (Comment: You can set some hidden parameters
such as server location, in the page when the user loads it. Such parameters mea
n nothing to the user and are generally not displayed. However, determined users
can still view them using "View Source" for the page). | a. POST
Which is the BEST case use Container-managed persistent (CMP)? | a. When you req
uire some kind of special bean, like multi-tables, that cannot be completely rea
lized with a single bean
Which statement is correct about Message-Driven Beans?(Choose one) | a. Message-
Driven Beans stateless
Every method of the remote interface must throw a ___________________ | a. Remot
eException
The instantiation of a session bean is done by the ____________________ while th
e management of the lifetime of the bean is done by the ________________________
___. | a. Container/EJB server
Which of the following code snippet of HTML document are correct structured? | a
. <HTML><HEAD><TITLE>...</TITLE>...</HEAD><BODY ...>...</BODY></HTML>
______and _______methods do not apply to stateless session beans. | a. ejbActiva
te() b. ejbPassivate()
A JavaBeans component has the following field: private boolean enabled; Which pa
irs of method declarations follow the JavaBeans standard for accessing this fiel
d? | a. public void setEnabled( boolean enabled) public booleangetEnabled()
Which of the following is indicated by URL, which is used on the Internet? | a.
Information resources(sources) on the Internet
You want to use a bean that is stored in com/enthu/GUI.ser file. Which of follow
ing statements correctly defines the tag that accesses the bean? | a. <jsp:useBe
an id="pref" beanName="com.enthu.GUI" type="com.enthu.GUI"/>
A JSP page has the following page directives: <%@page isErrorPage='false' %> <%@
page errorPage='/jsp/myerror.jsp' %>Which of the following implicit object is NO
T available to the jsp page? | a. exception
A bean with a property color is loaded using the following statement<jsp:useBean
id="fruit" class="Fruit"/>Which of the following statements may be used to prin
t the value of color property of the bean?.Select the one correct answer. | a. <
jsp:getProperty name="fruit" property="color"/>
The ____________ interface is a Java interface that enumerates the business meth
ods exposes by the enterprise bean class. | a. remote
A ____________ is a group of operations, which appear as one large operation dur
ing execution. | a. Transaction
Select the BEST case to Use Entity Beans? (Choose one) | a. At any given time, o
nly one client has access to the bean instance.
Message-Driven Bean does not have a home interface, local home interface, remote
interface, or a local interface. | a. True
For what reason does the following JSP fail to translate and compile?<html><body
><%! int x; %><%=x ; %></body></html> | a. Error in JSP Expression.
Which of the following statement is true about the Entity class? | a. E xxxxx nt
ity class must be declared as top level class
A bean with a property color is loaded using the following statement <jsp:useBea
n id="fruit" class="Fruit"/> Which statement may be used to set the color proper
ty of the bean. | a. <jsp:setProperty name="fruit" property="color" value="white
"/>
Which of the following xml fragments correctly define a security constraint in w
eb.xml? (Choose one) | a. <security-constraint> <web-resource-collection><web-re
source-name>Info</web-resource-name><url-pattern>/info/*</url-pattern><http-meth
od>GET</http-method></web-resource-collection><auth-constraint><role-name>manage
r</role-name></auth-constraint></security-constraint>
A JSP expression is used to insert values directly into the output. | a. True
A JSP page will not have access to session implicit variable if: | a. the sessio
n attribute of page directive is set to false.
The ______________ is the container-generated implementation of the remote inter
face. | a. EJB Object
Which of the following is NOT a valid attribute for a useBean tag? | a. classNam
e
What gets printed when the following JSP code is invoked in a browser? Select on
e correct answer. <%= if(Math.random() < 0.5) %> hello<%= } else { %>hi<%= } %>
| a. The JSP file will not compile.
Is it possible to share aHttpSession object between a Java Server Page and Enter
prise Java Bean? | a. Yes, you can pass the HttpSession as parameter to an EJB m
ethod, only if all objects in session are serializable
Deployment properties are stored in a _______________________ file. | a. XML
Which is the correct sequence? | a. Jsp page is translated -->jsp page is compli
ed-->jspInit is called ->_jspService is called -->jspDestroy is called
The HttpServletRequest has methods by which you can find out about incoming info
rmation such as: | a. All of the others
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with d
ynamically generated content from servlets. You simply write the regular HTML in
the normal manner, using familiar Web-page-building tools. | a. True
Which of the following is INCORRECT statement about implicit objects and scope?
| a. application can't be used to access other web application resources
Which statements are BEST describe class attribute of <jsp:useBean class=../> Ac
tion? | a. The fully qualified class name of the Java object.
Which of the following XML fragments correctly specify the class name for a serv
let in a deployment descriptor of a webapp? | a. <servlet-class>com.abcinc.Order
Servlet</servlet-class>
Which of the following statements is correct? Select the one correct answer. | a
. The setStatus method defined in the HttpServletRequest class takes an int as a
n argument and sets the status of Http response
The session time-out value is controlled in which way(s)? | a. Individual Sessio
n Setting b. Application Server Global Default d. Web Application Default
Which statements are BEST describe page directive of JSP file? | a. Defines page
settings for the JSP container to process
Which of the following lines of code, in the doPost() method of a servlet, uses
the RL rewriting approach to maintaining sessions? (Choose one) | a. out.println
("<a href='"+response.encodeURL("/servlet/XServlet")+" '>Click here</a>"));
To be a servlet a class should extend HttpServlet and override doGet or doPost,
depending on whether the data is being sent by GET or by POST. | a. False
Your web application named "FWorks" uses SpecialMath.class. This is an unbundled
class and is not contained in any jar file. Where will you keep this class file
? | a. FWorks/WEB-INF/classes
A JSP page uses the java.util.ArrayList class many times. Instead of referring t
he class by its complete package name each time, we want to just use ArrayList.
Which attribute of page directive must be specified to achieve this? Select one
correct answer. | a. import <@page import="java.util.ArrayList"/>
Which of the following implicit variables should be used by a jsp page to access
a resource and to forward a request to another jsp page?(Choose one) | a. appli
cation for both
If an HTTP client rrequest is NOT authenticated, what is returned by request.get
UserPrincipal()? | a. A null
Host names are translated into IP addresses by web servers. | a. False
Which statements are BEST describe <jsp:getProperty> Action? | a. Gets property
in the specified JavaBean instance and converts the result to a string for outpu
t in the response.
The brower transmits the username and password to the server without any encrypt
ion in which of the following Authentication mechanism? (Choose one) | a. FORM b
ased Authentication
Your jsp page uses java.util.TreeMap.Adding which of the following statement wil
l ensure that this class is available to the paper?(Choose one) | a. <%@page imp
ort="java.util.TreeMAp"%>
Which statements are BEST describe uri attribute of <%@taglib uri=...%>directive
of JSP file? | a. Specifies the relative or absolute URI of the tag library des
criptor.
The two most common HTTP requests are get and put. | a. False
When the client calls a bean, it can in turn call another bean. Do you agree wit
h this statemnt? | a. Disagree
For JSP scopes of request and page, whate type of object is used to store the at
tribute? | a. HttpServletRequest and PageContext respectively.
The specifications set by EJB need NOT match with those of the component interfa
ce. | a. False
Which is NOT a core component of JSP? | a. scriptlets
Each page has its own instances of the page-spoce implicit objects. | a. True
Host names are translated into IP addresses y web servers. | a. True
Which syntax is correct for JSP Expressions? | a. <%=expression%>
The two most common HTTP requests are get and put. | a. True
Identify the technique that can be used to implement'sessions' if the client bro
wser does not support cookies.(Choose one)| a. URL rewriting
Which of the following is true statement about the JavaServer Page life cycle? (
Choose one) | a. The_jspService() method is called from the generated servlet's
service() method.
Which is NOT the top value of EJB? | a. Easy to upgrade.
The page directive is used convey information about the page to JSP container. w
hich statement is legal page directive. Select one correct statement | a. <%@pag
e info="test page" session="false"%>
The method getWriter returns an object of type PrintWriter. This class has print
ln methods to generate output. Which of these classes define the getWeriter meth
od? Select one correct answer. | a. ServletContext
The method getWriter returns an object type PrintWriter. this class has println
methods to generate output. Which of these classes define the getWriter method?
Select one correct answer. | a. ServletContext
You need to modify deployment descriptor for a web application insalled in MyWeb
App directory. Which file would you look for? | a. web.xml in MyWebApp/WEB-INF
Which JSP directive declares the usage of a tag library in a JSP page? | a. tagl
ib
In which of the following cases will the method doEndTag() of a tag handler be i
nvoked? | a. It will be invoked only if doStartTag() or doAfterBody() return Tag
.DO_END_TAG.
Which is NOT a basic messaging model in message dreiven bean? | a. Place-to-plac
e
Which security mechanism proves that data has not been tampered with during its
transit through the nerwork? | a. Data integrity
What is the implication of using the HTTP GET method for a form submission?(Choo
se one) | a. The parameters will be appended to the URL as a query string.
Session bean implements ___ interface. | a. javax.ejb.SessionBean
Suppose in a garment shop, a request is made for all the colors available in a p
articular garment along with the all the sizes and their respective prices, then
which session bean will be used thandle such processes? | a. Stateful session b
ean
Which of the following file is the correct name and location of deployment descr
iptor of a web application? Assume that the web application is rooted at\doc-roo
t. Select one correct answer | a. \doc-root\WEB-INF\web.xml
Action <jsp:include> is evaluated once at page translation time. | a. False
Which method would you use to put the sesison id the URL to support sessions usi
ng URL rewriting? | a. encodeURL() of HttpServletResponse
Servlets usually are used on the client side of a networking application. | a. F
alse
Which is true about RMI? | a. RMI allows objects to be send from one computer to
another
Which component can use a container-managed entity manager with an extended pers
istent context? | a. Only stateful session beans
Which is NOT responsibility of the business tier in a multitier web-based applic
ation with web, business, and EIS tiers? | a. To integrate with the legacy appli
cations
The JavaPersistent API defines the Query interface. Which statement is true abou
t the Query.executeUpdate method? | a. It must always be executed within a trans
action
A developer wants to use the Java Persistence query language. Which statement is
true? | a. The WHERE clause is used to determine the types of objects to be ret
rieved from persistent store
A stateful session bean must commit a transaction before a business method | a.
False
A developer wants to create a Java Persistence query that returns valid US phone
numbers (formatted as 123-456-7890) from a collection of defferently formatted
international phone numners. The developer needs only those numbers that begin w
ith 303. Which WHERE clause is correct? | a. WHERE addr.phone LIKE '303-___-____
'
Which statement is NOT true about JMS? | a. JMS support both synchronous and asy
nchronous message passing
Which Java technology provides a unified interface to multiple naming and direct
ory services? | a. EJB
What is the purpose of JNDI? | a. To access various direcoty services using a si
ngle interface
Which is NOT provided by the EJB tier in a multitier JEE (J2EE) application? | a
. XML Parsing
Which is true about the relationship "A keyboard has 101 keys"? | a. This is a o
ne-to-may relationship
Which statement describe about Message-Driven Beans is correct? (Choose one) | a
. The bean mediates between the client and the other components of the applicati
on, presenting a simplified view to the client.
Which statement is correct about the Java Persistence API support for the SQL qu
eries? | a. SQL queries are expected to be portable across database
Which statement is true about the EJB 3.0 stateful session beans? | a. Its conve
rsational state is retained acroess method invocations and transactions
A developer must implement a "shopping cart" object for a web-based application.
The shopping cart must be able to maintain the state of the cart, but the state
is not stored persistently. Which JEE (J2EE) technology is suited to this goal?
| a. Stateful session beans
Which type of JEE (or J2EE) component is used to store business data persistentl
y? | a. Entity Bean
Which statement is correct about Java EE client of a message-driven beans? | a.
The client can use JNDI to obtain a reference to a message-driven bean instance
Which technology is used for processing HTTP requests and mapping those requests
to business objects | a. Servlets
A Java programmer wants to develop a browser-based multitier application for a l
arge bank. Which Java edition (or editions) should be used to develop this syste
m? | a. J2SE and J2EE
Cookies never expire | a. False
Which statements are BEST describe <jsp:useBean> Action? | a. Specifies that the
JSP uses a JavaBean instance. This action specifies the scope of the bean and a
ssigns it an ID that scripting components can use to manipulate the bean.
Servlet methods are executed automatically. | a. True
Which of the following method calls can be used to retrieve an object from the s
ession that was stored using the name "userid"? | a. getAttribute("userid");
Given that a servlet has been mapped to /account/*. Identity the HttpServletRequ
est methods that will return the /* segement for the URL:/myapp.account/*. | a.
getPathInfo
When a Web server responds to a request from a browser or other Web client, the
response typically consists of: (Choose one) | a. a status line, some reposne he
aders, and the document.
Which of the following statemtn is a correct JSP directive?(Choose one) | a. <%@
tabliburi="http://www.abc.com/tags/util" prefix="util"%>
Which statements are BEST describe id attribute of <jsp:useBean id=.../> Action?
| a. The name used to manipulate the Java object with actions <jsp:setProperty>
and <jsp:getProperty>. A variable of this name is also declared for use in JSP
scripting elements. The name specified here is case sensitive.
JSP ___ let you insert arbitrary code into the servlet's _jspService method (whi
ch is called by service). | a. scriptlets
A web application named webmail has a file named folderview.jsp which the user s
hould be able access directly. Which of the following directory may contain this
file?(Choose one) | a. /webmail/jsp
Identify correct statement about a WAR file.(Choose one) | a. It is used by web
application developer to deliver the web application in a single unit.
Computers that run ____ software make resources available, such as web pages, im
ages, PDF documents and even objects that perform complex task. | a. Web server
Which of these is legal attribute of page directive? | a. errorPage
Which of the following is NOT a technique used for maintaining sessions? | a. se
sison.invalidate();
A JSP page needs to generate an XML file. Which attribute of page directive may
be used to specify that the JSP page is generating an XML file? | a. <%@page con
tentType ="text/xml">
The <servlet-mapping> element (in web.xml) provides a means of defining URLs to
use the servlet resours. | a. True
Which statements are BEST describe contentType attribute of <%@page contentType=
...%> directive? | a. Specifies the MIME type of the data in the response to the
client. The default type is text/htmt.
A message-driven bean must commit a transaction before a business method | a. Tr
ue
Which Java technology provides a unified interface to multiple naming and direct
ory services? | a. JNDI
Which Java technology provides a standard API for publish-subcribe messaging mod
el? | a. JMS
Which is disadvantage of using JEE ( or J2EE) server-side technologies in a web-
based application? | a. Complexity
What is the purpose of JNDI? | a. To access various directory services using a s
ingle interface
Which is NOT associatied with the business tier in a JEE (J2EE) web-based applic
ation? | a. JSP
Which is NOT true about stateless session beans? | a. They are used to represent
data stored in a RDBMS
HttpSession objects have a built-in data structure that lets you strore any numb
er of keys and associated values. | a. True
The HttpServletRequest has methods by which you can find out aout imcoming infor
mation such as: (choose one) | a. All the above
If you want the same servlet to handle both GET and POST and to take the same ac
tion for each, you can simply have doGet call doPost, or vice versa. | a. True
To send text output a response, the following method of HttpServlet Reponse may
be used to get the appropriate Writer/Stream object. Select the one correct answ
er. | a. getWriter
Session will automatically become inactive when the amount of time between clien
t accesses exceeds the interval specified by getMaxInactiveInterval. | a. True
HttpSession objects have a built-in data structure that lets you store any numbe
r of keys and associated values. | a. True
The HttpServletRequest has methods by which you can find about incoming informat
ion such as: (choose one) | a. All the above
Sessions will automatically become inactive when the amount of time between clie
nt accesses exceeds the interval specified by getMaxInactiveInterval. | a. True
Servlets are programs that run on a Web servlet, acting as a middle layer betwee
n a request coming from a Web browser or other HTTP client and databases or appl
ications on the HTTP server. | a. True
We can look up the HttpSession object by calling the getSession method of HttpSe
rvletResponse | a. True
What is the likely effect of calling a servlet with the POST HTTP method if that
servlet does not have a doPost() method? (Choose one.) | a. 405 response code:
SC_METHOD_NOT_ALLOWED.
The same servlet class can be declared using different logical names in the depl
oyment descriptor. | a. True
___ provides a way to indentify a user across more than one page request or visi
t to a Web site and to store information about that user. | a. Cookie
The same servlet class can be declared using different logical in the deployment
descriptor. | a. True
Session death is more likely to come about through a time-out mechanism. If ther
e is no activity on a session for a predefined length of time, the web container
invalidates the session. | a. True
When you obtain a session (using HttpServletRequest.getSession()), the web conta
iner manufactures a unique ID string for the session. This is passed as a token
between the client and server. | a. True
Session death can come about through an explicit call (in servlet code) to HttpS
ession.invalidate(); | a. True
How many session (HttpServletRequest) time out mechanisms? | a. 3
Session death is more likely to come about through a time-out mechanism. If thes
e is no activity on a session for a predefined length of time, the web container
invalidates the session. | a. True
Which security mechanism limits access to the availability of resources to pemit
ted groups of users or programs?(Choose one.) | a. Authorization
Which security mechanism proves that data has not been tampered with during its
transit through the network?(Choose one.) | a. Data intergrity
Which of these are true. Select the two correct answer. | a. The default value o
f is ThreadSafe attribute of page directive is true b. When is ThreadSafe attrib
ute of page directive is set to true, a thread is created for each request for t
he page
Which of the following techniques is likely to return an initalization parameter
for a JSP page? (Choose two.) | a. <%String s = getInitParameter("myPam");%> b.
<% config.getInitParameter("myPam")%>
___ send a request to an object and includes the result in a JSP file. | a. <jsp
:include>
Which security mechanism limits access to the availability of resources to permi
tted groups of users or programs? (Choose one.) | a. Authorization
Session death can come about through an explicit call(in servlet) to http sessio
n invalidate() | True
You can set a page to be an error page either through web.xml or by adding a pag
e directive_____ | a. <%@page isErrorPage="errorPage.jsp" %>
Given that a servlet has been mapped to /account/*. Identity the HttpServletRequ
est methods that will return the /account segement for the URI: /myapp/account/*
. | c. getPathInfo
Which of the following code snippet of HTML document are correct structured? | a
. <HTML><HEAD><TITLE>...</TITLE>...</HEAD><BODY ...>...</BODY></HTML>
Which of the following XML fragments correctly specify the name used for a servl
et class in the deployment descriptor of a web application?The outermost tag's n
ame containing servlet properties itself is the name of the servlet. | a. <servl
et-name>OrderServlet</servlet-name>
Servlet Container calls the init method on a servlet instance ____ | a. Only on
ce in the life time of the servlet instance.
The path in a URL typically specifies a resource s exact location on the server. | a
. True
Which of these is a correct fragment within the web-app element of deployment de
scriptor? Select one correct answer. | a. <error-page> <error-code>404</error-co
de> <location>/error.jsp</location> </error-page>
Which of the following classes define the methods setStatus(...) and sendError(.
..) used to send an
HTTP error back to the browser? (Choose one) | c. Both are defined in HttpServle
tResponse.
The <servlet> element holds declarative information about a servlet. It has only
two mandatory subelements <servlet-name>, a logical name for the servlet, and <serv
let-class>, the fully qualified Java class name without the .class extension. |
a. True
What would be the best directory in which to store a supporting JAR file for a w
eb application? Note that in the list below, all directories begin from the cont
ext root | d. \WEB-INF\lib
Consider the code shown in the exhibit for the init() method of a HTTP servlet.W
hich of the following LOC "may" correctly retrieve the DBURL parameter at //1?(A
ssume that servletcontext is a reference to ServletContext for this servlet.)(Ch
oose one)public void init(){Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");// 1 G
et DBURL heretheConnection = DriverManager.getConnection(dbUrl, "admin", "admin"
);} | a. this.getInitParameter("DBURL");
Your web application named "FWorks" uses SpecialMath.class. This is an unbundled
class and is not contained in any jar file. | a. FWorks/WEB-INF/classes
Identify the technique that can be used to implement 'sessions' if the client br
owser does not support cookies.(Choose one) | a. Hidden form fields.
How can you ensure the continuity of the session while using HttpServletResponse
.sendRedirect() method when cookies are not supported by the client? | b. By enc
onding the redirect path with HttpServletResponse.encodeRedirectURL() method.
For application and session JSP scopes, what class of object is used to store th
e attributes?(Choose one) | d. HttpSession and ServletContext respectively
Your web application logs a user in when she supplies username/password. At that
time a session is created for the user. Your want to let the user to be logged
in only for 20 minutes. The application should redirect the user to the login pa
ge upon any request after 20 minutes of activity. Which of the following HttpSes
sion methods would be helpful to you for implementing this functionality? | b. g
etLastAccessTime()
Which of the following is NOT a technique used for maintaining sessions? | c. se
ssion.invalidate();
The web.xml file for a webapp contains the follwing XML fragment for configuring
session timeout.<session-config><session-timeout>300</session-timeout></session
-config>What would be the session timeout interval for the sessions created in t
his web application? | a. 300 minutes
When you obtain a session (using getSession() of HttpServletRequest object), the
web container manufactures a unique ID string for the session. This is passed a
s a token between the client and server. | a. True
Each page has its own instances of the page-scope implicit objects. | a. True
Your jsp page uses java.util.TreeMap. Adding which of the following statement wi
ll ensure that this class is available to the page? (Choose one) | a. <%@ page i
mport="java.util.TreeMap"%>
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/test.jsp? name="John". The test.jsp contains the following code.<%! Stri
ng myName=request.getParameter();%><% String test= "welcome" + myName; %><%= tes
t%> | b. The program gives a syntax error because of the statement <%! String my
Name=request.getParameter();%>
Which technique is likely to return an initialization parameter for a JSP page?
| b. <% String s = getInitParameter("myParm"); %>
You can set a page to be an error page either through web.xml or by adding a pag
e directive_____ | a. <%@page isErrorPage="true" %>
Which of the given jsp statement is equivalent to<%= userbean.getAge() %> ?Assum
e that userbean.getAge() returns an integer. (Choose one) | d. <jsp:getProperty
name="userbean" method="getAge"/>
A programmer is designing a class to encapsulate the information about an invent
ory item. A JavaBeans component is needed to do this. The Inventoryltem class ha
s private instance variables to store the item information:10. private int itemI
d;11. private String name;12. private String description;Which method signature
follows the JavaBeans naming standards for modifying the itemld instance variabl
e? | c. setItemId(int itemId)
Which of the following represents a correct syntax for using a Javabean? | c. <j
sp:useBean id="fruit" class="Fruit" beanName="Fruit"/>
Which security mechanism limits access to the availability of resources to permi
tted groups of users or programs? | a. Authorization
Which of the following XML fragments correctly defines a role named "manager" in
web.xml? | d. <security-role><role-name>manager</role-name></security-role>
A custom tag can be nested inside another custom tag. | a. true
Identify the correct element is required for a valid <taglib> tag in web.xml (Ch
oose one) | e. <taglib-uri>
What should be the value of <body-content> subelement of element <tag> in a TLD
file if the tag should not have any contents as its body? | b. empty
A tag library defines a set of elements that can be inserted into the JSP file.
| a. True
Which statement is true about EJB 3.0 containers? | a. javax.naming.initialConte
xt is guaranteed to provide a JNDI name space
A developer must implement a oeshopping cart object for a web-based application. The
shopping cart must be able to maintain the state of the cart, but the state is
not stored persistently. Which JEE (J2EE) technology is suited to this goal? | c
. Stateful session beans
Which is true about JEE ( or J2EE)? | c. JEE includes servlet APIs and EJB APIs
Which Java technology provides a standard API for publish-subscribe messaging mo
del? | b. JMS
Which is true about JDBC? | b. The JDBC API is included in J2SE
Which statement is true about both stateful and stateless session beans about be
an instances? | a. Bean instances are NOT require to survive container crashes c
. A bean with bean-managed transactions must commit or rollback any transaction
before returning from a business method
A Java developer needs to be able to send email, containing XML attachments, usi
ng SMTP. Which JEE (J2EE) technology provides this capability? | d. JavaMail
Which of the following statement is true about the Entity class? | b. Entity cla
ss must be declared as top level class
Which of the following lines of code are correct? (Choose one) | a. @Entitypubli
c class Company{...}public class Employee extends Company{...} b. @Entitypublic
class Company{...}@Entitypublic class Employee extends Company{...} c. public cl
ass Company{...}@Entitypublic class Employee extends Company{...}
Which three about JMS are true? (Choose three.) | a. JMS supports an event-orien
ted approach to message reception. b. JMS supports both synchronous and asynchro
nous message passing. c. JMS provides a common way for Java programs to access a
n enterprise messaging system's messages.
Which statement is true? | a. JMS enables an application to provide flexible, as
ynchronous data exchange.
A Java programmer wants to develop a small application to run on mobile phones.
Which Java edition (or editions) are required to develop the application? | a. J
2SE and J2ME
Which is true? | a. The JDBC API is included in J2SE.
Which two are true? (Choose two.) | a. J2EE application developers need J2SE. b.
J2EE includes servlet APIs and EJB APIs.
Which is true? | a. Threading allows GUI applications to perform lengthy calcula
tions and respond to user events at the same time.
Which two are characteristics of an RDBMS? (Choose two.) | a. An RDBMS represent
s data using two-dimensional tables. b. Java technologies provide capabilities f
or connecting a legacy RDBMS to a web application.
Which is true about RMI? | a. RMI allows objects to be sent from one computer to
another.
Which statement about threading in Java is false? | a. A thread is a special typ
e of method.
What is the definition of the acronym SQL? | a. Structured Query Language
Which two are true? (Choose two.) | a. SQL commands can be written in applicatio
ns that use NO Java technologies b. SQL allows you to modify multiple rows in a
table with a single command.
Which two are valid representations of operations in UML? (Choose two.) | a. - o
p(p : P) : P b. + op(param : int) : int
What gets printed when the following expression is evaluated? Select the one cor
rect answer. ${(1==2) ? 4 : 5} | a. 1
What gets printed when the following expression is evaluated? Select the one cor
rect answer.${4 div 5} | b. 0.8
How many numbers gets printed when the following JSTL code fragment is executed?
Select the one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core
" prefix="c" %><c:set var="item" value="2"/><c:choose><c:when test="${item>0}"><
c:out value="1"/></c:when><c:when test="${item==2}"><c:out value="2"/></c:when><
c:when test="${item<2}"><c:out value="3"/></c:when><c:otherwise><c:out value="4"
/></c:otherwise></c:choose> | b. One number gets printed.
Which numbers gets printed when the following JSTL code fragment is executed? Se
lect the two correct answers.<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %><c:set var="j" value="4,3,2,1"/><c:forEach items="${j}" var="item"
begin="1" end="2" varStatus="status"><c:out value="${status.count}" default="abc
"/></c:forEach> | b. 2 c. 3
Which number gets printed when the following JSTL code fragment is executed? Sel
ect the one correct answers.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" p
refix="c" %><c:set var="j" value="4,3,2,1"/><c:forEach items="${j}" var="item" v
arStatus="status"><c:if test="${status.first}"><c:out value="${status.index}" de
fault="abc"/></c:if></c:forEach> | a. 1
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/test.jsp? nam<%! String myName=request.getParameter();%><% String test=
"welcome" + myName; %><%= test%>e="John". The test.jsp contains the following co
de. | b. The program gives a syntax error because of the statement <%! String my
Name=request.getParameter();%>
Which of the following correctly represents the following JSP statement. Select
the one correct answer.<%x=1;%> | e. <jsp:scriptlet>x=1;</jsp:scriptlet>
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with the following parameter and a Location header in th
e URL. Select the one correct answer. | b. SC_MOVED_TEMPORARILY
When implementing a tag, if the tag just includes the body verbatim, or if it do
es not include the body, then the tag handler class must extend the BodyTagSuppo
rt class. | b. False
A tag handler class must implement the javax.servlet.jsp.tagext.Tag interface. T
his is accomplished by extending the class TagSupport or another class named in
one of the options below. Select the one correct answer. | d. BodyTagSupport
A JSP file that uses a tag library must declare the tag library first. The tag l
ibrary is defined using the taglib directive - <%= taglib uri="..." prefix="..."
%> Which of the following specifies the correct purpose of prefix attribute. Sel
ect the one correct answer. | d. The prefix attribute is used in front of a tagn
ame of a tag defined within the tag library.
Which of the elements defined within the taglib element of taglib descriptor fil
e are required. Select the two correct answers. | a. name d. tag-class
Consider the following HTML code. Which method of MyFirstServlet will be invoked
when you click on the url shown by the page? | a. doGet
HTTP is a "stateless" protocol: each time a client retrieves a Web page, it open
s a separate connection to the Web server, and the server does not automatically
maintain contextual information about a client. | a. True
Which interface can you use to retrieve a resource that belongs to the current w
eb application? | a. ServletContext
Which interface you CANNOT use to obtain a RequestDispatcher Object? | a. Servle
tContext
Study the statements:1) The context path contains a special directory called WEB
-INF, which contains the deployment descriptor file, web.xml.2) A client applica
tion may directly access resources in WEB-INF or its subdirectories through HTTP
. | a. Only statement 1 is true
Which directory is legal location for the deployment descriptor file? Note that
all paths are shown as from the root of the web application directory. | b. \WEB
-INF
Which of the following statement correctly store an object associated with a nam
e at a place where all the servlets/jsps of the same webapp participating in a s
ession can access it? Assume that request, response, name, value etc. are refere
nces to objects of appropriate types.(Choose one) | a. request.getSession().setA
ttribute(name, value);
Which of the following lines of code, in the doPost() method of a servlet, uses
the URL rewriting approach to maintaining sessions? (Choose one) | a. out.printl
n("<a href=' "+response.encodeURL("/servlet/XServlet")+" '>Click here</a>"));
Which of the following statements is true? (Choose one) | a. Session data is sha
red across multiple webapps in the same webserver/servlet container.
What is the result of attempting to access the following JSP page?<html><body><%
! public String methodA() {return methodB();}%><%! public String methodB() {retu
rn "JAD Final Test";}%><h2><%= methodA() %></h2></body></html> | a. "JAD Final T
est" is output to the resulting web page.
What is the consequence of attempting to access the following JSP page?<html><bo
dy><%!public void _jspService(HttpServletRequest request, HttpServletResponse re
sponse){out.write("A");}%><% out.write("B"); %></body></html> | a. Duplicate met
hod compilation error.
Which of the following are correct JSP expressions | a. <%= new Date() %>
Objects with application scope are part of a particular Web application. | a. Tr
ue
Which of the following is a correct JSP declaration for a variable of class java
.util.Date? | a. <%! Date d = new Date(); %>
Which of the following task may happen in the translation phase of JSP page? (Ch
oose one) | a. Creation of the servlet class corresponding to the JSP file.
Select the correct directive statement insert into the first line of following l
ines of code (1 insert code here): | a. <%@page import='java.util.*' %>
The following statement is true or false? oeIf the isThreadSafe attribute of the pa
ge directive is true, then the generated servlet implements the SingleThreadMode
l interface. | a. True
Which of the following statement is a correct JSP directive?(Choose one) | a. <%
@ tagliburi="http://www.abc.com/tags/util" prefix="util" %>
Which is NOT a scope of implicit objects of JSP file? | a. application
Which statements are BEST describe <jsp:getProperty> Action? | c. Sets a propert
y in the specified JavaBean instance. A special feature of this action is automa
tic matching of request parameters to bean properties of the same name.
A bean present in the page and identified as 'mybean' has a property named 'name
'. Which of the following is a correct way to print the value of this property?
| a. <jsp:getProperty name="mybean" property="name"/>
Which statements are BEST describe errorPage attribute of <%@ page errorPage= .%> di
rective? | a. Any exceptions in the current page that are not caught are sent to
the error page for processing. The error page implicit object exception referen
ces the original exception.
Which statements are BEST describe property attribute of <jsp:setProperty proper
ty= . /> Action? | a. The ID of the JavaBean for which a property (or properties) wi
ll be set.
Which of the following xml fragments correctly define a security constraint in w
eb.xml? (Choose one) | a. <security-constraint><web-resource-collection><web-res
ource-name>Info</web-resource-name><url-pattern>/info/*</url-pattern><http-metho
d>GET</http-method></web-resource-collection> <user-data-constraint><transport-g
uarantee>CONFIDENTIAL</transport-guarantee></user-dataconstraint></security-cons
traint>
You need to make sure that the response stream of your web application is secure
. Which factor will you look at? (Choose one) | c. data integrity
Which of the following element are required for a valid <taglib> tag in web.xml?
(Choose one) | a. <taglib_uri>
Which of the following deployment descriptor snippets would you use to declare t
he use of a tag library? | c. <taglib><taglib-uri>http://abc.net/ourlib.tld</tag
lib-uri><taglib-location>/WEBINF/ ourlib.tld</taglib-location></taglib>
Which of the following elements defines the properties of an attribute that a ta
g needs? | a. attribute
Which statements are BEST describe prefix attribute of <%@ taglib prefix= %>directiv
e of JSP file? | a. Specifies the relative or absolute URI of the tag library de
scriptor.
Which element defined within the taglib element of taglib descriptor file is req
uired? Select one correct answer. | a. Tag
Which is NOT associated with the business tier in a JEE (J2EE) web-based applica
tion? | a. JSP
Which is NOT Enterprise Beans? | a. Business Beans
A developer is working on a project that includes both EJB 2.1 and EJB 3.0 sessi
on beans. A lot of business logic has been implemented and tested in these EJB 2
.1 session beans. Some EJB 3.0 session beans need to access this business logic.
Which design approach can achieve this requirement? | a. Add adapted home inter
faces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interop
erable.
Which statement is true about EJB 3.0 stateful session beans and stateless sessi
on beans? | a. Both can have multiple remote and local business interfaces
If you want to send an entity object as the pass by value through a remote inter
face, which of the following statements are valid? (Choose one) | b. @Entitypubl
ic class Employees implements Serializable{...}
Which statement about entity manager is true? | a. A container-managed entity ma
nager must be a JTA entity manager.
Can we use the annotation @PrePassivate for more than one method in a Entity bea
n? | b. No
Which is NOT a correct statement about entity beans? | c. They are used to imple
ment business processes
Which statement about an entity instance lifecycle is correct? | d. A managed en
tity instance is the instance associated with a persistence context.
Which is a valid PostConstruct method in a message-driven bean class? | c. @Post
Constructprivate void init() {}
Which statement describe about JMS is NOT true? | c. JMS use JNDI to locate the
destination
Consider the following HTML code. Which method of MyFirstServlet will be invoked
when you click on the url shown by the page? | a. doGet
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with the following parameter and a Location header in th
e URL. Select one correct answer. | b. SC_MOVED_TEMPORARILY
HTTP is a "stateless" protocol: each time a client retrieves a Web page, it open
s a separate connection to the Web server, and the server does not automatically
maintain contextual information about a client. | a. True
Servlet methods are executed automatically. | a. True
HttpSession objects have a built-in data structure that lets you store any numbe
r of keys and associated values. | a. True
Which interface can you use to retrieve a resource that belongs to the current w
eb application? | a. ServletContext
Which interface you CANNOT use to obtain a RequestDispatcher Object? | a. Servle
tContext
Study the statements: <question>1) The context path contains a special directory
called WEB-INF, which contains the deployment descriptor file, web.xml. <questi
on>2) A client application may directly access resources in WEB-INF or its subdi
rectories through HTTP. | a. Only statement 1 is true
Which directory is legal location for the deployment descriptor file? Note that
all paths are shown as from the root of the web application directory. | b. \WEB
-INF
A .. manages the threading for the servlets and JSPs and provides the nec
Web server. | a. Web Container
Which of the following statement correctly store an object associated with a nam
e at a place where all the servlets/jsps of the same webapp participating in a s
ession can access it? Assume that request, response, name, value etc. are refere
nces to objects of appropriate types.(Choose one) | a. request.getSession().setA
ttribute(name, value);
Which of the following lines of code, in the doPost() method of a servlet, uses
the URL rewriting approach to maintaining sessions? (Choose one) | a. out.printl
n("<a href=' "+response.encodeURL("/servlet/XServlet")+" '>Click here</a>"));
Which of the following statements is true? (Choose one) | a. Session data is sha
red across multiple webapps in the same webserver/servlet container.
Which of these is legal attribute of page directive?. | c. errorPage
What is the result of attempting to access the following JSP page?<question><htm
l><question><body><question><%! public String methodA() {<question> return metho
dB();<question>}<question>%><question><%! public String methodB() {<question> re
turn "JAD Final Test";<question>}<question>%><question><h2><%= methodA() %></h2>
<question></body><question></html> | a. "JAD Final Test" is output to the result
ing web page.
What is the consequence of attempting to access the following JSP page?<question
><html><question><body><question><%!<question> public void _jspService(HttpServl
etRequest request, HttpServletResponse response) {<question> out.write("A");<que
stion> }<question> %><question><% out.write("B"); %><question></body><question><
/html> | a. Duplicate method compilation error.
Which of the following are correct JSP expressions | a. <%= new Date() %>
Objects with application scope are part of a particular Web application. | a. Tr
ue
Which of the following is a correct JSP declaration for a variable of class java
.util.Date? | a. <%! Date d = new Date(); %>
Which of the following task may happen in the translation phase of JSP page? (Ch
oose one) | a. Creation of the servlet class corresponding to the JSP file.
Select the correct directive statement insert into the first line of following l
ines of code (1 insert code here): | a. <%@page import='java.util.*' %>
The following statement is true or false? <question> oeIf the isThreadSafe attribut
e of the page directive is true, then the generated servlet implements the Singl
eThreadModel interface. | a. True
Which of the following statement is a correct JSP directive?(Choose one) | a. <%
@ tagliburi="http://www.abc.com/tags/util" prefix="util" %>
Which is NOT a scope of implicit objects of JSP file? | a. application
Which statements are BEST describe <jsp:getProperty> Action? | c. Sets a propert
y in the specified JavaBean instance. A special feature of this action is automa
tic matching of request parameters to bean properties of the same name.
A bean present in the page and identified as 'mybean' has a property named 'name
'. Which of the following is a correct way to print the value of this property?
| a. <jsp:getProperty name="mybean" property="name"/>
Which statements are BEST describe errorPage attribute of <%@ page errorPage= .%> di
rective? | a. Any exceptions in the current page that are not caught are sent to
the error page for processing. The error page implicit object exception referen
ces the original exception.
Which statements are BEST describe property attribute of <jsp:setProperty proper
ty= . /> Action? | a. The ID of the JavaBean for which a property (or properties) wi
ll be set.
Which of the following xml fragments correctly define a security constraint in w
eb.xml? (Choose one) | a. <security-constraint>a. <web-resource-collection>a. <
web-resource-name>Info</web-resource-name>a. <url-pattern>/info/*</url-pattern>a
. <http-method>GET</http-method>a. </web-resource-collection>a. <user-data-const
raint>a. <transport-guarantee>CONFIDENTIAL</transport-guarantee>a. </user-data-c
onstraint>a. </security-constraint>
You need to make sure that the response stream of your web application is secure
. Which factor will you look at? (Choose one) | c. data integrity
Which of the following element are required for a valid <taglib> tag in web.xml?
(Choose one) | a. <taglib_uri>
Which of the following deployment descriptor snippets would you use to declare t
he use of a tag library? | c. <taglib> c. <taglib-uri>http://abc.net/ourlib.tld<
/taglib-uri>c. <taglib-location>/WEB-INF/ourlib.tld</taglib-location>c. </taglib
>
Which of the following elements defines the properties of an attribute that a ta
g needs? | a. attribute
Which statements are BEST describe prefix attribute of <%@ taglib prefix= %>directiv
e of JSP file? | a. Specifies the relative or absolute URI of the tag library de
scriptor.
Which element defined within the taglib element of taglib descriptor file is req
uired? Select one correct answer. | a. Tag
Which is NOT associated with the business tier in a JEE (J2EE) web-based applica
tion? | a. JSP
Which statement is true about EJB 3.0 containers? | a. javax.naming.initialConte
xt is guaranteed to provide a JNDI name space
A Java developer needs to be able to send email, containing XML attachments, usi
ng SMTP. Which JEE (J2EE) technology provides this capability? | d. JavaMail
Which is NOT Enterprise Beans? | a. Business Beans
A developer is working on a project that includes both EJB 2.1 and EJB 3.0 sessi
on beans. A lot of business logic has been implemented and tested in these EJB 2
.1 session beans. Some EJB 3.0 session beans need to access this business logic.
Which design approach can achieve this requirement? | a. Add adapted home inter
faces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interop
erable.
Which statement is true about EJB 3.0 stateful session beans and stateless sessi
on beans? | a. Both can have multiple remote and local business interfaces
Which is NOT true about stateless session beans? | c. They are used to represent
data stored in a RDBMS
If you want to send an entity object as the pass by value through a remote inter
face, which of the following statements are valid? (Choose one) | b. @Entity b.
public class Employees implements Serializable{b. ...b. }
Which statement about entity manager is true? | a. A container-managed entity ma
nager must be a JTA entity manager.
Can we use the annotation @PrePassivate for more than one method in a Entity bea
n? | b. No
Which is NOT a correct statement about entity beans? | c. They are used to imple
ment business processes
Which statement about an entity instance lifecycle is correct? | d. A managed en
tity instance is the instance associated with a persistence context.
Which is a valid PostConstruct method in a message-driven bean class? | c. @Post
Construct c. private void init() {}
Which statement describe about Message-Driven Beans is correct? (Choose one) | a
. Message-Driven Beans are stateful
Which statement describe about JMS is NOT true? | c. JMS use JNDI to locate the
destination
Which of the following are valid iteration mechanisms in jsp? | <% int i = 0; f
or(;i<5; i++) { %> "Hello World"; <% i++; } %>
Which of the following methods will be invoked if the doStartTag() method of a t
ag returns Tag.SKIP_BODY? | doEndTag()
Select the BEST case to use message-driven bean?(Choose one) | Need to avoid tyi
ng up server resources andneed the applications to process messages asynchronous
ly
Which is NOT the role of EJB Deployer? | Write the code that calls on components
supplied by bean providers
Which of the following method can be used to add cookies to a servlet response?
| HttpServletResponse.addCookie(Cookie cookie)
What is output to the web page on the second access to the same instance of the
following JSP? <html><body><% int x = 0; %><%= x++ %></body> </html> | 0
In EJB 2.0, ejb-jar.xml deployment descriptor file must be placed in ___________
folder. | META-INF
The page directive is used to convey information about the page to JSP container
. Which statement is legal page directive. Select one correct statement | <%@ pa
ge info="test page" session="false"%>
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/Final/test.jsp?name=John. The test.jsp contains the following code.<% St
ring myName=request.getParameter("name");%><% String test= "Welcome " + myName;
%><%=test%>What
| The page displayis the
"Welcome
output?John"
What will happen when a servlet makes the following call within its doGet() meth
od? getServletContext().setAttribute("userid", userid); | The userid attribute i
s placed in application scope.
Which of the following is true statement about the JavaServer Page life cycle?(C
hoose one) | The _jspService() method is called from the generated servlet s servi
ce() method
Which is NOT the main type of JSP constructs that you embed in a page? | actions
Which
| Allstatement(s)
the others about Servlet Life Cycle is(are) correct? (Choose one)
_______________ sends a request to an object and includes the result in a JSP fi
le | <jsp:include>Which syntax is correct for JSP Declarations? | <%! code %>
Which statement is correct about Container-managed persistent (CMP)? | Container
-managed persistent persisted by the Enterprise Java Beans container
Your jsp page uses classes from java.util package. Which of the following statem
ent would allow you to import the package? (Choose one) | <%@ page import="java.
util.*"%>
Which of the following is a valid standard action that can be used by a jsp page
|to<jsp:include
import content
page='another.jsp'/>
generated by another JSP file named another.jsp?
Which class that includes the getSession method that is used to get the HttpSess
ion object? | HttpServletRequest
Which of the following statement correctly store an object associated with a nam
e at a place where all the servlets/jsps of the same webapp participating in a s
ession can access it? Assume that request, response, name, value etc. are refere
nces to objects of appropriate types.(Choose one) | request.getSession().setAttr
ibute(name, value);
If a ______________is being used then all the operations need to be written by t
he| Bean-Managed
developer to persistent
a persistententity
API. bean
Which is the CORRECT statement? | Entity beans represent persistent state object
s (things that don t go away when the user goes away)
Study the statements:1) URL rewriting may be used when a browser is disabled coo
kies. 2) In URL encoding the session id is included as part of the URL. Which is
the correct option? | Both 1 and 2 are trueA ___________________________ in EJB
is an object that is deploy on any EJB Server | Component
You can set a page to be an error page either through web.xml or by adding a pag
e|directive
<%@page errorPage="errorPage.jsp"
_____ %>A .. manages the threading for the servlets an
JSPs and provides the necessary interface with the Web server | Web Container
create() method of entity bean home interface returns _____________ | nullThe __
_______________ is the overall application architect. This party is responsible
for understanding how various components fit together and writes the application
s that combine components | Application Assembler
Identify correct statement about a WAR file.(Choose one) | It contains web compo
nents such as servlets as well as EJBs
Which of the following statement is correct? (choose one) | Authorization means
determining whether one has access to a particular resource or not.
A|session
FalseWhich
beanofbeing
the following
used by a is
client
example
can of
alsoJSPbedirective?
used by another
Selectclient.
one correct a
nswer. | includeWhich interface and method should be used to retrieve a servlet
initialization
| ServletConfigparameter
: getInitParameter(String
value? (Choose one)name)
Which is NOT the BEST case to use Enterprise Java Beans? (Choose one) | The appl
ications are small or medium size.
Which of the following classes define the methods setStatus(...) and sendError(.
..)
| Both
usedare
to defined
send an inHTTPHttpServletResponse
error back to the browser?
Which is NOT EJB container? | Apache Tomcat 5.5Which of the statements regarding
the following code are correct? public void doPost(HttpServletRequestreq, HttpS
ervletResponse res) throws IOException, ServletException{res.getWriter().print("
Hello ");RequestDispatcherrd = getServletContext().getRequestDispatcher("/test.j
sp");rd.include(req, res);res.getWriter().print("World");} | "Hello" and "World"
both will be a part of the output.
Which statement is true? | When isThreadSafe attribute of page directive is set
eto true, a thread is created for each request for the pag
A ____________ session bean is a bean that holds conversations that span a singl
e method call. | stateless
Which of the following elements are used for error handling and are child elemen
ts of <web-app> of a deployment descriptor? | <error_page>
Message-driven beans do not have any return value. | True
Given the following deployment descriptor:<web-app> context-param><param-name>jd
bcDriver</param-name><param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value></co
ntext-param><servlet><servlet-name>InitParams</servlet-name><servlet-class>InitP
aramsServlet</servlet-class></servlet> ..</web-app>What is the outcome of runnin
g the following servlet? (Choose one.)public class InitParamsServlet extends Htt
pServlet { protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {ServletContextsc = this.getServl
etContext(); PrintWriter out = response.getWriter(); out.write("Initialization P
arameter is: " + sc.getInitParameter("jdbcDriver")); }} | "Initialization Parame
ter is: null" returned to the requester
Consider the contents of 2 jsp files:<!-- In File : test.jsp --><html><body><% S
tring s = "Hello"; %>//1 insert LOC here.<%=s%></body></html><!-- In File : test
2.jsp --><% s = s+" world"; %>What can be inserted at //1 so that it prints "Hel
lo| <jsp:include
world" when test.jsp
page="test2.jsp"/>
is requested?
Which of the following is true about Data Integrity? | The information/data is n
ot tampered with, in transit from host to client.
To be a servlet, a class should extend HttpServlet and override doGet or doPost,
depending on whether the data is being sent by GET or by POST. | True
Name the default value of the scope attribute of <jsp:useBean> | pageThe propert
ies that characterize transactions are known as ACID properties. | True
In ejb-jar.xml file, <persistence-type> element value is _________________ | Bea
n or Container
Identify correct statement about a WAR file.(Choose one) | It contains web compo
nents such as servlets as well as EJBs.
Select the word to replace ???to make the diagram about messaging domain correct
| Topic
A web application is located in "helloapp" directory. Which directory should it'
s deployment descriptor be in? | helloapp/WEB-INFWhich statement is correct abou
t Message-Driven Beans exception handling? | Message-Driven Beans cannot send an
y exceptions back to clients
HTTP is a "stateless" protocol: each time a client retrieves a Web page, it open
s a separate connection to the Web server, and the server does not automatically
maintain contextual information about a client. | True
Which statement is correct about Bean-managed persistent (BMP)? | Bean-managed p
ersistent persisted by the developer, who write the code for the database access
callsRegarding URL rewriting for session support, which of the following is tru
e? | Every URL that the client uses must include jsessionid.
Which syntax is correct for JSP Scriptlets? | <% code %>
What is output to the web page on the second access to the same instance of the
following JSP?<html><body><%! int x = 0; %><%= x++ %></body> </html> | 0Which of
these is legal return type of the doStartTag method defined in a class that ext
ends TagSupport class? | EVAL_BODYSelect the correct JMS programming model. | Lo
cate the JMS Driver->Create a JMS connection->Create a JMS session->Locate the J
MS destination->Create a JMS producer or a JMS consumer->Send or receive message
.
___________________ includes a static file in a JSP file, parsing the file's JSP
elements | include directive
Which of the following JSP variable is not available within a JSP expression? Se
lect one correct answer | httpsession
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with the following parameter and a Location header in th
e URL. Select one correct answer. | SC_MOVED_TEMPORARILY
You do not want the user to see the data and the format being passed to your ser
ver when the user tries to submit the information for registering with your site
. Which HTTP method would you use? (Comment: You can set some hidden parameters
such as server location, in the page when the user loads it. Such parameters mea
n nothing to the user and are generally not displayed. However, determined users
can still view them using "View Source" for the page). | POST
The ______________ supplies business components, or enterprise beans. | Bean pro
vider
Which is the BEST case use Container-managed persistent (CMP)? | When you requir
e some kind of special bean, like multi-tables, that cannot be completely realiz
ed with a single bean
Which statement is correct about Message-Driven Beans?(Choose one) | Message-Dri
ven Beans stateless
Every method of the remote interface must throw a __________________ | RemoteExc
eption
Which of these is true about deployment descriptors? Select one correct answer |
None of the others
The instantiation of a session bean is done by the ____________________ while th
e management of the lifetime of the bean is done by the ________________________
___.
| Container/EJB server
Which of the following code snippet of HTML document are correct structured? | <
HTML><HEAD><TITLE>...</TITLE>...</HEAD><BODY ...>...</BODY></HTML>
What is the result of attempting to access the following JSP page?<html><body><%
! public String methodA() { return methodB();}%><%! public String methodB() { re
turn "JAD Final Test";}%><h2><%= methodA() %></h2></body></html> | "JAD Final Te
st" is output to the resulting web page
______and
| ejbActivate()
ejbPassivate()
_______methods do not apply to stateless session beans.
A JavaBeans component has the following field | public void setEnabled( boolean
enabled) public booleangetEnabled()Which of the following is indicated by URL, w
hich is used on the Internet? | Information resources(sources) on the Internet
You want to use a bean that is stored in com/enthu/GUI.ser file. Which of follow
ing statements correctly defines the tag that accesses the bean? | <jsp:useBean
id="pref" beanName="com.enthu.GUI" type="com.enthu.GUI"/>
A JSP page has the following page directives:<%@page isErrorPage='false' %> <%@p
age errorPage='/jsp/myerror.jsp' %> Which of the following implicit object is NO
T|available
exceptionto the jsp page?
A bean with a property color is loaded using the following statement <jsp:useBea
n id="fruit" class="Fruit"/>Which of the following statements may be used to pri
nt the value of color property of the bean?. Select the one correct answer. | <j
sp:getProperty name="fruit" property="color"/>
The ____________ interface is a Java interface that enumerates the business meth
ods exposes by the enterprise bean class. | remote
A ____________ is a group of operations, which appear as one large operation dur
ing
| Transaction
execution.
Select the BEST case to Use Entity Beans? (Choose one) | At any given time, only
one client has access to the bean instance.
Which
Point-to-Point
are the types of messaging domains? (choose 2) | Publish/Subscribe
Message-Driven Bean does not have a home interface, local home interface, remote
interface, or a local interface. | True
For what reason does the following JSP fail to translate and compile? <html><bod
y><%! int x; %><%=x ; %></body></html> | Error in JSP Expression
Which of the following statement is true about the Entity class? | Entity class
must be declared as top level class
A bean with a property color is loaded using the following statement <jsp:useBea
n id="fruit" class="Fruit"/> Which statement may be used to set the color proper
ty of the bean | <jsp:setProperty name="fruit" property="color" value="white"/>
Which of the following xml fragments correctly define a security constraint in w
eb.xml?
| <security-constraint><web-resource-collection><web-resource-name>Info</web-re
(Choose one)
source-name><url-pattern>/info/*</url-pattern><http-method>GET</http-method></we
b-resource-collection><auth-constraint><role-name>manager</role-name></auth-cons
traint></security-constraint>
Study the statements about web.xml file: 1) The deployment descriptor file is ca
lled web.xml, and it must be located in the WEB-INF directory.2) web.xml is in X
ML (extended markup language) format. Its root element is <web>. | Only statemen
t 1 is true
A JSP expression is used to insert values directly into the output. | True
A|JSP
thepage
session
willattribute
not have of
access
pagetodirective
session is
implicit
set tovariable
false if:
The ______________ is the container-generated implementation of the remote inter
face | EJB ObjectWhich of the following is NOT a valid attribute for a useBean t
ag? | classNameWhat gets printed when the following JSP code is invoked in a bro
wser? Select one correct answer. <%= if(Math.random() < 0.5) %> hello<%= } else
{ %> hi<%= } %> | The JSP file will not compile
Is it possible to share aHttpSession object between a Java Server Page and Enter
prise Java Bean? | Yes, you can pass the HttpSession as parameter to an EJB meth
od, only if all objects in session are serializableDeployment properties are sto
red
| XML
in a _______________________ file.
Which is the correct sequence? | Jsp page is translated -->jsp page is complied-
->jspInit is called ->_jspService is called -->jspDestroy is calledThe HttpServl
etRequest has methods by which you can find out about incoming information such
as:
| All of the othersThe ____________________class makes every entity bean differ
ent.
| primary key
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with d
ynamically generated content from servlets. You simply write the regular HTML in
the normal manner, using familiar Web-page-building tools | True
Which of the following is INCORRECT statement about implicit objects and scope?
| application can't be used to access other web application resources
The exception-type element specifies an exception type and is used to handle exc
eptions generated from a servlet. Which element of the deployment descriptor inc
ludes the exception-type as a sub-element? Do not include the element in enclosi
ng parenthesis | error-page
Which syntax is correct for JSP Declarations? | <%! code %>
Which of the following is legal JSP syntax to print the value of i. Select the o
ne correct answer | <%int i = 1;%> <%= i %>
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/test.jsp?name="John". The test.jsp contains the following code. <%! Stri
ng myName=request.getParameter();%><% String test= "welcome" + myName; %><%= tes
t%> | The program gives a syntax error because of the statement <%! String myNam
e=request.getParameter();%>
Which of the following correctly represents the following JSP statement. Select
the one correct answer. <%=x%> | <jsp:expression>x</jsp:expression>
Which of the following correctly represents the following JSP statement. Select
the one correct answer. <%x=1;%> | <jsp:scriptlet>x=1;</jsp:scriptlet>
What gets printed when the following JSP code is invoked in a browser. Select th
e one correct answer. <%= if(Math.random() < 0.5) %> hello<%= } else { %> hi <
%= } %> | The JSP file will not compile.
Which of the following are correct. Select the one correct answer | To use the c
haracter %> inside a scriptlet, you may use %\> instead.
What gets printed when the following is compiled. Select the one correct answer.
<% int y = 0; %> <% int z = 0; %> <% for(int x=0;x<3;x++) { %> <% z++;++y;%> <%
}%> <% if(z<y) {%> <%= z%> <% } else {%> <%= z - 1%> <% }%> | 2
Which of the following JSP variables are not available within a JSP expression.
Select the one correct answer. | httpsession
A bean with a property color is loaded using the following statement <jsp:usebea
n id="fruit" class="Fruit"/> Which of the following statements may be used to pr
int the value of color property of the bean. Select the one correct answer | <js
p:getProperty name="fruit" property="color"/>
A bean with a property color is loaded using the following statement | <jsp:setP
roperty name="fruit" property="color" value="white"/>
A bean with a property color is loaded using the following statement <jsp:usebea
n id="fruit" class="Fruit"/> What happens when the following statement is execut
ed. Select the one correct answer. <jsp:setProperty name="fruit" property="*"/>
| C. All the properties of the fruit bean are assigned the values of input pa
rameters of the JSP page that have the same name
Which of the following represents a correct syntax for usebean. Select the two c
orrect answers | <jsp:usebean id="fruit type ="String"/> <jsp:usebean id="fruit
type ="String" beanName="Fruit"/>
Name the default value of the scope atribute of <jsp:usebean>. | page
Which of the following statements are true for <jsp:usebean>. Select the two cor
rect answers. | The id attribute must be defined for <jsp:usebean>. The <jsp:use
bean> must include either type or class attribute or both.
Which of these are legal attributes of page directive. Select the two correct an
swers | errorPage . session
Which of the following represents the XML equivalent of this statement <%@ inclu
de file="a.jsp"%> . Select the one correct statement | C. <jsp:directive.i
nclude file="a.jsp"/>
Assume that you need to write a JSP page that adds numbers from one to ten, and
then print the output.<% int sum = 0;for(j = 0; j < 10; j++) { %>// XXX --- Add
j to sum<% } %>// YYY --- Display the sum Which statement when placed at the loc
ation XXX can be used to compute the sum. Select the one correct statement | <%
sum = sum + j; %>
Now consider the same JSP example as last question. What must be added at the lo
cation YYY to print the sum of ten numbers. Select the one correct statement | <
%= sum %>
JSP pages have access to implicit objects that are exposed automatically. One su
ch object that is available is request. The request object is an instance of whi
ch class? | HttpServletRequest
JSP pages have access to implicit objects that are exposed automatically. Name t
he implicit object that is of type HttpSession. | session
A Java bean with a property color is loaded using the following statement <jsp:u
sebean id="fruit" class="Fruit"/> What is the effect of the following statement.
<jsp:setproperty name="fruit" property="color"/> Select the one correct answer.
| If there is a non-null request parameter with name color, then its value gets
assigned to color property of Java Bean fruit.
The page directive is used to convey information about the page to JSP container
. Which of these are legal syntax of page directive. Select the two correct stat
ement | <%@ page info="test page" session="false"%> <%@ page session="true" %>
Is the following JSP code legal? Select the one correct statement. <%@page info=
"test page" session="false"%> <%@page session="false"%> | No. This code will g
enerate syntax errors
A JSP page uses the java.util.ArrayList class many times. Instead of referring t
he class by its complete package name each time, we want to just use ArrayList.
Which attribute of page directive must be specified to achieve this. Select the
one correct answer | import
A JSP page needs to generate an XML file. Which attribute of page directive may
be used to specify that the JSP page is generating an XML file. | contentType
Which of these are true. Select the two correct answers | The default value of i
sThreadSafe attribute of page directive is true .When isThreadSafe attribute of
page directive is set to true, a thread is created for each request for the page
Which of the following are examples of JSP directive. Select the two correct ans
wers.(?)(not checked yet) | include, taglibrary, page
Which of these is true about include directive. Select the one correct answer |
When using the include directive, the JSP container treats the file to be includ
ed as if it was part of the original file
Name the implicit variable available to JSP pages that may be used to access all
the other implicit objects | pageContext
Which of the following files is the correct name and location of deployment desc
riptor of a web application. Assume that the web application is rooted at \doc-r
oot. Select the one correct answer | C. \doc-root\WEB-INF\web.xml
Which element of the servlet element in the deployment descriptor is used to spe
cify the parameters for the ServletConfig object. Select the one correct answer.
| B. init-param
Which of these is true about deployment descriptors. Select the one correct answ
er | The order of elements in deployment descriptor is not important. The elemen
ts can follow any order
The exception-type element specifies an exception type and is used to handle exc
eptions generated from a servlet. Which element of the deployment descriptor inc
ludes the exception-type as a sub-element. Select the one correct answer | error
-page
Which of these is a correct fragment within the web-app element of deployment de
scriptor. Select the one correct answer. | <error-page> <exception-type> mypacka
ge.MyException</exception-type> <location> /error.jsp</location> </error-page>
Which element of the deployment descriptor of a web application includes the wel
come-file-list element as a subelement. Select the one correct answer.(?)(not ch
ecked yet) | welcome-file
Which of these is a correct fragment within the web-app element of deployment de
scriptor. Select the two correct answer | A.<error-page> <error-code>404</error-
code> <location>/error.jsp</location> </error-page> D. <error-page> <exception-
type>mypackage.MyException</exception-type> <location>/error.jsp</location> </er
ror-page>
Which of these is a correct example of specifying a listener element resented by
MyClass class. Assume myServlet element is defined correctly. Select the one co
rrect answer | <listener> <listener-class>MyClass</listener-class></listener>
The root of the deployment descriptor is named as | web-app
With in a context-param element of deployment descriptor, which of the following
element is required? | param-name
Which of these is not a valid top level element in web-app | param-name
Which of the follwing are mandatory elements within the filter element. Select t
wo correct answers. | A.filter-name D.filter-class
Which of these is not a valid value for dispatcher element of filter-mapping. Se
lect the one correct answer. | RESPONSE
Which of these is not correct about the filter-mapping element of web-app. Selec
t the one correct answer | dispatcher element can be declared zero to three time
s in the filter-mapping element
When implementing a tag, if the tag just includes the body verbatim, or if it do
es not include the body, then the tag handler class must extend the BodyTagSuppo
rt class. Is this statement true of false. | false
Fill in the blanks. A tag handler class must implement the javax.servlet.jsp.tag
ext.Tag interface. This is accomplished by extending the class TagSupport or ano
ther class named in one of the options below. Select the one correct answer. | B
odyTagSupport
Is this statement true or false. The deployment descriptor of a web application
must have the name web.xml . In the same way the tag library descriptor file mus
t be called taglib.xml | false
A JSP file that uses a tag library must declare the tag library first. The tag l
ibrary is defined using the taglib directive - <%= taglib uri="..." prefix="..."
%> Which of the following specifies the correct purpose of prefix attribute. Sel
ect the one correct answer. | The prefix attribute is used in front of a tagname
of a tag defined within the tag library.
A JSP file uses a tag as <myTaglib:myTag>. The myTag element here should be defi
ned in the tag library descriptor file in the tag element using which element. S
elect the one correct answer | name
Which of the elements defined within the taglib element of taglib descriptor fil
e are required. Select the two correct answers | A. tlib-version B.short-nam
e
Which of the elements defined within the taglib element of taglib descriptor fil
e are required. Select the two correct answers | A. name D.tag-class
Name the element within the tag element that defines the name of the class that
implements the functionality of tag. Select the one correct answer | tag-class
Which of these are legal return types of the doStartTag method defined in a clas
s that extends TagSupport class. Select the two correct answers | D.EVAL_BODY_IN
CLUDE (F.SKIP_BODY
Which of these are legal return types of the doAfterBody method defined in a cla
ss that extends TagSupport class. Select the two correct answers | D.EVAL_BODY_A
GAIN (F.SKIP_BODY
Which of these are legal return types of the doEndTag method defined in a class
that extends TagSupport class. Select the two correct answers. | A. EVAL_PAGE (E
.SKIP_PAGE)
The method getWriter returns an object of type PrintWriter. This class has print
ln methods to generate output. Which of these classes define the getWriter metho
d? Select the one correct answer. | HttpServletResponse
Name the method defined in the HttpServletResponse class that may be used to set
the content type. Select the one correct answer. | setContent
Which of the following statement is correct. Select the one correct answer | The
HttpServletResponse defines constants like SC_NOT_FOUND that may be used as a p
arameter to setStatus method
The sendError method defined in the HttpServlet class is equivalent to invoking
the setStatus method with the following parameter. Select the one correct answer
| SC_NOT_FOUND
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with the following parameter and a Location header in th
e URL. Select the one correct answer | SC_MOVED_TEMPORARILY
Which of the following statements are correct about the status of the Http respo
nse. Select the one correct answer. | A status of 200 to 299 signifies that the
request was successful.
To send binary output in a response, the following method of HttpServletResponse
may be used to get the appropriate Writer/Stream object. Select the one correct
answer. | getOutputStream
To send text output in a response, the following method of HttpServletResponse m
ay be used to get the appropriate Writer/Stream object. Select the one correct a
nswer. | getWriter
Is the following statement true or false. URL rewriting may be used when a brows
er is disabled. In URL encoding the session id is included as part of the URL. |
true
Name the class that includes the getSession method that is used to get the HttpS
ession object. | HttpServletRequest
Which of the following are correct statements? Select the two correct answers |
A.The getRequestDispatcher method of ServletContext class takes the full path of
the servlet, whereas the getRequestDispatcher method of HttpServletRequest clas
s takes the path of the servlet relative to the ServletContext C.The getRequestD
ispatcher(String URL) is defined in both ServletContext and HttpServletRequest m
ethod
A user types the URL http://www.javaprepare.com/scwd/index.html . Which HTTP req
uest gets generated. Select the one correct answer | A. GET method
Which HTTP method gets invoked when a user clicks on a link? Select the one corr
ect answer | GET method
When using HTML forms which of the folowing is true for POST method? Select the
one correct answer. | POST method sends data in the body of the request.
Which of the following is not a valid HTTP/1.1 method. Select the one correct an
swer | COMPARE method
Name the http method used to send resources to the server. Select the one correc
t answer | B. PUT method
Name the http method that sends the same response as the request. Select the one
correct answer | TRACE method
Which three digit error codes represent an error in request from client? Select
the one correct answer | C. Codes starting from 400
Name the location of compiled class files within a war file? Select the one corr
ect answer | /WEB-INF/classes
What gets printed when the following expression is evaluated? Select the one cor
rect answer. ${(1==2) ? 4 : 5} | 5
What gets printed when the following expression is evaluated? Select the one cor
rect answer. ${4 div 5} | 0.8
What gets printed when the following expression is evaluated? Select the one cor
rect answer. ${12 % 4} | 0
What is the effect of executing the following JSP statement, assuming a class wi
th name Employee exists in classes package. <%@ page import = "classes.Employee"
%> <jsp:useBean id="employee" class="classes.Employee" scope="session"/> <jsp:s
etProperty name="employee" property="*"/> | The code sets the values of all prop
erties of employee bean to matrching parameters in request object
What is the effect of evaluation of following expression? Select the one correct
answer. ${(5*5) ne 25} | false
What is the effect of evaluation of following expression? Select the one correct
answer. ${'cat' gt 'cap'} | true
How many numbers are printed, when the following JSTL code fragment is executed?
Select the one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core
" prefix="c" %> <c:forEach var="item" begin="0" end="10" step="2"> ${item} </c:f
orEach> | 6
What gets printed when the following JSTL code fragment is executed? Select the
one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%> <c:set var="item" value="2"/> <c:if test="${var==1}" var="result" scope="ses
sion"> <c:out value="${result}"/> </c:if> | Nothing gets printed.
What gets printed when the following JSTL code fragment is executed? Select the
one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%> <c:set var="item" value="2"/> <c:forEach var="item" begin="0" end="0" step="
2"><c:out value="${item}" default="abc"/></c:forEach> | 0
How many numbers gets printed when the following JSTL code fragment is executed?
Select the one correct answer.<%@ taglib uri="http://java.sun.com/jsp/jstl/core
" prefix="c" %> <c:set var="item" value="2"/> <c:choose> <c:when test="${item>0}
"> <c:out value="1"/> </c:when> <c:when test="${item==2}"> <c:out value="2"/> </
c:when> <c:when test="${item<2}"> <c:out value="3"/> </c:when> <c:otherwise> <c:
out value="4"/> </c:otherwise> </c:choose> | One number gets printed.
Which numbers gets printed when the following JSTL code fragment is executed? Se
lect the two correct answers. <%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %> <c:set var="j" value="4,3,2,1"/> <c:forEach items="${j}" var="ite
m" begin="1" end="2"> <c:out value="${item}" default="abc"/> </c:forEach> | 2 3
Which numbers gets printed when the following JSTL code fragment is executed? Se
lect the two correct answers.<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %> <c:set var="j" value="4,3,2,1"/> <c:forEach items="${j}" var="item
" begin="1" end="2" varStatus="status"> <c:out value="${status.count}" default="
abc"/> </c:forEach> | 2 3
Which number gets printed when the following JSTL code fragment is executed? Sel
ect the one correct answers.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" p
refix="c" %><c:set var="j" value="4,3,2,1"/><c:forEach items="${j}" var="item" v
arStatus="status"><c:if test="${status.first}"><c:out value="${status.index}" de
fault="abc"/></c:if></c:forEach> | 1
Which of these represent the correct path for the core JSTL library in JSTL vers
ion 1.1? Select the one correct answer | http://java.sun.com/jsp/jstl/core
Identify the method used to get an object available in a session.(Choose one) |
a. getAttribute of HttpSession
See the extract from web.xml of web application "mywebapp" on server named myser
ver, runs on port 8080: <servlet-mapping><servlet-name>ServletA</servlet-name><u
rl-pattern>/</url-pattern></servlet-mapping><servlet-mapping><servlet-name>Servl
etB</servlet-name><url-pattern>/bservlet.html</url-pattern></servlet-mapping><se
rvlet-mapping><servlet-name>ServletC</servlet-name><url-pattern>*.servletC</url-
pattern></servlet-mapping><servlet-mapping><servlet-name>ServletD</servlet-name>
<url-pattern>/dservlet/*</url-pattern></servlet-mapping>Given that a user enters
the following into her browser, which (if any) of the mapped servlets will exec
ute? (Choose one.) http://myserver:8080/mywebapp/Bservlet.html | a. ServletA
The HttpSession method getAttribute returns the object associated with a particu
lar name. | a. True
Which method of ReportGeneratorServlet will be called when the user clicks on th
e URL shown by the following HTML. Assume that ReportGeneratorServlet does not
override the service(HttpServletRequest, HttpServletResponse) method of the Http
Servlet class. (Choose one) | a. doGet(HttpServletRequest, HttpServletResponse);
Select the correct directive statement insert into the first line of following l
ines of code (1 insert code here): | a. <%@page import='java.util.*' %>
GET requests and POST requests can both be used to send form data to a web serve
r. | a. True
Which statements are BEST describe id attribute of <jsp:useBean id=..... /> Acti
on? | a. The name used to manipulate the Java object with actions <jsp:setProper
ty> and <jsp:getProperty>. A variable of this name is also declared for use in J
SP scripting elements. The name specified here is case sensitive.
Which of the following methods will be invoked if the doStartTag() method of a t
ag returns Tag.SKIP_BODY? | a. doEndTag()
Which is NOT associated with the business tier in a JEE (J2EE) web-based applica
tion? | a. JSP
Which statement is true about both stateful and stateless session beans about be
an instances? | a. Bean instances are NOT require to survive container crashes
Which of the elements defined within the taglib element of taglib descriptor fil
e are required? Select one correct answer. | a. taglib-location
In which of the following Authentication mechanism, the browser transmits the us
ername and password to the server without any encryption? (Choose one) | a. HTT
P BASIC Authentication
Which of the following is a valid standard action that can be used by a jsp page
to import content generated by another JSP file named another.jsp? | a. <jsp:i
nclude page='another.jsp'/>
Which of the following techniques would correctly put a bean into application sc
ope? (You can assume that any necessary page directives are present and correct
elsewhere in the JSP page.)(Choose one.) | a. <jsp:useBean id="app1" class="web
cert.ch07.examp0701.AddressBean" scope="application" />
Which statement about JMS is true? | a. JMS supports Publish/Subcribe
Which is the CORRECT statement about JMS? | a. JMS uses JNDI to find destination
Which statements are BEST describe name attribute of <jsp:setProperty name=....
/> action? | a. The ID of the JavaBean for which a property (or properties) will
be set.
Action _______has the ability to match request parameters to properties of the s
ame name in a bean by specifying "*" for attribute property. | a. <jsp:setProper
ty>
Consider the following java code://in file Book.java package com.bookstore;publi
c class Book{private long isbn; public Book(){ isbn = 0; }public long getIsbn(){
return isbn; }public void setIsbn(long value){ this.isbn = value; }}Code for br
owse.jsp:<jsp:useBean class="com.bookstore.Book" id="newbook" />LINE 1 : <jsp:se
tProperty name="newbook" property="isbn" value="1000"/> Which of the following s
tatements are correct? | a. The isbn property of newbook will be set to 1000.
Which of the following is equivalent <%! ? (Choose one) | a. <jsp:declaration
<html><body><form action="loginPage.jsp">Login ID:<input type= "text" name="logi
nID"><br>Password:<input type="password" name="password"><br><input type="submit
" value="Login"><input type="reset" value="Reset"></form></body><html> Study the
above html code. Assume that user clicks button Reset. What is the correct stat
ement? | a. All inputs are cleared.
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with d
ynamically generated content from servlets. You simply write the regular HTML in
the normal manner, using familiar Web-page-building tools. | a. True
A JSP page needs to generate an XML file. Which attribute of page directive may
be used to specify that the JSP page is generating an XML file? | a. <%@page con
tentType ="text/xml">
JSP __________ let you insert arbitrary code into the servlet's _jspService meth
od (which is called by service). | a. scriptlets
Which HTTP method is used in FORM based Authentication? | a. POST
Review the following scenario; then identify which security mechanisms would be
important to fulfill the requirement. (Choose one.) An online magazine company w
ishes to protect part of its website content, to make that part available only t
o users who pay a monthly subscription. The company wants to keep client, networ
k, and server processing overheads down: Theft of content is unlikely to be an i
ssue, as is abuse of user IDs and passwords through network snooping. | a. Autho
rization and Authentication
Which statement about entity manager is true? | a. A container-managed entity ma
nager must be a JTA entity manager.
Which class type must be implicitly or explicitly denoted in the persistence.xml
descriptor as managed persistence classes to be included within a persistence u
nit? | a. Entity classes
Which option can be used to predefine Java Persistence queries for easy use? | a
. @NamedQuery annotation
What is the implementation specification of EJB 3 session bean classes? | a. a s
ession bean class must be marked with @Stateless or @Stateful
Which statement is true about management of an EJB's resources? | a. The referen
ce to home object is obtained through JNDI to improve maintainability and flexib
ility.
Which is NOT belonging to basic three types of EJB? | a. Transfer object
Which act as a proxy to an EJB? | a. Remote instance
Which statement is true about EJB 3.0 stateful session beans and stateless sessi
on beans? (Choose one) | a. Both can have multiple remote and local business int
erfaces
Consider the following HTML code. Which method of MyFirstServlet will be invoked
when you click on the url shown by the page? | a. doGet
Which of the following element are required for a valid <taglib> tag in web.xml?
(Choose one) | a. <taglib_uri>
Which of the following elements defines the properties of an attribute that a ta
g needs? | a. attribute
Which statements are BEST describe property attribute of <jsp:setProperty proper
ty=.... /> Action? | a. The ID of the JavaBean for which a property (or properti
es) will be set.
Which statements are BEST describe errorPage attribute of <%@ page errorPage=...
.%> directive? | a. Any exceptions in the current page that are not caught are s
ent to the error page for processing. The error page implicit object exception r
eferences the original exception.
Which of the following statement is a correct JSP directive?(Choose one) | a. <%
@ tagliburi="http://www.abc.com/tags/util" prefix="util" %>
Which is NOT a scope of implicit objects of JSP file? | a. application
A bean present in the page and identified as 'mybean' has a property named 'name
'. Which of the following is a correct way to print the value of this property?
| a. <jsp:getProperty name="mybean" property="name"/>
Which statements are BEST describe prefix attribute of <%@ taglib prefix=...%>di
rective of JSP file? | a. Specifies the relative or absolute URI of the tag libr
ary descriptor.
Which element defined within the taglib element of taglib descriptor file is req
uired? Select one correct answer. | a. Tag
Which statement is true about EJB 3.0 stateful session beans and stateless sessi
on beans? | a. Both can have multiple remote and local business interfaces
Which statement about entity manager is true? | a. A container-managed entity ma
nager must be a JTA entity manager.
Which statement describe about Message-Driven Beans is correct? (Choose one) | a
. Message-Driven Beans are stateful
A developer is working on a project that includes both EJB 2.1 and EJB 3.0 sessi
on beans. A lot of business logic has been implemented and tested in these EJB 2
.1 session beans. Some EJB 3.0 session beans need to access this business logic.
Which design approach can achieve this requirement? | a. Add adapted home inter
faces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interop
erable.
Which is NOT Enterprise Beans? | a. Business Beans
Which is NOT associated with the business tier in a JEE (J2EE) web-based applica
tion? | a. JSP
Which statement is true about EJB 3.0 containers? | a. javax.naming.initialConte
xt is guaranteed to provide a JNDI name space
The following statement is true or false? "If the isThreadSafe attribute of the
page directive is true, then the generated servlet implements the SingleThreadMo
del interface." | a. True
Select the correct directive statement insert into the first line of following l
ines of code (1 insert code here): | a. <%@page import='java.util.*' %>
Which interface you CANNOT use to obtain a RequestDispatcher Object? | a. Servle
tContext
Study the statements:<question>1) The context path contains a special directory
called WEB-INF, which contains the deployment descriptor file, web.xml.<question
>2) A client application may directly access resources in WEB-INF or its subdire
ctories through HTTP. | a. Only statement 1 is true
A .................... manages the threading for the servlets and JSPs and provi
des the necessary interface with the Web server. | a. Web Container
Which interface can you use to retrieve a resource that belongs to the current w
eb application? | a. ServletContext
HttpSession objects have a built-in data structure that lets you store any numbe
r of keys and associated values. | a. True
HTTP is a "stateless" protocol: each time a client retrieves a Web page, it open
s a separate connection to the Web server, and the server does not automatically
maintain contextual information about a client. | a. True
Servlet methods are executed automatically. | a. True
Which of the following statement correctly store an object associated with a nam
e at a place where all the servlets/jsps of the same webapp participating in a s
ession can access it? Assume that request, response, name, value etc. are refere
nces to objects of appropriate types.(Choose one) | a. request.getSession().setA
ttribute(name, value);
Which of the following lines of code, in the doPost() method of a servlet, uses
the URL rewriting approach to maintaining sessions? (Choose one) | a. out.printl
n("<a href=' "+response.encodeURL("/servlet/XServlet")+" '>Click here</a>"));
Objects with application scope are part of a particular Web application. | a. Tr
ue
Which of the following is a correct JSP declaration for a variable of class java
.util.Date? | a. <%! Date d = new Date(); %>
Which of the following task may happen in the translation phase of JSP page? (Ch
oose one) | a. Creation of the servlet class corresponding to the JSP file.
Which of the following are correct JSP expressions | a. <%= new Date() %>
What is the consequence of attempting to access the following JSP page? <questio
n><html><question><body><question><%! <question> public void _jspService(HttpSer
vletRequest request, HttpServletResponse response) {<question> out.write("A");<q
uestion> }<question> %><question><% out.write("B"); %><question></body><question
></html> | a. Duplicate method compilation error.
Which of the following statements is true? (Choose one) | a. Session data is sha
red across multiple webapps in the same webserver/servlet container.
Each page has its own instances of the page-scope implicit objects. | a. True
A developer wants to achieve the following two behaviors for an EJB 3.0 session
bean:(1) If the client calls a business method with a transaction context, the c
ontainer will invoke the enterprise bean's method in the client's transaction co
ntext.(2) If the client calls a business method without a transaction context, t
he container will throw the javax.ejb.EJBTransactionRequiredException.Which tran
saction attribute should be used? | a. MANDATORY
Which statement about JMS is true? | a. JMS supports Publish/Subcribe
Which statement is correct about Java EE client of a message-driven beans? | a.
The client can use JNDI to obtain a reference to a message destination
Which is NOT Enterprise Beans? | a. Business Beans
Which act as a proxy to an EJB? | a. Remote instance
________ is the well-known host name that refers to your own computer. | a. loc
alhost
You have to send a gif image to the client as a response to a request. Which of
the following calls will you have to make? (Choose one) | a. response.setContent
Type("image/gif");
The Java Persistent API defines the Query interface. Which statement is true abo
ut the Query.executeUpdate method ? | a. It must always be executed within a tra
nsaction
A JSP page called test.jsp is passed a parameter name in the URL using http://lo
calhost/Final/test.jsp?name=John. The test.jsp contains the following code.<% St
ring myName=request.getParameter("name");%><% String test= "Welcome " + myName;
%><%=test%>What is the output? | a. The page display "Welcome John"
Which is NOT associated with the business tier in a JEE (J2EE) web-based applica
tion? | a. JSP
Which option can be used to predefine Java Persistence queries for easy use? | a
. @NamedQuery annotation
Which statement is true about EJB 3.0 containers? | a. javax.naming.initialConte
xt is guaranteed to provide a JNDI name space
Which statement is NOT true about JMS? | a. JMS does NOT depend on MOM (Messagin
g-Oriented Middleware) products
Which statement about entity manager is true? | a. A container-managed entity ma
nager must be a JTA entity manager.
Which is NOT belonging to basic three types of EJB? | a. Transfer object
Which class type must be implicitly or explicitly denoted in the persistence.xml
descriptor as managed persistence classes to be included within a persistence u
nit? | a. Entity classes
To read the cookies that come back from the client, you call getCookies on the H
ttpServletRequest. | a. True
Which is the CORRECT statement about JMS? | a. JMS uses JNDI to find destination
What is the implementation specification of EJB 3 session bean classes? | a. a s
ession bean class must be marked with @Stateless or @Stateful
Which statement is true about both stateful and stateless session beans about be
an instances? | a. Bean instances are NOT require to survive container crashes
Given a stateless session bean with container-managed transaction demarcation, f
rom which method can a developer access another enterprise bean? | a. business m
ethod from the business interface
The same servlet class can be declared using different logical names in the depl
oyment descriptor. | a. True
Study the statements:1) The context path contains a special directory called WEB
-INF, which contains the deployment descriptor file, web.xml. 2) A client applic
ation may directly access resources in WEB-INF or its subdirectories through HTT
P. | a. Only statement 1 is true
Which statement is true about management of an EJB's resources? | a. The referen
ce to home object is obtained through JNDI to improve maintainability and flexib
ility.
Which is NOT a technique that can be used to implement 'sessions' if the client
browser does not support cookies? | a. Using Http headers.
_________________ provides a way to identify a user across more than one page r
equest or visit to a Web site and to store information about that user. | a. Ses
sion management
Which statement is true about the EJB 3.0 stateful session beans? | a. Its conve
rsational state is retained across method invocations and transactions
Which of the following methods can be used to add cookies to a servlet response?
| a. HttpServletResponse.addCookie(Cookie cookie)
Which statement is true about EJB 3.0 stateful session beans and stateless sessi
on beans? (Choose one) | a. Both can have multiple remote and local business int
erfaces
Given that a servlet has been mapped to /account/. Identity the HttpServletReque
st methods that will return the /account segement for the URI: /myapp/account/.
| b. getServletPath
What should be the return type of the method using @PrePassivate? | b. void
Which statements are BEST describe isErrorPage attribute of <%@ page isErrorPage
=....%> directive? | b. Specifies if the current page is an error page that will
be invoked in response to an error on another page. If the attribute value is t
rue, the implicit object exception is created and references the original except
ion that occurred.
Which statements are BEST describe <jsp:include> Action? | b. Dynamically includ
es another resource in a JSP. As the JSP executes, the referenced resource is in
cluded and processed.
A stateful session bean must commit a transaction before a business method | b.
False
Which security mechanism proves that data has not been tampered with during its
transit through the network? | b. Data integrity
Which is disadvantage of using JEE (or J2EE) server-side technologies in a web-b
ased application? | b. Complexity
Which statement describe about JMS is NOT true? | b. JMS enhances access to emai
l services
Which statements are BEST describe page implicit object of jsp file? | b. This j
ava.lang.Object object represents the this reference for the current JSP instanc
e.
Which component can use a container-managed entity manager with an extended pers
istent context? | b. Only stateful session beans
The sendRedirect method defined in the HttpServlet class is equivalent to invoki
ng the setStatus method with they following parameter and a Location header in t
he URL. Select one correct answer. | b. SC_MOVED_TEMPORARILY
Which directory is legal location for the deployment descriptor file? Note that
all paths are shown as from the root of the web application directory. | b. \WEB
-INF
Which is NOT provided by the EJB tier in a multitier JEE (J2EE) application? | b
. XML Parsing
Which is true about JDBC? | b. The JDBC API is included in J2SE
Which is true about the relationship "A keyboard has 101 keys"? | b. This is a o
ne-to-may relationship
If you want to send an entity object as the pass by value through a remote inter
face, which of the following statements are valid? (Choose one) | b. @Entity pub
lic class Employees implements Serializable{...}
Which statement is correct about the Java Persistence API support for the SQL qu
eries? | b. The result of a SQL query is not limited to entities
Which of the following lines of code are correct? | b. @Entity public class Empl
oyees{... }
Can we use the annotation @PrePassivate for more than one method in a Entity bea
n? | b. No
What should be the return type of the method using @PrePassivate? | void
Can we use the annotation @PrePassivate for more than one method in a Entity bea
n? | No
An object with page scope exists in every JSP of a particular Web application. |
False
Which statement describe about JMS is NOT true? | b. JMS enhances access to emai
l services
Which statement describe about Message-Driven Beans is correct? (Choose one) | b
. An EJB 3.0 message-driven beans can itself be the client of another message-dr
iven beans
Which Java technology provides a standard API for publish-subscribe messaging mo
del? | b. JMS
To send binary outptut in a response, the following method of HttpServletRespons
e may be used to get the appropriate Writer/Stream object. | b. getOutputStream
Which is true about JDBC? | b. The JDBC API is included in J2SE
Which Java technology provides a standard API for publish-subscribe messaging mo
del? | b. JMS
How can you ensure the continuity of the session while using HttpServletResponse
.sendRedirect() method when cookies are not supported by the client? | b. By en
conding the redirect path with HttpServletResponse.encodeRedirectURL() method.
Which of the following defines the class name of a tag in a TLD? | b. tag-class
Which statements are BEST describe prefix attribute of <%@ taglib prefix=...%>di
rective of JSP file? | b. Specifies the required prefix that distinguishes custo
m tags from built-in tags. The prefix names jsp, jspx, java, javax, servlet, sun
and sunw are reserved.
Can we use the annotation @PrePassivate for more than one method in a Entity bea
n? | No
Which is true about RMI? | b. RMI allows objects to be send from one computer to
another
Which Java technology provides a unified interface to multiple naming and direct
ory services? | b. JNDI
Which is disadvantage of using JEE ( or J2EE) server-side technologies in a web-
based application? | b. Complexity
Which of the following correctly represents the following JSP statement? Select
one correct answer. <%=x%> | b. <jsp:expression>x</jsp:expression>
Which of these is a correct fragment within the web-app element of deployment de
scriptor? Select the one correct answer | b. <error-page> <exception-type> mypac
kage.MyException</exception-type> <location> /error.jsp</location> </error-page>
Which statement describe about JMS is NOT true? | c. JMS use JNDI to locate the
destination
Which is NOT represented in a UML class diagram? | c. The interaction between ob
jects in sequential order
Which type of JEE (or J2EE) component is used to store business data persistentl
y? | c. Entity Bean
The requirement for an online shopping application are: It must support millions
of customers. The invocations must be transactional. The shopping cart must be
persistent. Which technology is required to support these requirements? | c. EJB
Which statement is true about the use of a persist operation in a transaction of
an Entity Beans | c. If a user persists a new entity with an existing primary k
ey the transaction will fail
EJB 3.0 specifications are first implemented in ________ | c. Java EE 5
Which of these is legal attribute of page directive?. | c. errorPage
Which is NOT a correct statement about entity beans? | c. They are used to imple
ment business processes
A developer must implement a "shopping cart" object for a web-based application.
The shopping cart must be able to maintain the state of the cart, but the state
is not stored persistently. Which JEE (J2EE) technology is suited to this goal?
| c. Stateful session beans
Which is true about JEE ( or J2EE)? | c. JEE includes servlet APIs and EJB APIs
Which statements are BEST describe <jsp:getProperty> Action? | c. Sets a propert
y in the specified JavaBean instance. A special feature of this action is automa
tic matching of request parameters to bean properties of the same name.
Which is a valid PostConstruct method in a message-driven bean class? | c. @Post
Construct c. private void init() {}
What do you need to create a EJB3 session bean? | c. Annotate the session bean w
ith @Stateful or @Stateless
You need to make sure that the response stream of your web application is secure
. Which factor will you look at? (Choose one) | c. data integrity
A developer is working on a project that includes both EJB 2.1 and EJB 3.0 sessi
on beans. A lot of business logic has been implemented and tested in these EJB 2
.1 session beans. Some EJB 3.0 session beans need to access this business logic.
Which design approach can achieve this requirement? | c. No need to modify exis
ting EJB 2.1 session beans. Use the @EJB annotation to inject a reference to the
EJB 2.1 home interface into the EJB 3.0 bean class.
Which is NOT true about stateless session beans? | c. They are used to represent
data stored in a RDBMS
Which is NOT a correct statement about entity beans? | c. They are used to imple
ment business processes
Following is the code for doGet() and doPost() method of TestServlet. Which of t
he statement is correct? image | c. This will work for HTTP GET as well as POST
requests.
Which is NOT true about stateless session beans? | c. They are used to represent
data stored in a RDBMS
Which is NOT a correct statement about entity beans? | c. They are used to imple
ment business processes
Which is a valid PostConstruct method in a message-driven bean class? | c. @Post
Construct private void init() {}
Which is true about JEE ( or J2EE)? | c. JEE includes servlet APIs and EJB APIs
EJB 3.0 specifications are first implemented in ________ | c. Java EE 5
Which statements are BEST describe taglib directive of JSP file? | c. Allows pro
grammers to include their own new tags in the form of tag libraries. These libra
ries can be used to encapsulate functionality and simplify the coding of a JSP.
Which is NOT represented in a UML class diagram? | c. The interaction between ob
jects in sequential order
Which is NOT true about stateless session beans? | c. They are used to represent
data stored in a RDBMS
What do you need to create a EJB3 session bean? | c. Annotate the session bean w
ith @Stateful or @Stateless
Which of the following are valid iteration mechanisms in jsp? | c. <% int i = 0;
for(;i<5; i++){ %>"Hello World";<% i++;}%>
Which of the following constitute valid ways of importing Java classes into JSP
page source? | c. <%@ page import="java.util.*" %>
A developer is working on a project that includes both EJB 2.1 and EJB 3.0 sessi
on beans. A lot of business logic has been implemented and tested in these EJB 2
.1 session beans. Some EJB 3.0 session beans need to access this business logic.
Which design approach can achieve this requirement? | c. No need to modify exis
ting EJB 2.1 session beans. Use the @EJB annotation to inject a reference to the
EJB 2.1 home interface into the EJB 3.0 bean class.
Which statement is true about the use of a persist operation in a transaction of
an Entity Beans | c. If a user persists a new entity with an existing primary k
ey the transaction will fail
What is the purpose of JNDI? | d. To access various directory services using a s
ingle interface
Which statement about an entity instance lifecycle is correct? | d. A managed en
tity instance is the instance associated with a persistence context.
A Java programmer wants to develop a browser-based multitier application for a l
arge bank. Which Java edition (or editions) should be used to develop this syste
m? | d. J2SE and J2EE
A Java developer needs to be able to send email, containing XML attachments, usi
ng SMTP. Which JEE (J2EE) technology provides this capability? | d. JavaMail
A Java developer needs to be able to send email, containing XML attachments, usi
ng SMTP. Which JEE (J2EE) technology provides this capability? | d. JavaMail
Which is NOT responsibility of the business tier in a multitier web-based applic
ation with web, business, and EIS tiers? | d. To generate dynamic content
Which is NOT associated with the web tier in a JEE (J2EE) web-based application?
| d. Message-driven beans
Which technology is used for processing HTTP requests and mapping those requests
to business objects | d. Servlets
What would be the best directory in which to store a supporting JAR file for a w
eb application? Note that in the list below, all directories begin from the cont
ext root. | d. \WEB-INF\lib
A developer is working on a user registration application using EJB 3.0. A busin
ess method registerUser in stateless session bean RegistrationBean performs the
user registration. The registerUser method executes in a transaction context sta
rted by the client. If some invalid user data causes the registration to fail, t
he client invokes registerUser again with corrected data using the same transact
ion. Which design can meet this requirement? | d. Create an application exceptio
n with the rollback attribute set to false and have registerUser method throw it
after registration fails.
Which statement about an entity instance lifecycle is correct? | d. A managed en
tity instance is the instance associated with a persistence context.
A developer is working on a user registration application using EJB 3.0. A busin
ess method registerUser in stateless session bean RegistrationBean performs the
user registration. The registerUser method executes in a transaction context sta
rted by the client. If some invalid user data causes the registration to fail, t
he client invokes registerUser again with corrected data using the same transact
ion. Which design can meet this requirement? | d. Create an application exceptio
n with the rollback attribute set to false and have registerUser method throw it
after registration fails.
Which of the following is correct? Select one correct answer | d. To use the ch
aracter %> inside a scriptlet, you may use %\> instead.
Which of the following is NOT a standard technique for providing a sense of "sta
te" to HTTP? | d. HTTP is already a stateful protocol.
Which statements are BEST describe response implicit object of jsp file? | d. Th
is object represents the response to the client. The object normally is an insta
nce of a class that implements HttpServletResponse (package javax.servlet.http).
If a protocol other than HTTP is used, this object is an instance of a class th
at implements javax.servlet.ServletResponse.
Which of the following method calls can be used to retrieve an object from the s
ession that was stored using the name "userid"? | d. getAttribute("userid");
Identify the method used to get an object available in a session. (Choose one)
| d. getAttribute of HttpSession
A developer wants to use the Java Persistence query language. Which statement is
true? | d. The WHERE clause is used to restrict the contents of a collection of
objects that are returned from a query.
A developer wants to create a Java Persistence query that returns valid US phone
numbers (formatted as 123-456-7890) from a collection of differently formatted
international phone numbers. The developer needs only those numbers that begin w
ith 303. Which WHERE clause is correct? | d. WHERE addr.phone LIKE '303-___-____
'
Which is NOT associated with the web tier in a JEE (J2EE) web-based application?
| d. Message-driven beans
A Java developer needs to be able to send email, containing XML attachments, usi
ng SMTP. Which JEE (J2EE) technology provides this capability? | d. JavaMail
Which of these is true about include directive? Select the one correct answer.
| d. When using the include directive, the JSP container treats the file to be i
ncluded as if it was part of the original file.
Which statement about an entity instance lifecycle is correct? | d. A managed en
tity instance is the instance associated with a persistence context.
Which statements are BEST describe request implicit object of jsp file? | e. Thi
s object represents the client request. The object normally is an instance of a
class that implements HttpServletRequest (package javax.servlet.http). If a prot
ocol other than HTTP is used, this object is an instance of a subclass of javax.
servlet.ServletRequest.
Which is NOT a scope of implicit objects of JSP file? | e. response
Which is NOT a state in the EJB 3 Entity beans life cycle states? | e. Exit
Which of the following JSP variable is not available within a JSP expression? Se
lect one correct answer | e. httpsession
Identify the correct element is required for a valid <taglib> tag in web.xml (Ch
oose one) | e. <taglib-uri>
Which is NOT a state in the EJB 3 Entity beans life cycle states? | e. Exit
In which layer of the JDBC architecture does the JDBC-ODBC bridge reside?|It res
ides in the JDBC layer.
Which of the following is NOT a benefit of using JDBC?|JDBC programs are tightly
integrated with the server operating system.
In JDBC API, which of the following statements can be used to call a stored proc
edure?|CallableStatement
When you want to delete some rows in a table of a database, the method of the jav
a.sql.Statement interface must be used.|executeUpdate()
The next() method of the java.sql.ResultSet class return |a boolean value.
The . method of the class helps loading a JDBC driver.|forName( ), java.lang.Class
In JDBC, which of the following class/interface should be used to call a store p
rocedure?|CallableStatement
You are going to execute an insert statement to add some data into the database.
Which of the following methods should you use?|executeUpdate()
You are required to build an application that connects to database to store and
retrieve data. Your application must be independent with the underlying database
. Which driver types should you use?|Type 3-driver
In JDBC model, which driver types provide access to database through native code
libraries C/C++?|Type 2-driver
In a JDBC application, suppose that the Connection, named con, was created. Stud
y the following code:String sql= select * from Students ;|The above code will throw
an exception.
Suppose that you will insert a lot of rows into a database table row-by-row. Whi
ch of the following interfaces should be used?|PreparedStatement
One of the benefits of Type 1 driver (JDBC ODBC Bridge) is that it can provide c
onnection to a database when Java driver is not available for that database. Whi
ch of the following options is another advantage of the Type 1 driver?|None of t
he others
You are required to build an application that can connect to database to display
data to end users. The requirement for the database connectivity is that it mus
t provide a performance as fast as possible.
Suppose that all types of drivers are available. Which type should you choose to
satisfy the requirement?|Type 2
The default type of the ResultSet object is ____.|TYPE_FORWARD_ONLY
If you want execute a SQL statement many times, the ____ object should be used.|
If you want execute a SQL statement many times, the ____ object should be used.
The JDBC API supports processing models for database access.|two-tier and three-
tier models
With respect to processing models for database access, ____|In the two-tier mode
l, a Java application talks directly to the data source.
Suppose that the current position of a ResultSet, named rs, is at the last recor
d, the statement rs.next() will return |false
Which of the following statements is correct regarding Type 4 JDBC driver (Nativ
e Protocol)?|It helps the Java applications communicate directly with the databa
se using Java sockets.
The first in the most common objects are used in a database Java program: (1) ja
va.sql.Connection|(1)
The Java program can .........|not directly access data in a database file that
is managed by a database management system.
Statement objects return SQL query results as ___ objects.|ResultSet
______________ drivers that implement the JDBC API as a mapping to another data
access API, such as ODBC. Drivers of this type are generally dependent on a nati
ve library, which limits their portability.|Type 1
Which JDBC processing model that requires a JDBC driver that can communicate wit
h the particular data source being accessed?|two-tier
With respect to the java.sql.Statement interface,(1) When we need retrieving dat
a from a table of a database, the method of the Statement interface should be used
.|executeQuery( ), executeUpdate( )
The correct order in which database -accessing objects should be created: |Conne
ction Statement- ResultSet ResultSetMetaData
With respect to JDBC,(1) In the two-tier model, a Java application talks directl
y to the data source.|True, true, false
The default type of the ResultSet object is ...|TYPE_FORWARD_ONLY
The ... object contains not just an SQL statement, but an SQL statement that has
been precompiled.|PreparedStatement
With respect to processing models for database access, in the ... model, a Java
application talks directly to the data source.|Two-tier
A/An is bound to a port number so that the TCP layer can identify the application
having network comunication|socket
Select a correct statement about TCP and UDP protocol:|TCP (Transmission Control
Protocol) is a connection-based protocol that provides a reliable flow of data
between two computers.
You are trying to look up obj1 object on the server 192.168.12.1 using RMI techn
ology with default port.
Select a correct statement below:|Naming.lookup("rmi://192.168.12.1/obj1") ;
Consider the following url address:http://192.168.2.2:12/users/index.html Select
a correct statement:|http is protocol, 192.168.2.2:12 is socket.
In a client-server application model, which side will initialize a connection?|C
lient
Select correct statement. In RMI implementations,|the remote class must implemen
t the remote inteface.
With respect to the Java RMI, a server and a client program .|can run in two separ
ate virtual machines.
Which of the following options is a valid method that is used to bind a name to
an object in RMI model?|Naming.rebind(name, object);
You are building an rmi application. Which of the following interfaces you must
extend for your remote interface?|java.rmi.Remote
In RMI Architecture, which of the following components is reponsible for storing
a mapping between a specific name and a remote object?|RMI registry
A(An) ... . is one endpoint of a two-way communication link between two programs r
unning on the network.|socket
Two streams in a Java socket are .|Binary streams
Which of the following protocols is a reliable protocol?|TCP
Which of the following statements is correct?|Basically, RMI technology uses tra
ditional sockets but socket classes are created invisibly to developers.
Suppose you are building a client server based application using TCP socket |The
server creates a separate InputStream and OutputStream objects for each one. Th
en,
In a client-server application model, which side will wait for a connection?|ser
ver
In Java Network programming using sockets, five steps are usually used: 1) Open
a socket. 2) Open an input stream and output stream to the socket. |1, 2, 3, 4,
5
Select correct statement. In RMI implementations, _____|The remote class must im
plement the remote inteface.
In RMI implementations, all methods, declared in the remote interface, must thro
w the ____ exception.|java.rmi.RemoteException
RMI applications often comprise two separate programs, a server and a client and
they _________.|can run in two separate virtual machines
What is the role of RMI registry?|The RMI registry is a program that associates
names with RMI services.
Which of the following statement is correct about object serialization?|Transien
t fields are not serialized.
To implement RMI, classes need to be implemented: (1) Remote interface, (2) Serv
er object, (3) Server program, (4) Client program,|1, 2, 3, 4, 5
Two streams are packed in a socket are .........|InputStream and OutputStream
Select correct statements about remote interface. (choose 1)|All of the others.
Select correct statement about RMI. (choose 1)|All of the others.
Select incorrect statement about ServerSocket class. (choose 1)|To make the new
object available for client connections, call its accept() method, which returns
an
In Windows systems, the program helps creating the Stub of a RMI server and the pr
ogram will work as a RMI container (RMI registry). |rmic.exe, rmiregistry.exe
With respect to steps in RMI implementation.(1) Create the remote interface|1, 2
, 4, 3
With respect to networking and the client-server model. (1) A socket is one endp
oint (a combination of an IP address and a port number) |True, true, true
With respect to networking and the client-server model. (1) A server runs on a s
pecific computer and has a socket that is bound to a |True, true.
In a client-server application model, which sides will initiate a connection?|Cl
ient
With respect to the Java socket. (1) A socket contains two binary streams for se
nding and receiving data. |True, false, false
In RMI implementations, all methods, declared in the remote interface, must thro
w the ...exception.|java.rmi.RemoteException
RMI applications often comprise two separate programs, a server and a client and
they...|Can run in two separate virtual machines
Which of the following layout managers subdivides its territory into a matrix of
rows and columns?|Grid Layout
Which of the following layout managers arranges components in horizontal rows (l
eft to right in the order they were added to their container)|Flow Layout
Which of the following layout classes is in java.awt package?|All of the others.
The default layout manager used by JPanel is:|FlowLayout
To make the background color of a label different with the color of its containe
r, we need to use the .. method of the JLabel class first.|setOpaque(true)
A swing container that groups some common components in a complex GUI.|JPanel
Which method do you use to force the prompt to a textfield ?|Textfield.requestFo
cus()
Which of the following statements is not correct about JTree control?|Which of t
he following statements is not correct about JTree control?
You are building a table model class that extends the AbstractTableModel class.
Which of the following methods is not required to re-implement?|getColumnName()
Which of the following options is a method that you need to override when implem
enting the ActionListener interface?|actionPerformed()
Suppose you are building an application that connects to the database to store a
nd retreive data. Your application is built based|Model.
Suppose that the layout of the frame f is BorderLayout. Study the following stat
ement:|None of the others.
You are required to build a GUI application. The application has a main window w
hich displays:|You are required to build a GUI application. The application has
a main
Which of the following layout managers will make all its components the same siz
e?|GridLayout
In JTree control, which of the following classes represents for one node?|Defaul
tMutableTreeNode
A component that displays an icon, but that doesn t react to user clicks|label
The container has a row of components that should all be displayed at the same s
ize, filling the container s entire area|GridLayout
The container has one component that should take up as much space as possible. W
hich layouts that easily deal with this|BorderLayout or GridLayout
A component that lets the user pick a color.| color chooser
Which method do you use to enable and disable components such as JButton s?|setE
nable
Which of the following statement is correct about Card layout?|Card layout arran
ges components in time rather than in space.
Which of the following statements is correct about Flow layout?|The Flow layout
arranges frames in horizontal rows.
Suppose that we have a combobox that contains a list of data. The combobox can o
nly display to the user one item at a time|The list of data of the combobox can
be
In Swing, what is the role of the component s model?|It is responsible for the dat
a that the component presents to the users.
Select an incorrect statement.|A combobox can contain strings only.
We can replace a card layout of a container with ..........|tabbed pane
In a complex GUI containing a lot of components and user must be select some dat
a in a group of specific data, the component should be used is .......|combo box
Select incorrect statement about FlowLayout. (choose 1)|It is the default layout
manager type for JFrame.
The container can display three completely different components at different tim
es, depending perhaps on user input or program state.|CardLayout
The border layout resizes the ______ components to fill the remaining centre spa
ce.|Center
A _____ dialog prevents user input to other windows in the application unitl the
dialog is closed.|Modal
The Swing component classes can be found in the ________________ package.|javax.
swing
Which is four-step approach to help you organize your GUI thinking. (Choose one.
)|Identify needed components.Isolate regions of behavior.Sketch the GUI.
Choose layout managers(1) 12 buttons can not be added to a container which is as
signed to a grid layout 2x5.|None of the others.
Which of the following layout manager will present components with the same size
. |java.awt.GridLayout
Select correct statement(s).(1) The Swing's list component (JList) can display t
ext only.|3
Select correct statement(s).(1) Swing is part of the Java Foundation Classes and
provides a rich set of GUI components.|1, 2
Which component can display an image, but cannot get focus?|JLabel
The container has one component that should take up as much space as possible. W
hich layouts that easily deal with this situation should be selected?|GridLayout
A component that lets the user pick a color.|JColorChooser
Which method do you use to enable or disable components such as JButtons?|None o
f the others
Select a characteristic that is not supported by the Java language? | procedure-
oriented.
Select an incorrect identifier in Java. | &x
(1) A value variable contains data's value. (2) A reference variable contains th
e address of data. The statement (1) is ___, and the statement (2) is___ |True,
true
Select the output of the following Java code: System.out.print(1>>10); System.ou
t.print(-1>>20); | 0-1
The Java language supports: | All of the others.
A Java source code will be compiled to | Java bytecode.
Study the following Java code:int[] a= {1,2,3,4};int b=1;a[b]=b=3;If the code is
executed, the array contains values: | { 1, 3, 3, 4 }
If all three top-level elements occur in a source file, they must appear in whic
h order? | Package declaration, imports, class/interface/enum definitions.
How can you force garbage collection of an object? | Garbage collection cannot b
e forced.
What is the return type of the instanceof operator? | A boolean.
Comparison operators in Java language return ..... | a Boolean value.
Suppose that a, and b are single dimensional arrays of integers, index1 and inde
x2 are valid indexes. Study the following statements: (1) a[index1]= b[index2] ;
(2) a=b; |Both (1) and (2) are accepted.
What is an identifier? |A word used by a developer to name a variable, a method,
a class, or a label
Select a correct Java declaration: | int $myInt;
A Java source code is a file with the file extension is . |.java
A Java source code will be compiled to the file with file extension is |.class
A reference variable can not be ..|an integral value.
With respect to rules and conventions for naming variables in Java, select an in
correct statement. |None of the others.
Select a wrong declaration:|None of the others.
Select a correct template of a Java source file.|package mypkg;import java.lang.
*; class A { // class members }
Which of the following is not a primitive data type in Java language?|String
Suppose that the folowing Java code executes. What is the value of the result of
variable.int x= -7, y=3; int result= x%y; |-2
Which of the following declarations is not correct?|int x = 0A;
Which of the following commands is valid to execute a java byte-code file?|java
myPackage.MyClassFile
Which of the following operators will shift all bit values to the right and fill
the empty bits on the left end with 0s?|>>>
Consider the following operands and result:11001110 (Operand 1: )11110001(Operan
d 2)00111111(Result) Which of the following operators can create the above resul
t?|XOR
Which of the following options is not a Java characteristic?|Platform dependent
Which of the following commands is used to compile java source code into java by
tecode?|javac
Files containing java bytecode have the extension as:|.class
Consider the following expression:0000 0000 0000 0011 A 0000 0000 0000 0100 = BI
f A is XOR operator, then B will be:|0000 0000 0000 0111
Select an incorrect statement.|In a Java soure code, the first code line must be
a class declaration.
Study the following Java code:int [] a= { 1, 2, 3, 4, 5 };Select the best choice
. |The variable a is a reference to a memory location that stores values.
Study the following Java code:byte x= 5;byte y= 5<<1;Suppose that the above code
is executed, the variable y will store a binary value as | 00001010
Which of the following features Java does not suppor|Insecure
If we have a java class name as follows:public class MyClass {}When the above cl
ass is compiled successfully, which of the following files contains the java byt
ecode?|MyClass.class
Consider the following declaration:int 3_my_var = 0x1c;Select a correct statemen
t:|The statement is incorrect because a variable declaration cannot start with a
number.
Select the incorrect declaration.|double f = d32;
With respect to access modifier overridden, the right order is:|private, protect
ed, default, public
Which modifiers on instance variables will announce to the compiler that these v
ariables are not stored as part of its object's persistent state.|transient
Select an operation which may cause an unchecked exception.|Select an operation
which may cause an unchecked exception.|Accessing an element of an array.
Select the correct syntax for throwing an exception when declaring a method.|[Mo
difier] {Return type] Identifier (Parameters) throws TypeOfException
Select incorrect Java program entry point declarations.(1) public static void ma
in()(2) public static void main(String [] args)(3) public static void main(Strin
g args[])(4) public static void main(string [] args)(5) public static void main(
String args)|1, 4, 5
Select correct statements.(1) A public member of a class can be accessed in all
classes.(2) A default member of a class can be accessed in all classes.(3) A pro
tected member of a class can be accessed in the package containing this class.(4
) A private member of a class can be accessed in the package containing this cla
ss.|1, 3
Which of the following Java operations cause compile-time errors?int m=5, n=7;fl
oat x = m; //1double y= n; //2 m = y; // 3 n = x; // 4 |3, 4
If the following code is executed. What is the output?int[] a= {1,2,3,4};System.
out.println(a[6]); |ArrayIndexOutOfBoundsException
If a Java source code contains an assert as an identifier and it will be compile
d with JDK version 1.4 or higher, . |The option source 1.4 must be specified when it
is compiled.
Which of the following statements are true?1)An abstract class can not have any
final methods.2)A final class may not have any abstract methods.|Only statement
2.
When a negative byte is cast to a long, what are the possible values of the resu
lt?|Negative value.
Suppose a method called finallyTest() method consisting of a try block, followed
by a catch block, followed by a finally block. Assuming the JVM doesn t crash and
the code does not execute a System.exit() call, under what circumstances will t
he finally block not begin to execute?|If the JVM doesn't crash and the code doe
s not execute a System.exit() call, the finally block will always execute.
Java compiler allows .|Implicit widening conversions.
Errors beyond the control of a program are called .........|Exceptions
What is NOT a unary operator?|/
What is NOT a comparison operator?|>>
A method in a super class is implemented using the default modifier, this method
can not be overridden in subclasses using the .. modifier.|private
A . method is implemented in a super class can not be overridden in derived class
es.|final
The try catch statements must be used to contain statements that |may cause checked
exceptions.
Which of the following modifiers is not an access modifier?|final
Which of the following declarations is not correct?|public protected String mySt
ring;
Which of the following statement is not correct about default access modifier?|T
o declare a variable that have default access modifier, we use the default keywo
rd. For example: default String myString;
Which of the following statement is NOT correct about protected access modifier?
|Protected variables of a class can only be accessed by its sub-class in the sam
e package
int x=2; //1long z=3; //2double t=5.4;//3x=t; //4z=x; //5Which statement causes
an error? |The statements (4) and (5).
Which of the following declarations is not valid?|private int[] ar3 = new int[2]
{1, 2};
Which of the following modifiers can assure that a class is not inherited by oth
er classes?|final
The protected modifier cannot be applied to which of the following declarations?
|static class A { }
Which of the following modifiers is valid for a constructor?|private
Which of the following modifiers does not allow a method to be overridden?|final
Which of the following access modifiers does not allow a class to be accessed ou
tsite its package?|default
When handling exceptions, how many catch{} blocks can be used for one try{} bloc
k?|None of the others
Which of the following statements is correct?|For value types, narrowing convers
ion is not allowed.
The default access modifier in Java is .|None of the others.
The private and protected modifiers are not applied on .....|class
Study the following Java code:int n= 256;byte x= (byte) n;Suppose that the above
code is executed, the value of the variable x is |0
Which of the following modifiers cannot be applied for a class?|protected
Which of the following modifiers cannot be applied for interface and abstract cl
asses?|protected
Which of the following access modifiers makes a class cannot be inherited?|final
Which of the following modifiers makes a variable can be modified asynchronously
?|volatile
The protected modifier can not be applied to...|Class
Which of the following statements is not a reason for using nested classes?|It s
upports a way for easily creating an object that is declared in an enclosing cla
ss declaration.
Select a correct statement about interfaces.|In its most common form, an interfa
ce is a group of related methods with empty bodies.
Select a correct statement.|None of the others.
. is applied in a class. . is applied in a class hierarchy.|Method overloading, method
overriding.
An abstract class |can contain all concrete methods.
An interface can contain .. |Constants.
Suppose that the class A contains an inner class, named B. In a method of A, to
access data of a B object, |The B object must be referred by a reference declared
in A.
Suppose x and y are of type TrafficLightState, which is an enum. What is the bes
t way to test whether x and y refer to the same constant? (Choose one.)|if (x ==
y)
Suppose class X contains the following method:void doSomething(int a, float b) {
}Which of the following methods may appear in class Y, which extends X? (Choose
one.)|public void doSomething(int a, float b) { }
Which of the following restrictions apply to anonymous inner classes? (Choose on
e) .|They must be defined inside a code block.
Which of the following may override a method whose signature is void xyz(float f
)?|public void xyz(float f)
We can ......|All of the others.
In a subclass, a calling to a constructor of superclass .......|must be the firs
t line in a constructor of the subclass.
What does the default modifier mean?|It provides access to any class in the same
package.
Which statement is correct about protected modifier?|Only variables and methods
may be declared as protected members.
In Java, .....|All of the others.
Suppose that A, B, C are classes in which B is a subclass of A. Study the follow
ing declarations:A objA;B objB;C objC; Select a valid statement.|objA=objB;
The re-use code ability is a result of the in OOP.|inheritance
Real-world objects share two characteristics: They all have state and behavior.
Software objects are conceptually similar to real-world objects: they too consis
t of state and related behavior. A software object stores its state in _____ and
exposes its behavior through ______.|fields, methods
Object-oriented programming allows classes to ____ commonly used state and behav
ior from other classes. In Java, the ____ keyword is used to declare a subclass
of another class. |inherit, extends
The term "instance variable" is another name for ____, and the term "class varia
ble" is another name for _____.|non-static field, static field
Which of the following statements is not a reason for using nested classes?|None
of the others.
Select correct statement about interfaces.|In its most common form, an interface
is a group of related methods with empty bodies
In OOP, which of the following statements is correct in terms of cohesion?|Each
method should perform one specific task only.
Consider the following piece of code:import javax.swing.JTextField; class Counte
r { int count=0; void increment() { count++; } void reset() { count=0; } JTextFi
eld txt= new JTextField(); void display() { // display the count txt.setText( Coun
ter: + count); } } The bove code is an example of ......|tight coupling
You are assigned a job that you need to buy a lock to replace the old one in you
r company. A lock-set includes 2 components: a lock and a key. Each key can only
fit one lock. A key and a lock is an example of |tight coupling
Which of the following statements is not true in terms of overriding methods?|An
overriding method (in sub-class) can throw any checked exception (or subclasses
of those exceptions) that are not declared in the overridden method (in supper-
class).
Which of the following statements is correct about overloading methods?|Overload
ing methods are implemented in the same class
Which of the following statements is correct about overridding methods?|Each par
ent class method may be overridden once at most in any one subclass.
Which of the following options we try to achieve while designing object oriented
software?|Low coupling
Which of the following statements is correct?|Outer class must contain an instan
ce of the inner class before accessing members of the inner class.
A software object stores its state in .. and exposes its behaviors through ...|Fie
lds, methods
In a class, non static fields are called as .., and static fileds are called as .|In
stance variables, class variables
With respect to Java, select a correct statement about interfaces.|None of the o
thers.
Select a correct statement about encapsulation implementation in OOP:|All of the
others
Consider the following class:class MyClass {void myFunction(){}int myFunction()
{return 0;}}Select a correct statement about MyClass.|MyClass has a compile erro
r.
Which of the following methods can be used to call a constructor of a father cla
ss from the sub-class?|super()
Select an incorrect statement about inner classes:|An inner class cannot be decl
ared inside a method of the outer class.
... exist within a ... Every ... has at least one...|Threads, process, process,
thread
Multithreaded execution is an essential feature of the Java platform. Every appl
ication has at least ... thread(s).|None of the others
An application that creates an instance of Thread must provide the code that wil
l run in that thread. Select a correct way to do this.|Provide a Runnable object
. The Runnable object is passed to the Thread constructor.
if an object is visible to more than one thread, all reads or writes to that obj
ect's variables should be done through ... methods.|None of the others
Select correct statement(s).(1) A process has a self-contained execution environ
ment.(2) A sub-thread has a self-contained execution environment.(3) Programmers
can schedule sub-threads of a program. |1
Two sub-threads of a program may not need synchronized if |They do not access any
common resource.
Select correct statement(s):(1) A thread can be an instance of the java.lang.Thr
ead class.(2) A thread can be an instance of a subclass of the java.lang.Thread
class.(3) An instance of a class which implements the java.lang.Runnable can sup
ply the executable code for a thread object. |1, 2, 3
(1) An object having synchronized methods is called a( an ) .(2) The technique can b
applied with a hope that a deadlock situation may not occur in a program .(3) T
he sleep( ) method of the java.lang.Thread class accepts a argument that specifie
s a( an ) . |Monitor, wait-notify, specific period of time.
A thread s run() method includes the following lines:1. try {2. sleep(100);3. } ca
tch (InterruptedException e) { }Assuming the thread is not interrupted, which on
e of the following statements is correct?|At line 2, the thread will stop runnin
g. It will resume running some time after 100 milliseconds have elapsed.
A monitor called mon has 10 threads in its waiting pool; all these waiting threa
ds have the same priority. One of the threads is thr1. How can you notify thr1 s
o that it alone moves from the Waiting state to the Ready state? (Choose one).|Y
ou cannot specify which thread will get notified.
Which of the following methods in the Thread class are deprecated? (Choose one)|
suspend() and resume()
Which of the following statements about threads is true? (Choose one.)|Threads i
nherit their priority from their parent thread.
As soon as a Java thread is created, it enters the .. state.|ready
Thread synchronization should be implemented if .....|Threads access common reso
urces.
Which of the following statements is correct about Thread?|During its lifetime,
a thread spends some time executing and some time in any of non-executing states
.
Which of the following statement is correct about Thread?|When the run() method
of a thread returns, that thread is put into ready state.
Which method is NOT a member the Object class?|waitAll()
When a thread begins waiting an IO operation, it enters the .. state.|blocked
In multi-processing system,|Each process usually accesses its own data.
_____ exist within a ____ - every _____ has at least one.|Theads, process, proce
ss.
Multithreaded execution is an essential feature of the Java platform. Every appl
ication has at least _____ thread(s).|one
An application that creates an instance of Thread must provide the code that wil
l run in that thread. Select a correct way to do this.|Provide a Runnable object
. The Runnable object is passed to the Thread constructor.
if an object is visible to more than one thread, all reads or writes to that obj
ect's variables should be done through ____ methods.|synchronized
Select a correct statement.|Deadlock describes a situation where two or more thr
eads are blocked forever, waiting for each other.
Which of the following statements is true?|A thread must obtain the lock of the
object it is trying to invoke a synchronized method.
Which of the following methods causes a thread to release the lock of the object
that it is currently holding?|wait()
The muti-threaded programming is used .|when some tasks must be performed concurre
ntly.
The muti-threaded programming is used .|when a task must be performed at un-predic
table time.
Race condition may happen when:|More than one threads access the shared data of
the application.
To create a thread in Java, we can:|Create a subclass of the java.lang.Thread cl
ass and override the method run().
Select correct priority values of a thread (Integer values only):|From 1 to 10
Which of the following options is not a thread state?|Indelayed
With respect to threads in Java, select a correct statement.|The main method (en
try point of a Java program) is a default thread.
if an object may be accessed by some threads. These accesses should be done thro
ugh ____ methods.|Synchronized
Select the best choice.|Deadlock describes a situation where two or more threads
are blocked forever, waiting for each other.
Race condition may happen if:|There is more than one threads access the shared d
ata of the application.
Which of the following options is not a valid thread priority property?|AVERAGE_
PRIORITY
When is a thread considered as a dead thread?|When the run() method terminates.
When is a thread started running?|The Scheduler decides when a thread is started
running.
The Java Collection framework is implemented in the ...package.|None of the othe
rs.
In order to use the TreeSet class, the class that describes elements must implem
ent the ... interface.|java.lang.Comparable
All of the numeric wrapper classes in the java.lang package are subclasses of th
e abstract class ...|java.lang.Number
String S= "Hello"; String S2= new String("Java Program"); The String class descr
ibes an immutable chain of Unicode characters. Select a statement that causes an
error.|None of the others.
Study the following code was implemented in the Hello class:
static void print(Integer obj){
System.out.println(obj);
}
And it is used as:Integer obj= new Integer(5); int n= obj; //(1) Hello.print( n
); //(2) A .. operation is carried out at the code line (1)A .. operation is ca
rried out at the code line (2) |Unboxing, boxing
The top interface of the Java Collection Framework is . |Collection
If we want to store a group of different elements in ascending order, the java.u
til. class should be used. |SortedSet
An instance of the java.util.Scanner class can read data from the keyboard (1),
a file (2), a string of characters (3).(1) is ., (2) is ., and (3) is ..|true, true,
ue
Given a string constructed by calling s = new String( "xyzzy" ), which of the ca
lls modifies the string? (Choose one.)|None of the others.
Which one statement is true about the following code?1. String s1 = "abc" + "def
";2. String s2 = new String(s1);3. if (s1 == s2)4. System.out.println("== succee
ded");5. if (s1.equals(s2))6. System.out.println(".equals() succeeded");|Line 6
executes and line 4 does not.
Which one statement is true about the following code fragment? (choose 1)1. impo
rt java.lang.Math;2. Math myMath = new Math();3. System.out.println("cosine of 0
.123 = " + myMath.cos( 0.123 ) ); |Compilation fails at line 2.
Suppose prim is an int and wrapped is an Integer. Which of the following are leg
al Java statements? (Choose one.)|All the others.
Suppose that obj1 and obj2 are objects and they belong to the same class. Study
the semantics of following statements: (1) if (obj1==obj2) { } (2) if (obj1.equa
ls( obj2 )) { } |(1) and (2) are different.
A characteristic of generic technique is ......|It adds stability to the code by
making more of bugs detectable at compile time.
Suppose that obj1 and obj2 are reference variables. The expression obj1==obj2 wi
ll execute |a swallow comparison.
One of the difference about Lists and Sets:|A list can contain duplicate items b
ut a set can not.
Study the following Java statements: String s1= Hello ; String s2= Hello ; String s3= H
ello ;|There is only one string is stored in memory of the program.
Study the following Java statements:String S= William, Bill is ill. ; int index1= S
.indexOf( ill ); int index2= S.lastIndexOf( ill ); The value of index1 is .. and index2 i
s |1, 17
To traverse elements in a set, one after one element, the java.util. .interface mus
t be use.|Iterator
The _____ class is the ultimate ancestor of all Java classes.|Object
The Java Collection framework is implemented in the ______ package.|java.util
In order to use the TreeSet class, the class that describes elements must implem
ent the ______ interface.|java.lang.Comparable
All of the numeric wrapper classes are subclasses of the abstract class ______.|
Number
String S= Hello ;String S2= new String( Hello );The String class describes an immutable
chain of Unicode characters. Select a statement that causes an error.|None of t
he others.
When invoking Math.random(), which of the following options might be the result?
|The result is less than 1.0
Which of the following statements is true about Object class?|By default, the eq
uals() method simply performs the == operator
Which of the following classes will you choose to deal with string data type to
achieve the above requirements?|StringBuilder
Suppose that a homogenous collection of objects, that belong the same type, are
managed. Which of the following delarations is the best choice?|java.util.ArrayL
ist list;
Which of the following options is correct?|Values stored in TreeSet are not allo
wed duplication
Which of the following options is not a method of the Scanner class?|nextValue()
Which of the following collection cannot be used with Iterator class to traverse
through elements?|Array
Which of the following options is not a method of java.lang.Math Class?|None of
the others
Which of the following classes is the ultimate ancestor of all Java classes?|Non
e of the others
In Java Collection framework, which of the following pre-defined classes allow a
n element can be accessed through its index?|java.util.ArrayList
In which situation are generic collections used?|The collection contains homogen
ous elements.
Which of the following Java lists that allows data is stored in sorted order, an
d also, no duplicate data is allowed?|TreeSet
Which of the following methods can be used to achieve the above task?|Collection
s.shuffle()
You are required to validate an email string taken from users. A valid email for
m should be email@address.com.|"^\w+@\w+[.]\w+$"
If we use Math.random() method to random a number, which of the following number
s will never be appeared?|1.0
An I/O Stream represents an input source or an output destination. A stream can
represent...|All of the other choices.
The java.io.ObjectInputStream class is a subclass of the ...class.|java.io.Input
Stream
Select a correct statement.|All of the others.
When reading objects from an object stream,|we usually use an explicit casting.
Select correct statement(s).|1, 2
To read data from a text file using the line-by-line accessing. The right order
of object creations is: |File FileReader - BufferedReader
To write objects to an object file. The right order of object creations is: |Fil
eOutputStream- ObjectOutputStream
(1) The java.io . class makes it easier to write platform-independent code that ex
amines and manipulates files.|File, File
How do you use the File class to list the contents of a directory? (Choose one.)
|String[] contents = myFile.list();
Which of the following is true? (Choose one.)|None of the others
Given the following class:|iAmPublic, iAmPrivate
Which of the following are true?|All of the others.
When we access a file or directory metadata such as name, path, last modified ti
me, We should use the ........... class.|java.io.File
Suppose that you want reading some records stored in a text file, classes in the
java.io package can be used: |(1), (4), (5)
Consider the following declaration: RandomAccessFile(File file, String mode) If
the mode is declared as rws , what does it mean?|It means the file can be opened fo
r both reading and writing, and any changes to the file s content or metadata will
take place immediately.
Consider the following declaration: |It means the file can be opened for both re
ading and writing, and any changes to the file s content, but not its metadata, wi
ll take place immediately.
Two topmost abstract classes for character streams are ... and .|java.io.Reader, ja
va.io.Writer
The . class makes utilities to write platform-independent code that examines and m
anipulates folders.|java.io.File
To read/write objects from/to a file as object streams, the class declaration of
these objects must implement the marker interface ..|java.io.Serializable
An I/O Stream represents an input source or an output destination. A stream can
represent ____.|All of the others
In _____ binary streams, a read/write data unit is _______.|low-level, general-f
ormat data
The ObjectInputStream is a subclass of the _____ class.|InputStream
Select a correct statement.|All of the others.
When reading objects from an object stream, we usually use _____.|an explicit cl
ass casting
Which of the following options is not a valid declaration of the RandomAccessFil
e class?|RandomAccessFile r = new RandomAccessFile( file.txt , w );
In order to allow an object can be serialized into a file, which of the followin
g interfaces needs to be implemented?|java.io.Serializable
You are required to write a program that stores data retrieved from users to a t
ext file. The data must be stored line by line and in Unicode format. Which of t
he following classes is the best choice for storing tasks?|java.io.PrintWriter
Which of the following classes is not an abstract class?|None of the others.
We have the constructor of the java.io.RandomAccessFile class as follows: Random
AccessFile(String file, String mode)| w
Which of the following classes do not directly read from/write to input/output d
evices such as disk files or sockets; rather, they read from/write to other stre
ams? |DataInputStream/ DataOutputStream
Which of the following classes can be used to serialize an object into a file?|O
bjectOutputStream
Which of the following methods of the File class can be used to get the size of
a given file?|length()
A stream can represent .|All of the others.
The ObjectInputStream is a subclass of the . class.|None of the other.
When accessing objects in an object stream, we must .|Access them using a suitable
program.
Which of the following features is not supported by java.io.RandomAccessFile cla
ss?|Reading and writing data from and to a socket
You use java.io.RandomAccessFile to manipulate a file name myFile.txt. Which of
the following statements is valid if you want to open the file myFile.txt in a w
riting-only mode?|There is no writing-only mode in java.io.RandomAccessFile clas
s.
Which of the following classes are exclusively designed for writing and reading
Unicode characters?|FileReader/ FileWriter
Which of the following classes can be used for writing and reading objects (seri
alizing/de-serializing) from and to a file?|ObjectInputStream/ObjectOutputStream

Вам также может понравиться