Make your own free website on Tripod.com

Objective Questions without Answer:

1.       Which code segment could execute the stored procedure "countRecs()" located in a database server?

A) PreparedStatement pstmt = connection.prepareStatement("countRecs()");

pstmt.execute();

B) Statement stmt = connection.createStatement();

stmt.executeStoredProcedure("countRecs()");

C) Statement stmt = connection.createStatement();

stmt.execute("COUNTRECS()");

D) StoredProcedureStatement spstmt =

connection.createStoredProcedure("countRecs()");

spstmt.executeQuery();

E) CallableStatement cs = con.prepareCall("{call COUNTRECS}");

cs.executeQuery();

2.       JDK 1.2 includes Reference objects such as WeakReference and PhantomReference. How would you create your own type of Reference object?

A) Extend Reference.

B) Write methods to interact with the garbage collector.

C) You CANNOT create your own Reference type.

D) Implement Reference.

E) Create a class with a Reference attribute.

3.       Which Java API would you use while writing Java objects that act as servers for distributed CORBA objects written in C++?

A) JNI

B) JDBC

C) Infobus

D) JavaIDL

E) RMI

4.       Which of the following commands starts the Java IDL name service on port 1234?

A) nameserver -InitialPort 1234

B) tnameserv -ORBInitialPort 1234

C) cosnaming -COSInitialPort 1234

D) idlregistry -IDLInitialPort 1234

E) nameservice 1234

5.       What is Java serialization?

A) Distributed persistence.

B) The ability to examine the encapsulated data of a class.

C) Remote method invocation.

D) The ability transform the state of an object into bits and resurrect a copy of the

object from those bits.

E) Marshaling and unmarshaling of remote objects.

 

6.       How would you create a menu item "Save" with a shortcut key of "Ctrl+S"?

A) JMenuItem save = new JMenuItem("Save"); save.addShortcutKey( new

KeyStroke(KeyStroke.S | KeyStroke.CTRL_KEY) );

B) JMenuItem save = new JMenuItem("Save"); save.setMnemonic("Ctrl+S");

C) You would have to override the KeyPressed event of the top level Frame, and

handle the "Ctrl+S" to call the menu item's actionPerformed.

D) JMenuItem save = new JMenuItem("Save");

save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.

VK_S,Event.CTRL_MASK));

E) JMenuItem save = new JMenuItem("Save");

save.enableShortcut(KeyEvent.CTRL_KEY + KeyEvent.S);

 

public void print(Printable p){

PrinterJob pj = PrinterJob.getPrinterJob();

PageFormat pf = pj.pageDialog(pj.defaultPage());

pj.setPrintable(p,pf);

// now get user to select properties and confirm print

}

7.       Given the above sample code, which takes a Printable object and sets up a PrinterJob to print that object, what code would you use to allow the user to select properties for the print job, confirm, and then print?

A) p.print();

B) pj.printerDialog(pj.getDefaultPrinterOptions()); if( pj.printConfirmed() ) p.print();

C) PrinterDialog pd = new PrinterDialog(); if( pd.show() == Dialog.OK ) pj.print(p);

D) Properties props = pj.getUserOptions();

if(((Boolean)props.getValue(PrinterJob.CONFIRM)).equals(true)) p.print(pj);

E) if( pj.printDialog() ) pj.print();

8.       What is an RMI "stub"?

A) It acts as a client-side proxy to receive RMI calls and pass them to the server.

B) It receives RMI calls from the server to enable applet callbacks.

C) It is used by the client to find remote objects on a server.

D) It is the interface implemented by both the client and server objects.

E) It enables applets to make RMI calls without violating browser security.

9.       Which of the following types of audio files does JDK 1.2 NOT support?

A) MIDI

B) RMF

C) AU

D) MP3

E) WAV

  

1: Date myDate = new Date();

2: DateFormat dateFormat = DateFormat.getDateInstance();

3: String myString = dateFormat.format(myDate);

4: System.out.println( "Today is " + myString );

10.   How can you change line 2 above so that the date is displayed in the same format used in China?

A) DateFormat dateFormat = DateFormat.getDateInstance();

dateFormat.setLocale( java.util.Locale.CHINA );

B) DateFormat dateFormat = DateFormat.getDateInstance(

DateFormat.SHORT, java.util.Locale.CHINA);

C) java.util.Locale locale = java.util.Locale.getLocale("China");

DateFormat dateFormat = DateFormat.getDateInstance( locale );

D) DateFormat.setLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance();

E) java.util.Locale locale = java.util.Locale.getLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance( locale );

11.   How would you implement a text field for entering a password in a Login dialog using Swing components?

A) By using a JTextField and call setEchoChar('*').

B) By using a JPasswordField.

C) By using a JTextField and adding an event handler for the KeyPressed event

to echo a '*' character.

D) By creating your own class which extends JTextField and overrides the

keyDown() method to echo a '*' character.

E) use a JTextComponent and call

setTextDisplay(JTextComponent.PASSWORD).

12.   Which aspect(s) of the bean is used to modify or retrieve the JavaBeans properties?

A) Accessor methods

B) Persistence mechanism

C) propertyManager() method (required in all beans)

D) Event adapters

E) Associated java.beans.PropertyChangeListener class methods

 

class A {

Object get(Object o) {

try {

return o.getClass().getName();

} catch (Exception e) {

return null;

}

}

}

13.   Referring to the above, what is the expected output when the following code is executed?

A a = new A();

Vector v = new Vector();

System.out.println( a.get( v ) );

A) NullPointerException

B) A

C) Object

D) null

E) java.util.Vector

14.   What does double-buffering in animations do?

A) It draws the next frame to an off-screen image object before displaying to

eliminate flicker.

B) It prevents "hanging" using a MediaTracker object to ensure all frames are

loaded before beginning.

C) It puts multiple frame in the same file and uses cropImage() to select the

desired frame.

D) It uses a small image as wallpaper and a transparent image as the actual

frame.

E) It draws each image to the screen twice to eliminate white spots.

class Class1 {

int total=0;

public static void main(String args[]) {

doIt();

}

void doIt() {

for(int i=0;i<5;i++) total += i;

System.out.println(total);

}

}

15.   In reference to the above, how should the first line of method main() be changed to call doIt()?

A) Class1();

B) Class1 class1 = new Class1();

C) (new Class1()).doIt();

D) Class1().doIt();

E) No change is necessary.

16.   In a CORBA application, how would a client create a new remote object on the server?

A) By calling an existing server object's "factory" method which would create a

new object and return a reference to the client.

B) By using com.omg.CORBA.ORB.string_to_object() method to instantiate a new

object from a stringified object reference.

C) By using a naming service, such as the tnameserv in JDK 1.2, to create the

object.

D) By using the Remote Object Activation facility.

E) By using the server objects Home interface which provides methods for finding,

creating, and deleting objects.

static {

System.loadLibrary("mNativeLib");

}

public int myMethod(int count) {

Additional code here

}

17.   In reference to the above, if myMethod() is implemented in native code library "mNativeLib", how must its declaration be changed?

A) Replace myMethod()'s code with System.execute("mNativeLib",

myMethod(count));.

B) Replace it with native myMethod(int count) {}.

C) Replace it with public System.nativeMethod("myMethod(int)");.

D) Move it into the static code block.

E) Replace it with public native int myMethod(int count);.

18.   Which of the following is a requirement of a JavaBean?

A) Define a java.beans.PropertyEditor.

B) Use of the java.beans.PropertyChangeListener.

C) Provide a no-argument constructor.

D) Implement the java.beans.BeanInfo interface.

E) Extend java.beans.BeanDescriptor.

19.   How would you disable tooltips in a Swing based Java application?

A) Tool tip support is determined by the underlying windowing system, and cannot

be changed by a Java application.

B) UIManager.disableToolTips();

C) ToolTipManager.sharedInstance().setEnabled(false);

D) For each component in the application call: JComponent.setToolTipText(null);

E) SwingUtilities.setToolTipsEnabled(false);

20.   Which of the following is NOT a valid java.lang.String declaration?

A) String myString = new String();

B) String cde = "cde";

C) String myString = new String(5);

D) char data[] = {'a','b','c'};

String str = new String(data);

E) String myString = new String("Hello");

21.   Which of the following is true for untrusted applets running on most browsers?

A) Applets can connect to computers other than the codebase.

B) Applets can read to or write from files in the "/tmp" or "c:\tmp" directory.

C) Applets can change the ClassLoader.

D) Applets can retrieve the user's account name.

E) Applet frames display a warning.

22.   In reference to the above, when you click on the button the applet changes background colors. Which method must it call to do this?

A) repaint()

B) shade()

C) draw()

D) setbgcolor()

E) restart()

23.   In what way is it possible to circumvent applet security restrictions?

A) Install a different SecurityManager.

B) Attach a trusted digital signature to the downloaded applet JAR file.

C) Replace the default ClassLoader.

D) Connect to a ActiveX control located in the same web page.

E) There is no way to circumvent applet security restrictions.

1: class C extends Thread {

2: public void run() {

3: while(true) {

4: System.out.println("Hello World!");

5: try {

6: sleep(100);

7: } catch(Exception e) {}

8: }

9: }

10: public static void main(String[] s) {

11: C c = new C();

12: c.start();

13: }

14: }

  

24.   What is the result of the program above?

A) A java.lang.StackOverflowException is thrown.

B) The CPU is used complete up by the infinite loop.

C) Nothing. Compiler error on line 6.

D) The system exits immediately with little or no output.

E) "Hello World!" is printed forever.

public class TestApplet extends JApplet{

public void init(){

JButton b1 = new JButton("one");

JButton b2 = new JButton("two");

JButton b3 = new JButton("three");

JButton b4 = new JButton("four");

JButton b5 = new JButton("five");

getContentPane().add(b1);

getContentPane().add(b2);

getContentPane().add(b3);

getContentPane().add(b4);

getContentPane().add(b5);

}

}

25.   Given the above sample code of a JApplet, what would be displayed when the applet is run?

A) Only the button "five", occupying the entire area of the applet.

B) Five buttons, "one","two","three","four","five", in a column top to bottom.

C) Five buttons, "one","two","three","four","five", in a row left to right.

D) Only the button "one", occupying the entire area of the applet.

E) Five buttons, "one","two","three","four","five", randomly located within the

applet.

package mypackage;

class MyException extends java.lang.Exception {

public MyException() { super(); }

public MyException( String s ) { super(s); }

}

26.   Referring to the above, which code segment properly generates an exception of type "MyException"?

A) exception new MyException();

B) new Exception( MyException );

C) catch( MyException e) { }

D) throw new MyException("Error Occurred!");

E) MyException e = new MyException();

return e;

Sample Code

public void drawText(Graphics2D g, String text){

Font f = new Font("Century Gothic", Font.BOLD, 10);

g.setFont(f);

g.drawString(text, 20, 20);

}

27.   Given the above sample code, what would happen if the "Century Gothic" font was not available?

A) The Font() constructor will fail causing f to be null, and the setFont() method

will throw a NulPointerException.

B) The code will not compile, because only the following "logical" font names are

supported in Java: Dialog, DialogInput, Monospaced, Serif, SansSerif, and

Symbol.

C) A "default" Font object will be returned and this will be used.

D) The Font() constructor will throw an IllegalArgumentException.

E) "Century Gothic" is a built in Java font, which will always exist within the Java

runtime environment.

Sample Code

1: Date myDate = new Date();

2: DateFormat dateFormat = DateFormat.getDateInstance();

3: String myString = dateFormat.format(myDate);

4: System.out.println( "Today is " + myString );

28.   How can you change line 2 above so that the date is displayed in the same format used in China?

A) DateFormat dateFormat = DateFormat.getDateInstance(

DateFormat.SHORT, java.util.Locale.CHINA);

B) java.util.Locale locale = java.util.Locale.getLocale("China");

DateFormat dateFormat = DateFormat.getDateInstance( locale );

C) java.util.Locale locale = java.util.Locale.getLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance( locale );

D) DateFormat dateFormat = DateFormat.getDateInstance();

dateFormat.setLocale( java.util.Locale.CHINA );

E) DateFormat.setLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance();

29.   Which Java construct maps to the CORBA IDL 'module' construct?

A)interface

B)package

C)static variable

D)class

E)method

30.   How would you disable tooltips in a Swing based Java application?

A) UIManager.disableToolTips();

B) SwingUtilities.setToolTipsEnabled(false);

C) For each component in the application call: JComponent.setToolTipText(null);

D) ToolTipManager.sharedInstance().setEnabled(false);

E) Tool tip support is determined by the underlying windowing system, and cannot

be changed by a Java application.

Sample Code

void myMethod(int foo, int bar, String str) {

do {

if(foo <= bar) {

int i = 1;

System.out.println(str + ": " + i);

i++;

}

} while(i<10);

}

31.   What is the error in the above code?

A) myMethod does not define a valid return type.

B) You cannot concatenate strings inside a call to System.out.println().

C) If foo is greater than bar, the "do" loop will never terminate.

D) The "while" statement should appear to the left of the "}" bracket.

E) The "while" statement does not have access to variable i.

Sample Code

class PrimeThread extends Thread {

long minPrime;

long result;

PrimeThread(long minPrime) {

this.minPrime = minPrime;

}

public void run() {

// compute primes larger than minPrime

// . . .

}

}

32.   Referring to the above, which code segment could create and start the Prime Thread?

A) PrimeThread(143).run();

B) PrimeThread p = new PrimeThread();

p.run();

C) Thread p = new Thread(new PrimeThread(143));

p.run();

D) (new PrimeThread(143)).start();

E) Runnable r = new Runnable( PrimeThread(143) );

r.start();

Sample Code

public double SquareRoot( double value ) throws ArithmeticException

{

if (value >= 0) return Math.sqrt( value );

else throw new ArithmeticException();

}

public double func(int x) {

double y = (double) x;

try {

y = SquareRoot( y );

}

catch(ArithmeticException e) { y = 0; }

finally { --y; }

return y;

}

33.   Referring to the above, what value is returned when method func(4) is invoked?

A) -2.0

B) -1.0

C) 0

D) 1.0

E) 2.0

Sample Code

import java.awt.*;

class A extends Frame implements ActionListener,

WindowListener {

public A() {

Button button1 = new Button("Hello");

add(button1);

show();

}

public actionPerformed(ActionEvent e) {

// respond to mouse click

}

}

34.   In reference to the above, what statement could be added to the constructor for class A to monitor for a mouse click on button1?

A) button1.addListener(ActionListener);

B) button1.addActionListener(this);

C) super.addWindowListener(button1);

D) this.addActionListener(button1);

E) this.addEventListener(button1);

35.   Which method would be most efficient for inserting a new row into a table?

A) statement.insertRow()

B) statement.executeQuery()

C) statement.executeUpdate()

D) statement.execute()

E) statement.insertRecord()

36.   Which statement correctly describes the support for "Drag and Drop" provided by JDK 1.2?

A) "Drag and Drop" is supported between Java objects in the same JVM, and

between Java applications running in different JVMs.

B) "Drag and Drop" is not yet supported. The only supported data transfer method

is "Cut and Paste".

C) "Drag and Drop" is only supported between Java objects running in the same

JVM.

D) "Drag and Drop" is supported between Java objects in the same JVM, between

Java applications running in different JVMs, and between a Java application

and a native application.

E) "Drag and Drop" is supported between Java objects in the same JVM, between

Java applications running in different JVMs, between a Java application and a

native application, and between two native applications.

37.   In JavaBeans, what is a "constrained" property?

A) It is a property that allows changes of its value to be vetoed by registered

listeners.

B) It is read-only.

C) It causes the entire object to re-validate when it is modified.

D) It is tied to another internal (non-public) property.

E) It is static at runtime.

Sample Code

import java.rmi.*;

public class A {

public static void main(String args[]) {

int x=0, y=2;

anObject remoteObject;

try {

remoteObject = (anObject) Naming.lookup("rmi://h.com/B");

x = remoteObject.method1(y);

} catch(Exception e) {}

}

}

38.   In reference to the above, which of the following is NOT a valid conclusion regarding "anObject"?

A) anObject contains method method1() that takes an int parameter.

B) anObject extends java.rmi.Remote.

C) anObject is implemented by class B.

D) anObject responds to toString().

E) anObject is an interface.

Widget

Choice A

Choice B

Choice C

Choice D

Choice E

39.   The widget shown above is similar to which standard java.awt class?

A) List

B) Select

C) PullMenu

D) Choice

E) Menu

40.   Which of the following commands starts the Java IDL name service on port 1234?

A) idlregistry -IDLInitialPort 1234

B) nameserver -InitialPort 1234

C) cosnaming -COSInitialPort 1234

D) nameservice 1234

E) tnameserv -ORBInitialPort 1234

Sample Code

java.awt.Panel panel[] = new java.awt.Panel[3];

panel[0] = new java.awt.Panel();

panel[0].setSize(500,500);

panel[0].setLayout( new java.awt.BorderLayout() );

panel[1] = new java.awt.Panel();

panel[1].setLayout( new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT) );

panel[0].add( panel[1], "South" );

panel[2] = new java.awt.Panel();

panel[2].setSize(400,400);

panel[0].add( panel[2], "Center" );

java.awt.Button button1 = new java.awt.Button("Click Me!");

panel[1].add(button1);

41.   Where will button1 be positioned on panel[0] as shown above?

A) In the lower right-hand corner.

B) In the upper right-hand corner.

C) In the upper left-hand corner.

D) In the lower left-hand corner.

E) Centered horizontally at the top.

Sample Code

public drawThickLine(Graphics2D g, x1, y1, x2, y2){

// set line thickness here

g.drawLine(x1,y1,x2,y2);

}

42.   Given the above sample code, what code would you insert at the indicated point to make the method draw a line that is ten pixels wide?

A) Stroke s = new Stroke(); s.setWidth(10); g.setStroke(s);

B) g.setLineWidth(10);

C) g.setStroke( new BasicStroke(10.0f) );

D) g.setPen( new DefaultPen(10) );

E) g.setBrush( new Brush(10.0) );

Sample Code

class Employee{

protected String name, salary;

public Employee() {}

public Employee(String aName, String aSalary) {

name=aName; salary=aSalary;

}

public String toString(){ return (name + ", " + salary); }

}

class Manager extends Employee{

protected String car;

public Manager(String aName, String aSalary, String aCar) {

car = aCar;

super( aName, aSalary );

}

public String toString(){ return (name + ", " + salary + ", " + car); }

}

public class EmployeeTest{

public static void main( String[] args ){

Employee[] employees = new Employee[3];

employees[0] = new Employee("Smith","$25,000");

employees[1] = new Employee("Jones","$35,000");

employees[2] = new Manager("Wilson","$45,000","BMW");

for(int i=0; i<employees.length; i++)

System.out.println(employees[i]);

}

}

43.   Given the above sample code, what will be the result when the code is run?

A) The code will NOT compile, because "super(aName,aSalary);" must be the first

line in the Manager constructor.

B) Smith, $25,000 Jones, $35,000 Wilson, $45,000, BMW

C) The code will NOT compile, because the Manager class cannot access name

and salary from the Employee class.

D) Smith, $25,000 Jones, $35,000 Wilson, $45,000

E) The code will NOT compile, because System.out.println() does not take an

Employee parameter.

44.   Which of the following is NOT a valid java.lang.String declaration?

A) char data[] = {'a','b','c'};

String str = new String(data);

B) String myString = new String();

C) String myString = new String("Hello");

D) String cde = "cde";

E) String myString = new String(5);

Sample Code

public class TimerTest implements ActionListener{

public static void main(String[] args){

TimerTest test = new TimerTest();

javax.swing.Timer timer = new javax.swing.Timer(100,test);

}

public void actionPerformed(ActionEvent ev){

System.out.println("Timer ticked.");

}

}

45.   Given the above sample code, what would be the result when the code is run?

A) The words "Timer ticked." will be printed to the console once, after 100

milliseconds.

B) The words "Timer ticked." will be printed to the console every 100

microseconds.

C) Nothing, because the Timer is not started.

D) The words "Timer ticked." will be printed to the console every 100 seconds.

E) The words "Timer ticked." will be printed to the console every 100 milliseconds.

46.   Which command-line tool would you use to create public/private key pairs?

A) policytool

B) keytool

C) keymanager

D) jarsigner

E) javakey

47.   What is NOT a typical feature of visual JavaBeans?

A) Events, so that a simple communication metaphor can be used to connect up

beans.

B) Customization, so that when using an application builder a user can customize

the appearance and behavior of a bean.

C) Persistence, so that a bean can be customized in an application builder and

then have its customized state saved away and reloaded later.

D) Properties, both for customization and for programmatic use.

E) Distributed framework, so the visual component resides on the client, while the

logic resides on the server.

Sample Code

class Animal{

public Animal(int numLegs){}

}

class Dog extends Animal{

public void bark(){ System.out.println("woof!"); }

}

public class DogTest{

public static void main( String[] args ){

Dog rover = new Dog();

rover.bark();

}

}

48.   What will be the result when the above sample code is compiled and run?

A) The code will compile, but will cause a runtime error because the JVM will not

be able to load classes Animal and Dog.

B) The code will not compile because the class Dog has no constructor Dog().

C) The code will not compile because the class Animal has no constructor

Animal().

D) "woof!" will be printed to the console.

E) The code will not compile because the classes Animal and Dog are not

declared as public.

Sample Code

module Test{

interface Tester{

long doTest();

};

};

49.   Given the above sample code, which JDK 1.2 tool would you use to generate the corresponding Java interface, stub, skeleton, helper, and holder classes?

A) rmic

B) tnameserv

C) idlc

D) javac

E) idltojava

50.   What class should be used to represent the U.S. Mountain time zone in date/time calculations?

A) java.util.Locale

B) java.util.Date

C) java.util.SimpleTimeZone

D) java.util.GregorianCalendar

E) java.util.Calendar

Sample Code

<import java.io.*;

Additional code here

FileInputStream f = new FileInputStream("store");

ObjectInputStream in = new ObjectInputStream(f);

Object obj = in.readObject();

51.   In reference to the above, what additional code will produce the type of object represented by "obj"?

A) obj.toString();

B) String name;

String all[] = {"String","StringBuffer","Array", others here};

for(int i=0;i<all.length;i++)

if(name = all[i].equals(Class.instanceOf(all[i]))) break;

C) obj.getClass();

D) new Class.getName(obj);

E) Classloader.getInstance(obj);

52.   What class in java.security can be subclassed to represent entities that can be authenticated using their public keys?

A) DigitalSignature

B) Signer

C) Signature

D) Identity

E) KeyPair

53.   What happens if a parameter is passed to a remote object (using RMI) which does NOT implement Remote or Serializable?

A) It is passed by reference.

B) It is passed by value.

C) A java.lang.NullPointerException is thrown.

D) A java.rmi.MarshallException is thrown.

E) The code will not compile.

54.   Which of the following do you NOT have to develop when creating an Entity EJB?

A) Entity context

B) Remote interface

C) Primary Key

D) Bean implementation

E) Home interface

55.   Which interface would you implement if you want your class to handle its own serialization?

A) Externalizable

B) Streamable

C) Cloneable

D) ObjectOutput

E) Serializable

56.   Which of the following is a requirement of a JavaBean?

A) Provide a no-argument constructor.

B) Define a java.beans.PropertyEditor.

C) Extend java.beans.BeanDescriptor.

D) Implement the java.beans.BeanInfo interface.

E) Use of the java.beans.PropertyChangeListener.

57.   What is the primary purpose of the RMI/IIOP extension?

A) To allow RMI objects to communicate with Servlets over HTTP.

B) To allow RMI objects to communicate with CORBA objects.

C) To allow RMI objects to communicate with DCOM objects.

D) To allow RMI objects to communicate through a firewall.

E) To allow RMI objects to communicate with Enterprise JavaBeans.

Sample Code

class A {

int method1(int i) {

return i*2;

}

int method1(float f) {

int i = (int) f;

return i*2;

}

}

58.   In reference to the above, will attempting to compile class A pass or fail?

A) It will fail because floats cannot be cast to integers.

B) It will fail because there is no inheritance information.

C) It will fail because there are duplicate methods.

D) It will fail because there is no main method.

E) Succeed.

Sample Code

public class ArrayTest{

public static void main(String[] args){

// insert code here

}

}

59.   Given the above sample code, what would you insert to print out a list of the command-line arguments?

A) for(int i=0; i<sizeof(args); i++) System.out.println(args[i]);

B) for(int i=0; i<args.length(); i++) System.out.println(args[i]);

C) for(int i=0; i<args.length; i++) System.out.println(args[i]);

D) for(int i=0; i<args.size(); i++) System.out.println(args[i]);

E) for(int i=0; i<args.getLength(); i++) System.out.println(args[i]);

Sample Code

public void parseUserList( List users ){

Iterator iterator = users.iterator();

while( iterator.hasNext() ){

String user = iterator.next();

if( user.equals("Smith") )

iterator.remove();

}

}

60.   The above sample code is a method that takes a list of usernames and parses them to remove any users named "Smith". What is wrong with the code?

A) next() returns an Object, NOT a String, so you have to cast the returned value

to a String.

B) Iterator does not support removing elements from the underlying List; you

should use users.remove("Smith").

C) Iterator does not have a method called next(); it should be nextElement().

D) List does not have a method called iterator(); it should be getIterator().

E) Iterator does not have a method called hasNext(); it should be

hasMoreElements().

61.   Which of the following services is NOT provided by Java RMI?

A) Remote object activation

B) Naming service

C)Distributed garbage collection

D) Dynamic class loading

E) Distributed transaction management

Sample Code

public void createTempFiles(String d) {

File f = new File(d);

f.mkdirs();

// more code here ...

}

62.   What is the result when the following statement is invoked on the code above on a Unix platform?

createTempFiles( "/tmp/myfiles/_3214" );

A) The "myfiles" directory is created in the "/tmp" directory.

B) The directory "/tmp/myfiles/_3214" is created if it doesn't already exist.

C) A java.io.DirectoryNotCreatedException is thrown.

D) The file "_3214" is created in the "/tmp/myfiles" directory.

E) A java.lang.SecurityException is thrown.

Sample Code

int f = 2;

int g = 5;

double h;

h = 3+f/g+2;

63.   What is the expected value for h after execution of the above code?

A) 0.71

B) 5.0

C) 5.2

D) 5.4

E) 6

64.   How can you ensure compatibility of persistent object formats between different class versions?

A) Implement java.io.Serializable.

B) Override the default ObjectInputStream and ObjectOutputStream.

C) Implement java.io.Serilizable, add a serial version UID, and write your own

readObject() method to handle the different versions.

D) Make the whole class transient.

E) Add "transient" variables.

Sample Code

class Super{

protected int getX( int a ){ return 10*a; }

}

class Sub extends Super{

protected int getX( int b ){ return 5*b; }

}

public class Test{

public static void main( String[] args ){

Super s = new Sub();

System.out.println( s.getX(1) );

}

}

65.   What will be printed when the above code is run?

A) Nothing, because Sub has no constructor.

B) 5

C) 10

D) 50

E) The code will not compile because you cannot override a protected method.

Sample Code

class Class1 {

int total=0;

public static void main(String args[]) {

doIt();

}

void doIt() {

for(int i=0;i<5;i++) total += i;

System.out.println(total);

}

}

66.   In reference to the above, how should the first line of method main() be changed to call doIt()?

A) Class1();

B) Class1 class1 = new Class1();

C) (new Class1()).doIt();

D) Class1().doIt();

E) No change is necessary.

67.   What is the primary purpose of the RMI/IIOP extension?

A) To allow RMI objects to communicate with DCOM objects.

B) To allow RMI objects to communicate through a firewall.

C) To allow RMI objects to communicate with Servlets over HTTP.

D) To allow RMI objects to communicate with Enterprise JavaBeans.

E) To allow RMI objects to communicate with CORBA objects.

68.   How is an applet started by a browser?

A) The browser calls repaint(), which ends with a call to run().

B) Applets are not executed. They are displayed when the browser calls paint().

C) The browser loading the applet calls run().

D) The browser calls init() and then start().

E) The browser calls init().

69.   Which method is invoked each time a Servlet is invoked?

A) init()

B) process()

C) start()

D) service()

E) run()

Sample Code

public class TestServlet extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response){

// insert code here

}

}

70.   Given the above sample servlet code, what code fragment could you insert to print out the name and value of the cookies passed from the client that initiated this reqest?

A) String[] names = request.getSession().getValueNames(); for(int i=0;

i<names.length; i++){ String cookieValue =

request.getSession().getValue(names[i]);

System.out.println(names[i]+","+cookieValue); }

B) The Servlet API does NOT support the use of cookies, since they may not be

available in all browsers.

C) Cookie[] cookies = request.getCookies(); for(int i=0; i<cookies.length; i++)

System.out.println(cookies[i].getName()+","+cookies[i].getValue());

D) The Servlet API only supports the use of cookies for maintaining a sessionID

on the client.

E) Enumeration cookies = response.getCookies();

while(cookies.hasMoreElements()){ Cookie cookie =

(Cookie)cookies.nextElement();

System.out.println(cookie.getName()+","+cookie.getValue()); }

71.   What happens when you try to open a scrollable ResultSet on a JDBC driver that does NOT support scrollable ResultSets?

A) The standard JDBC classes handle scrolling for you.

B) A SQLException is thrown and no ResultSet is created.

C) All JDBC drivers support scrollable ResultSets.

D) A Java 1.2 JVM will not allow you to load a driver that does not support

scrollable ResultSets.

E) A SQLWarning should be issued on the Connection and a non-scrollable

ResultSet is returned.

Widget

Choice A

Choice B

Choice C

Choice D

Choice E

72.   The widget shown above is similar to which standard java.awt class?

A) Menu

B) List

C) Choice

D) Select

E) PullMenu

73.   Which statement correctly describes the support for "Drag and Drop" provided by JDK 1.2?

A) "Drag and Drop" is not yet supported. The only supported data transfer method

is "Cut and Paste".

B) "Drag and Drop" is supported between Java objects in the same JVM, between

Java applications running in different JVMs, and between a Java application

and a native application.

C) "Drag and Drop" is only supported between Java objects running in the same

JVM.

D) "Drag and Drop" is supported between Java objects in the same JVM, and

between Java applications running in different JVMs.

E) "Drag and Drop" is supported between Java objects in the same JVM, between

Java applications running in different JVMs, between a Java application and a

native application, and between two native applications.

74.   What is NOT a typical feature of visual JavaBeans?

A) Events, so that a simple communication metaphor can be used to connect up

beans.

B) Distributed framework, so the visual component resides on the client, while the

logic resides on the server.

C) Properties, both for customization and for programmatic use.

D) Persistence, so that a bean can be customized in an application builder and

then have its customized state saved away and reloaded later.

E) Customization, so that when using an application builder a user can customize

the appearance and behavior of a bean.

Sample Code

public void paint(Graphics g){

Graphics2D g2d = (Graphics2D) g;

// turn off antialiasing here

// display text

}

75.   Given the above sample code, how would you turn off text antialiasing before you display the text?

A) UIManager.setRenderingHints(Graphics2D.TEX_ANTIALIASING_ENABLED,

false);

B) SwingUtilities.setAntialisingEnabled(false);

C) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,

RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

D) RenderingHints hint = new

RenderingHints(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_OFF); g2d.addRenderingHint(rh);

E) You CANNOT control whether antialiasing is enabled. It depends on the native

windowing system.

Sample Code

module test{

interface Test{

long doTest();

};

};

76.   Given the above sample IDL file, Test.idl, which of the following files is NOT generated by running "idltojava Test.idl"?

A) TestHelper.java

B) _TestStub.java

C) Test.java

D) TestServer.java

E) TestHolder.java

Sample Code

class A{ }

class B extends A{ }

class C extends A{ }

class Test{

public static void main(String[] args){

A a = new A();

B b = new B();

C c = new C();

// assignment here

}

}

77.   Given the above sample code, which of the following assignments would be legal?

A) a=b

B) b=a

C) b=c

D) None of the above.

E) c=a

Sample Code

public class Test{

public static void main(String[] args){

int x=5, y=7;

swap(x,y);

System.out.println("x = " + x + ", y = " + y );

}

static void swap(int a, int b){

int c = a;

a = b;

b = c;

}

}

78.   Given the above sample code, what will be printed when the Test program is run?

A) x = 12, y = 12

B) x = 7, y = 5

C) x = 0, y = 0

D) x = 5, y = 7

E) The code will not compile, because the swap() method is not visible from

main().

class Class1 {

int total=0;

public static void main(String args[]) {

(new Class1()).doIt();

}

void doIt() {

for(int i=0;i<5;i++) total += i;

System.out.println(total);

}

}

79.   Which of the following Swing components is NOT a lightweight component?

A) JButton

B) JPanel

C) JFrame

D) JList

E) JRootPane

80.   Which Java construct maps to the CORBA IDL 'module' construct?

A) class

B) static variable

C) method

D) interface

E) package

81.   Which of the following is a limitation of subclassing the Thread class?

A) It cannot have any static methods in the class.

B) It must catch the ThreadDeath exception.

C) It must implement the Threadable interface.

D) It cannot subclass any other class.

E) It must declare the class final.

Sample Code

import java.rmi.*;

public class A {

public static void main(String args[]) {

int x=0, y=2;

anObject remoteObject;

try {

remoteObject = (anObject) Naming.lookup("rmi://h.com/B");

x = remoteObject.method1(y);

} catch(Exception e) {}

}

}

82.   In reference to the above, which of the following is NOT a valid conclusion regarding "anObject"?

A) anObject responds to toString().

B) anObject is an interface.

C) anObject contains method method1() that takes an int parameter.

D) anObject is implemented by class B.

E) anObject extends java.rmi.Remote.

Sample Code

void shifter(int[] array, int arrayLength) {

for(int i=1;i<arrayLength;i++) {

array[i-1] = array[i];

}

}

83.   How could you prevent other threads from changing data in "array" from the code above while method shifter() is executing?

A) Declare "array" as static.

B) Declare shifter as synchronized.

C) Call wait() before executing the for-loop.

D) Add "synchronized" to the "array[i-1] = array[i];" statement.

E) Enclose all code in all classes changing "array" in a synchronized (array) code

block.

Sample Code

public class Applet2D extends JApplet{

public void paint(Graphics g){

Graphics2D g2d = // *** insert code here ***

// further graphics code ...

}

}

84.   Given the above sample code, how would you obtain a reference to a Graphics2D object to allow you to use the advanced graphics functions supported by the Java 2D API?

A) Graphics2D g2d = UIManager.getGraphics2D();

B) Graphics2D g2d = g.getGraphics2D();

C) Graphics2D g2d = new Graphics2D(g);

D) Graphics2D g2d = SwingUtilities.getGraphics2D();

E) Graphics2D g2d = (Graphics2D) g;

85.   What is Java serialization?

A) Marshaling and unmarshaling of remote objects.

B) Remote method invocation.

C) The ability transform the state of an object into bits and resurrect a copy of the

object from those bits.

D) Distributed persistence.

E) The ability to examine the encapsulated data of a class.

86.   What are the two main types of persistence for entity EJBs?

A) Bean-managed and Container-managed

B) Application-managed and Database-managed

C) Client-managed and Server-managed

D) Context-managed and Session-managed

E) Applet-managed and Servlet-managed

87.   Which of the following actions is NOT required when converting a standard RMI object to work with RMI-IIOP?

A) Add code to initialize the ORB: ORB orb = org.omg.CORBA.ORB.init();

B) Replace any casting of Remote objects to Java types with the

javax.rmi.PortableRemoteObject.narrow() method calls.

C) Replace any code that uses java.rmi.Naming with JNDI code to talk to the

CORBA Naming Service.

D) Change the class to extend javax.rmi.PortableRemoteObject instead of

java.rmi.server.UnicastRemoteObject.

E) Use rmic with the -iiop option to produce stub and tie classes.

88.   Which aspect(s) of the bean is used to modify or retrieve the JavaBeans properties?

A) Event adapters

B) Accessor methods

C) propertyManager() method (required in all beans)

D) Persistence mechanism

E) Associated java.beans.PropertyChangeListener class methods

89.   What prevents a malicious applet from loading its own SecurityManager, giving itself unlimited access rights?

A) The browser loads a SecurityManager before loading applets and only one is

allowed.

B) SecurityManager cannot be loaded from a remote source.

C) SecurityManagers cannot be loaded unless the applet is digitally signed.

D) The applet needs private key of the browser to load a new SecurityManager.

E) The ClassLoader will deny loading a new SecurityManager.

90.   Which of the following is NOT typically found in a digital certificate?

A) private key of the signer

B) serial number

C) organization of the signing entity

D) registered name of the signer

E) expiration date

Sample Code

class B extends A {

int flag = 0;

public int getFlag() {

return flag;

}

protected void setFlag(int newSetting) {

flag = newSetting;

}

}

91.   Which statement describes the relationship between classes A and B in the code above?

A) The source code of B must be in the same file as A.

B) B is a subclass of A.

C) B is a superclass of A.

D) B belongs to the same package as A.

E) Instances of A have access to all of the methods defined by B.

92.   Which method can an untrusted applet call without necessarily throwing a security exception?

A) new FileOutputStream("/tmp/myTemp.out");

B) System.getProperty(...)

C) System.exit(...)

D) ClassLoader.getSystemClassLoader()

E) Runtime.exec(...)

Sample Screen

Object 1 Here

Object 2 Here Object 3 Here Object 4 Here

Object 5 Here

93.   To display five objects as shown above using all available screen space, what Layout Manager would be easiest?

A) CardLayout

B) FlowLayout

C) BorderLayout

D) null

E) GridLayout

Sample Code

String sql = "SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEE WHERE ID='123'";

Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATEABLE);

ResultSet rs = st.executeQuery(sql);

rs.first();

rs.updateString(1,"Tom");

rs.updateString(2,"Smith");

94.   Given the above sample code, what would you insert after the last line in order to write the changes to the database?

A) rs.updateRow();

B) rs.close();

C) st.saveChanges();

D) rs.next();

E) con.commit();

Sample Code

public interface A {

int myCount = 10;

void method1(int i);

int method2(float f);

}

-- New File --

class B implements A {

}

95.   In reference to the above, to implement A, what must class B do?

A) Class B must be abstract.

B) Class B must declare static versions of method1() and method2().

C) Class B must include non-abstract versions of method1() and method2(), or be

declared as abstract itself.

D) Class B must be in the same package as A.

E) Class B must override variable myCount.

Sample Code

static Object get() {

return value;

}

96.   Referring to the above, what could the declaration of "value" look like?

A) private static java.net.Socket value;

B) int value = 3;

C) public final Vector value;

D) private Object value = new Object();

E) public static int value = 10;

Sample Code

static Object get() {

return value;

}

97.   Referring to the above, what could the declaration of "value" look like?

A) private static java.net.Socket value;

B) int value = 3;

C) public final Vector value;

D) private Object value = new Object();

E) public static int value = 10;

Sample Code

class A {

int i, j, k;

public A(int ii) { i = ii; }

public A() {

k = 1;

}

}

98.   What code will instantiate an object of class A in the code above?

A) A(3) a;

B) A a = new A(4,8);

C) A a = new A(3);

D) A a = new A(3.3);

E) new A(this);

99.   How can you know when a user closes a window so you can perform cleanup?

A) By creating an inner class called WindowListener, extending

WindowEventHandler, then putting cleanup code in a processEvent(Event e)

method.

B) By placing cleanup code in a try - catch block that catches a

FrameClosingException.

C) By implementing WindowListener and putting cleanup code in a public void

windowClosing(WindowEvent e) method.

D) By implementing FrameListener and placing cleanup code in a

frameClosing(FrameEvent e) method.

E) Java does cleanup automatically when a window is closed.

String url=new String("http://www.tek.com");

100.                How could you retrieve the content of the above URL?

A) Object content = new URLConnection(url).getContent();

B) String content = new URLConnection(url).collect();

C) String content = new URLHttp(url).getString();

D) Object content = new URL(url).getContent();

E) Socket content = new Socket(new URL(url)).collect();

101.                Which class could you use to store a set of <key,value> pairs which are sorted by the keys?

A) TreeMap

B) HashMap

C) TreeSet

D) Hashtable

E) LinkedList

Sample Code

public class ArrayTest{

public static void main(String[] args){

// insert code here

}

}

102.                Given the above sample code, what would you insert to print out a list of the command-line arguments?

A) for(int i=0; i<args.length(); i++) System.out.println(args[i]);

B) for(int i=0; i<args.getLength(); i++) System.out.println(args[i]);

C) for(int i=0; i<args.size(); i++) System.out.println(args[i]);

D) for(int i=0; i<args.length; i++) System.out.println(args[i]);

E) for(int i=0; i<sizeof(args); i++) System.out.println(args[i]);

103.                Which Java API would you use to look up an Enterprise JavaBean (EJB) component?

A) JDBC

B) JMS

C) JNDI

D) Jini

E) JMAPI

Sample Code

public class CustomComponent extends JComponent implements Printable{

public int print(Graphics g, PageFormat pf, int pageNo){

// cast Graphics to Graphics2D

Graphics2D g2d = (Graphics2D) g;

// account for margins specified by PageFormat

g2d.translate(pf.getImageableX(),pf.getImageableY());

// call paint to print component

this.paint(g2d);

// tell the PrinterJob that the page was printed

return Printable.PAGE_EXISTS;

}

}

104.                The above sample code shows part of the code for a "printable" component. What is wrong with the code?

A) You CANNOT pass a Graphics2D object to paint(); it takes a Graphics object.

B) You should first check if pageNo>=0 and return Printable.NO_SUCH_PAGE, to

end the PrintJob, if not.

C) You should cast the Graphics to a PrinterGraphics object, NOT a Graphics2D.

D) PageFormat.getImageableX() and PageFormat.getImageableY() both return

doubles, but Graphics2D.translate(x,y) expects int parameters.

E) You CANNOT cast a Graphics object to a Graphics2D.

Sample Code

public double SquareRoot( double value ) throws ArithmeticException

{

if (value >= 0) return Math.sqrt( value );

else throw new ArithmeticException();

}

public double func(int x) {

double y = (double) x;

try {

y = SquareRoot( y );

}

catch(ArithmeticException e) { y = 0; }

finally { --y; }

return y;

}

105.                Referring to the above, what value is returned when method func(4) is invoked?

A) -2.0

B) -1.0

C) 0

D) 1.0

E) 2.0

Sample Code

int i=0;

float value = (float) 1.2;

String str = new String("Hello World");

boolean flag = false;

106.                Which is a valid use of the variable "flag" in the sample code above?

A) i = value*flag;

B) if(!flag == i) System.out.println(str);

C) flag += i;

D) !flag = true;

E) if(flag) flag=false;

Sample Code

int h = 7;

float f = 3f;

float result = h%f;

107.                In reference to the above, what is the value of "result" after execution?

A) 0

B) 1.0

C) 2.0

D) 2.33

E) 7.0

Sample Code

import java.lang.reflect.Constructor;

Constructor con;

con=new Constructor(Class.forName("Object"));

108.                What is wrong with the above code?

A) Constructor is static and need not be instantiated.

B) Constructor has a private constructor, inaccessible to the code above.

C) Constructor objects can only be created for classes in the default package.

D) Constructor is abstract and cannot be instantiated.

E) Objects cannot be created for Object objects.

109.                Which method would be most efficient for inserting a new row into a table?

A) statement.insertRow()

B) statement.executeQuery()

C) statement.execute()

D) statement.executeUpdate()

E) statement.insertRecord()

Sample Code

public class Test{

public static void main(String[] args){

StringBuffer[] messages = new StringBuffer[5];

messages[0].append("Hello world!");

System.out.println("First message is " + messages[0]);

}

}

110.                What will be the output when the above sample code is run?

A) First message is null.

B) A NullPointerException will be thrown.

C) First message is Hello World!

D) The code would not compile.

E) An ArrayIndexOutOfBounds will be thrown.

111.                In JavaIDL programming, the NamingContext allows you to bind objects to the naming service and look up objects. Which code fragment correctly gets a reference to the NamingContext (given that 'orb' is a reference to the ORB)?

A) org.omg.CORBA.ObjectHolder oh = orb.lookup_reference("NameService");

NamingContext nc = ObjectHelper.toNamingContext(oh);

B) org.omg.CORBA.Any any = orb.resolve_name_service("NameService");

NamingContext nc = NamingContextHolder.convert(any);

C) java.lang.Object o = orb.lookup("NameService"); NamingContext nc =

(NamingContext) o;

D) NamingContext nc = orb.getNamingContext("NameService");

E) org.omg.CORBA.Object o = orb.resolve_initial_references("NameService");

NamingContext nc = NamingContextHelper.narrow(o);

112.                Which class could you use to store a set of <key,value> pairs which are sorted by the keys?

A) TreeSet

B) LinkedList

C) TreeMap

D) Hashtable

E) HashMap

Sample Code

public final class B extends A {

// ...

}

113.                What is the meaning of "final" in the declaration above?

A) B cannot be subclassed.

B) This is the final version class A, which should be used if multiple versions are

present.

C) Class A is an abstract class.

D) Class A does not need to be instantiated to invoke its methods.

E) None of class A's methods can be overridden.

Sample Code

class A{ }

class B extends A{ }

class C extends A{ }

class Test{

public static void main(String[] args){

A a = new A();

B b = new B();

C c = new C();

// assignment here

}

}

114.                Given the above sample code, which of the following assignments would be legal?

A) b=c

B) a=b

C) c=a

D) None of the above.

E) b=a

115.                When are constructors invoked?

A) When the object needs garbage collection.

B) When a superclass object is instantiated.

C) When a new instance of a class is instantiated.

D) When any method is invoked on an object.

E) When the java virtual machine begins garbage collection.

116.                When designing a custom GUI component, which interface should you implement to provide support for assistive technologies such as screen magnifiers and speech recognition?

A) You do NOT have to implement an interface; simply have your component

extend JComponent to inherit the functionality.

B) Accessible

C) Externalizable

D) Observer

E) InputMethodListener

Applet

117.                In reference to the above, when you click on the button the applet changes background colors. Which method must it call to do this?

A) restart()

B) shade()

C) draw()

D) repaint()

E) setbgcolor()

Sample Code

public void parseUserList( List users ){

Iterator iterator = users.iterator();

while( iterator.hasNext() ){

String user = iterator.next();

if( user.equals("Smith") )

iterator.remove();

}

}

118.                The above sample code is a method that takes a list of usernames and parses them to remove any users named "Smith". What is wrong with the code?

A) next() returns an Object, NOT a String, so you have to cast the returned value

to a String.

B) Iterator does not have a method called hasNext(); it should be

hasMoreElements().

C) Iterator does not support removing elements from the underlying List; you

should use users.remove("Smith").

D) Iterator does not have a method called next(); it should be nextElement().

E) List does not have a method called iterator(); it should be getIterator().

Sample Code

class Animal{

public Animal(int numLegs){}

}

class Dog extends Animal{

public void bark(){ System.out.println("woof!"); }

}

public class DogTest{

public static void main( String[] args ){

Dog rover = new Dog();

rover.bark();

}

}

119.                What will be the result when the above sample code is compiled and run?

A) The code will compile, but will cause a runtime error because the JVM will not

be able to load classes Animal and Dog.

B) "woof!" will be printed to the console.

C) The code will not compile because the class Animal has no constructor

Animal().

D) The code will not compile because the class Dog has no constructor Dog().

E) The code will not compile because the classes Animal and Dog are not

declared as public.

120.                What is the primary purpose of the RMI/IIOP extension?

A) To allow RMI objects to communicate with Servlets over HTTP.

B) To allow RMI objects to communicate with CORBA objects.

C) To allow RMI objects to communicate through a firewall.

D) To allow RMI objects to communicate with Enterprise JavaBeans.

E) To allow RMI objects to communicate with DCOM objects.

Sample Code

public class B extends A {

int xC,yC,k;

void move(int x) {

xC = x;

}

}

121.                In reference to the above, what must you change to B so that it can be run in its own thread?

A) Implement Threadable.

B) Subclass ThreadGroup.

C) Make the class public, implement Runnable, and add a main() method.

D) Instantiate a new Thread.

E) Implement Runnable and add a "public void run()" method.

122.                How are multiple requests for a servlet handled, assuming that the servlet does NOT implement SingleThreadModel?

A) If the servlet is busy handling a request when another request is received, an

HTTP error 503 (service unavailable) is returned.

B) Only one request at a time is processed, and the others are placed in a queue.

C) A thread is allocated to execute the service method of the servlet.

D) It is up to the servlet programmer to determine how multiple requests are

handled.

E) A new instance of the servlet is created to handle each request.

Sample Code

static Object get() {

return value;

}

123.                Referring to the above, what could the declaration of "value" look like?

A) private static java.net.Socket value;

B) int value = 3;

C) public static int value = 10;

D) public final Vector value;

E) private Object value = new Object();

Sample Code

for(int i=0;i<=22;) {

if(i<= 10) {

int j= 2 + i;

i++;

// /* let us know */ //

System.out.println("i: " + i + " j: " + j);

}

}

124.                What is the error in the above code?

A) The comment line is not formatted correctly.

B) You cannot print integer values without converting them to strings.

C) The loop will never terminate.

D) Variable j is referenced outside its scope.

E) You cannot declare variables inside a for-loop.

Sample Code

package mypackage;

class MyException extends java.lang.Exception {

public MyException() { super(); }

public MyException( String s ) { super(s); }

}

125.                Referring to the above, which code segment properly generates an exception of type "MyException"?

A) MyException e = new MyException();

return e;

B) throw new MyException("Error Occurred!");

C) exception new MyException();

D) new Exception( MyException );

E) catch( MyException e) { }

126.                Which of the following does the java.security package NOT address?

A) access control lists

B) cookies

C) key management

D) digital signatures

E) message digests

Sample Code

public void actionPerformed(ActionEvent e) {

}

127.                What interface does the class containing the above code or a superclass most likely implement?

A) WindowListener

B) ActionAdapter

C) AWTEvent

D) ActionListener

E) ComponentEvent

128.                In what way is it possible to circumvent applet security restrictions?

A) Replace the default ClassLoader.

B) Attach a trusted digital signature to the downloaded applet JAR file.

C) Connect to a ActiveX control located in the same web page.

D) There is no way to circumvent applet security restrictions.

E) Install a different SecurityManager.

Sample Code

class A {

public static void main(String args[]) {

int x=2,y=3,z=7;

if(x!=y) {

x += 4;

x *= (y-1);

z %= y;

}

}

}

129.                What are ending values of variables x, y, and z after running the above code?

A) z=6, y=3, z=3

B) x=12, y=3, z=7

C) x=12, y=3, z=1

D) x=4, y=2, z=2

E) x=6, y=2, z=3

130.                How would you disable tooltips in a Swing based Java application?

A) SwingUtilities.setToolTipsEnabled(false);

B) For each component in the application call: JComponent.setToolTipText(null);

C) ToolTipManager.sharedInstance().setEnabled(false);

D) UIManager.disableToolTips();

E) Tool tip support is determined by the underlying windowing system, and cannot

be changed by a Java application.

Sample Code

import java.sql.*;

. . . Other Code Here. . .

Class.forName("any.sql.AsqlDriver");

String u = "jdbc:asql://mhost:1234/biz";

Connection c = DriverManager.getConnection(u);

131.                In reference to the above, what does the AsqlDriver class do?

A) It registers a driver with JDBC when it is loaded.

B) It is written 100% in java.

C) It can only be accessed through a Class object.

D) It is monitoring port 1234 on mhost.

E) It does not use ODBC.

132.                Which command starts the RMI Activation daemon, which manages remote object activation?

A) rmiad

B) rmiregistry

C) rmia

D) rmic

E) rmid

Sample Code

public void printIt(String txt) {

StringTokenizer st = new StringTokenizer(txt);

while (st.hasMoreTokens()) {

System.out.println(st.nextToken());

}

}

133.                Referring to the above, what is the result when the following statement is invoked? printIt(" Hello\n World\t!" );

A) The following is outputted:

HelloWorld!

B) The following is outputted:

Hello

World

!

C) The following is outputted:

Hello

World

!

D) The following is outputted:

Hello

World!

E) java.util.NoSuchElementException is thrown.

134.                Why would you use a WeakReference object?

A) It is useful for mapping to database types that do not easily map to any of the

standard Java types.

B) It allows you to maintain a reference to an object that the garbage collector

ignores.

C) It allows you to maintain a reference to an object in a different JVM, or on a

remote machine.

D) It allows you to assign the reference to objects of different types.

E) It prevents the object from being saved when your class is serialized.

Sample Code

public class SwingApplet extends JApplet{

public void init(){

JList list = new JList();

list.addElement("Hello");

list.addElement("World");

getContentPane().add(list);

}

}

135.                Given the sample applet code above, what would be displayed when the code is run?

A) The applet will be displayed with a JList component containing two elements,

occupying the entire screen area of the applet.

B) The applet will be displayed with a JList component containing two elements,

occupying the top-left corner of the applet.

C) Nothing - the code would not compile because you cannot add data directly to

a JList. You must create a DefaultListModel to hold the data.

D) Nothing - the code would not compile because JApplet does not have a

getContentPane() method. You should add the list directly to the JApplet.

E) The code will compile, but nothing will be displayed because you must override

the paint() method of JApplet and call the list's paint() method.

136.                Which class CANNOT be directly instantiated?

A) java.io.StringBufferInputStream

B) java.io.FileReader

C) java.io.DataInputStream

D) java.io.BufferedReader

E) java.io.InputStream

137.                Which of the following is true for untrusted applets running on most browsers?

A) Applets can read to or write from files in the "/tmp" or "c:\tmp" directory.

B) Applets can change the ClassLoader.

C) Applet frames display a warning.

D) Applets can connect to computers other than the codebase.

E) Applets can retrieve the user's account name.

Sample Code

class A {

B b = new B();

C c = (C) b;

}

138.                When will the cast of "b" to class C be allowed in the code above?

A) B and C are subclasses of the same superclass.

B) C is a final class.

C) If B and C are superclasses of the same subclass.

D) B is a superclass of C.

E) B is a subclass of C.

139.                When could you implement the java.io.Externalizable interface?

A) It will allow other virtual machines to retrieve an object.

B) To create a JavaBean used in visual programming environments.

C) It will make a class's public methods accessible outside the virtual machine.

D) When you must store an object on a different platform.

E) When you need control over the information recorded when placing objects in

persistent storage.

140.                If two objects with non-"transient" references to each other are serialized using ObjectOutputStream, will this create an infinite loop? Why or why not?

A) Yes, since the references are not "transient".

B) No, ObjectOutputStream ensures that each object is written only once.

C) Yes, ObjectOutputStream does not keep track of previously stored objects.

D) No, ObjectOutputStream only stores relative memory references.

E) No, ObjectOutputStream does not store referenced objects.

141.                Which Java construct maps to the CORBA IDL 'module' construct?

A) method

B) package

C) class

D) interface

E) static variable

142.                What code would you use to retrieve an image from a remote website in a Java application (i.e., NOT an applet)?

A) URL url = new URL("http://www.images.com/test.jpg"); Image img =

url.openConnection().getContent();

B) URL url = new URL("http://www.images.com/test.jpg"); Image img =

Toolkit.getDefaultToolkit().getImage(url);

C) URL url = new URL("http://www.images.com/test.jpg"); Image img = (new

AppletContext()).getImage(url);

D) URL url = new URL("http://www.images.com/test.jpg"); Image img =

Runtime.getRuntime().load(url);

E) URL url = new URL("http://www.images.com/test.jpg"); Image img = (new

Applet()).getImage(url);

Sample Code

import java.sql.*;

Additional code here

Connection con = DriverManager.getConnection(url);

String s = "call proc(?,?,?,?)";

CallableStatement cs = con.prepareCall(s);

cs.setInt(1,1);

cs.setInt(2,2);

cs.setInt(3,3);

cs.registerOutParameter(4,java.sql.TYPES.INTEGER);

143.                In reference to the above, which command will execute procedure proc(), which includes two INSERT sql statements and one OUT parameter?

A) con.getConnection(cs)

B) ResultSet = cs.runQuery()

C) cs.executeQuery()

D) cs.execute()

E) cs.prepareCall().execute()

144.                What class will open a TCP connection to a server for data communications using a proprietary application protocol?

A) java.net.ServerSocket

B) java.net.Socket

C) java.net.SocketImpl

D) java.net.DatagramSocket

E) java.net.URLConnection

145.                What is NOT a typical feature of visual JavaBeans?

A) Properties, both for customization and for programmatic use.

B) Customization, so that when using an application builder a user can customize

the appearance and behavior of a bean.

C) Events, so that a simple communication metaphor can be used to connect up

beans.

D) Distributed framework, so the visual component resides on the client, while the

logic resides on the server.

E) Persistence, so that a bean can be customized in an application builder and

then have its customized state saved away and reloaded later.

146.                In JavaIDL programming, the NamingContext allows you to bind objects to the naming service and look up objects. Which code fragment correctly gets a reference to the NamingContext (given that 'orb' is a reference to the ORB)?

A) org.omg.CORBA.Any any = orb.resolve_name_service("NameService");

NamingContext nc = NamingContextHolder.convert(any);

B) NamingContext nc = orb.getNamingContext("NameService");

C) java.lang.Object o = orb.lookup("NameService"); NamingContext nc =

(NamingContext) o;

D) org.omg.CORBA.Object o = orb.resolve_initial_references("NameService");

NamingContext nc = NamingContextHelper.narrow(o);

E) org.omg.CORBA.ObjectHolder oh = orb.lookup_reference("NameService");

NamingContext nc = ObjectHelper.toNamingContext(oh);

147.                How would you add data to a Swing component such as a JTable, JTree, or JList?

A) Add the data to the component's model.

B) Add the data directly to the component.

C) Add the data to the component's view.

D) Add the data to the component's peer.

E) Add the data to the component's controller.

148.                Which Java API would you use while writing Java objects that act as servers for distributed CORBA objects written in C++?

A) JDBC

B) RMI

C) Infobus

D) JavaIDL

E) JNI

149.                Which of the following is NOT a reserved java keyword?

A) boolean

B) final

C) finally

D) safe

E) native

150.                What is the purpose of the java.text package?

A) To allow formatting of text data for specific geographic locations.

B) To render text strings on java.awt.Container objects.

C) To facilitate spelling and grammar checks.

D) To perform font management between different platforms.

E) To provide classes for manipulating Strings.

151.                When an object is deserialized, how does the interpreter determine that the version of the class file matches the serialized data?

A) A unique identifier is included in the serialization stream that can be used to

determine class definition compatibility.

B) The serialized object stores the proper class name.

C) The serialized object stores a URL to the proper class.

D) The ClassLoader takes care of testing for deserialization.

E) The ClassLoader compares the hashCodes.

Sample Code

class A{ }

class B extends A{ }

class C extends A{ }

class Test{

public static void main(String[] args){

A a = new A();

B b = new B();

C c = new C();

// assignment here

}

}

152.                Given the above sample code, which of the following assignments would be legal?

A) None of the above.

B) c=a

C) b=c

D) a=b

E) b=a

153.                When are constructors invoked?

A) When the object needs garbage collection.

B) When any method is invoked on an object.

C) When the java virtual machine begins garbage collection.

D) When a new instance of a class is instantiated.

E) When a superclass object is instantiated.

154.                Which Java API would you use to look up an Enterprise JavaBean (EJB) component?

A) JDBC

B) Jini

C) JNDI

D) JMAPI

E) JMS

Sample Code

public class Applet2D extends JApplet{

public void paint(Graphics g){

Graphics2D g2d = // *** insert code here ***

// further graphics code ...

}

}

155.                Given the above sample code, how would you obtain a reference to a Graphics2D object to allow you to use the advanced graphics functions supported by the Java 2D API?

A) Graphics2D g2d = SwingUtilities.getGraphics2D();

B) Graphics2D g2d = UIManager.getGraphics2D();

C) Graphics2D g2d = g.getGraphics2D();

D) Graphics2D g2d = (Graphics2D) g;

E) Graphics2D g2d = new Graphics2D(g);

Sample Code

public void parseUserList( List users ){

Iterator iterator = users.iterator();

while( iterator.hasNext() ){

String user = iterator.next();

if( user.equals("Smith") )

iterator.remove();

}

}

156.                The above sample code is a method that takes a list of usernames and parses them to remove any users named "Smith". What is wrong with the code?

A) Iterator does not have a method called next(); it should be nextElement().

B) Iterator does not have a method called hasNext(); it should be

hasMoreElements().

C) Iterator does not support removing elements from the underlying List; you

should use users.remove("Smith").

D) next() returns an Object, NOT a String, so you have to cast the returned value

to a String.

E) List does not have a method called iterator(); it should be getIterator().

Sample Code

public void printIt(String txt) {

StringTokenizer st = new StringTokenizer(txt);

while (st.hasMoreTokens()) {

System.out.println(st.nextToken());

}

}

157.                Referring to the above, what is the result when the following statement is invoked? printIt(" Hello\n World\t!" );

A) The following is outputted:

HelloWorld!

B) The following is outputted:

Hello

World!

C) The following is outputted:

Hello

World

!

D) java.util.NoSuchElementException is thrown.

E) The following is outputted:

Hello

World

!

Sample Code

package B;

public class A {

int getSquare(int i) {

return i*i;

}

}

158.                Referring to the above, what objects can access method getSquare() in class A?

A) Class A, all subclasses of A, classes in package B, and all classes in sub-

packages of B.

B) Class A and its subclasses only.

C) Class A, all subclasses of A, and classes in package B only.

D) Class A and classes in package B only.

E) Class A.

Sample Code

class A {

Object get(Object o) {

try {

return o.getClass().getName();

} catch (Exception e) {

return null;

}

}

}

159.                Referring to the above, what is the expected output when the following code is executed?

A a = new A();

Vector v = new Vector();

System.out.println( a.get( v ) );

A) A

B) null

C) java.util.Vector

D) NullPointerException

E) Object

Sample Code

String readInput() {

try {

char buf[] = new char[80];

Reader in = new BufferedReader(System.in);

in.read(buf, 0, 80);

return new String(buf);

} catch (Exception e ) {}

return "";

}

160.                What is wrong with method readInput() above?

A) String objects cannot be instantiated with a character array.

B) java.io.IOException must be caught instead of java.lang.Exception.

C) BufferedReader cannot convert standard input into a Reader.

D) Standard input cannot be used with other input streams.

E) InputStream must be used with an InputStream.

In a CORBA appSample Code

public void print(Printable p){

PrinterJob pj = PrinterJob.getPrinterJob();

PageFormat pf = pj.pageDialog(pj.defaultPage());

pj.setPrintable(p,pf);

// now get user to select properties and confirm print

}

161.                Given the above sample code, which takes a Printable object and sets up a PrinterJob to print that object, what code would you use to allow the user to select properties for the print job, confirm, and then print?

A) pj.printerDialog(pj.getDefaultPrinterOptions()); if( pj.printConfirmed() ) p.print();

B) p.print();

C) Properties props = pj.getUserOptions();

if(((Boolean)props.getValue(PrinterJob.CONFIRM)).equals(true)) p.print(pj);

D) PrinterDialog pd = new PrinterDialog(); if( pd.show() == Dialog.OK ) pj.print(p);

E) if( pj.printDialog() ) pj.print();

162.                lication, how would a client create a new remote object on the server?

A) By using a naming service, such as the tnameserv in JDK 1.2, to create the

object.

B) By using com.omg.CORBA.ORB.string_to_object() method to instantiate a new

object from a stringified object reference.

C) By using the server objects Home interface which provides methods for finding,

creating, and deleting objects.

D) By using the Remote Object Activation facility.

E) By calling an existing server object's "factory" method which would create a

new object and return a reference to the client.

163.                What are the two main types of persistence for entity EJBs?

A) Application-managed and Database-managed

B) Applet-managed and Servlet-managed

C) Client-managed and Server-managed

D) Context-managed and Session-managed

E) Bean-managed and Container-managed

String username = Runtime.getParameter("username");

String us2ername = ar[0];

String u3sername = Class.getField("username");

String username4 = System.getenv("username");

String username5 = System.getProperty("username");

Sample Code

class A {

B b = new B();

C c = (C) b;

}

164.                When will the cast of "b" to class C be allowed in the code above?

A) C is a final class.

B) B is a subclass of C.

C) B and C are subclasses of the same superclass.

D) B is a superclass of C.

E) If B and C are superclasses of the same subclass.

Sample Code

package mypackage;

class MyException extends java.lang.Exception {

public MyException() { super(); }

public MyException( String s ) { super(s); }

}

165.                Referring to the above, which code segment properly generates an exception of type "MyException"?

A) MyException e = new MyException();

return e;

B) new Exception( MyException );

C) catch( MyException e) { }

D) exception new MyException();

E) throw new MyException("Error Occurred!");

Sample Code

class A {

int i, j, k;

public A(int ii) { i = ii; }

public A() {

k = 1;

}

}

166.                What code will instantiate an object of class A in the code above?

A) A a = new A(3.3);

B) A a = new A(4,8);

C) A a = new A(3);

D) A(3) a;

E) new A(this);

167.                Which interface is intended to supercede Enumeration in the collections framework?

A) Iterator

B) List

C) Vector

D) Set

E) Comparator

168.                Which of the following services is NOT provided by Java RMI?

A) Naming service

B) Distributed garbage collection

C) Distributed transaction management

D) Dynamic class loading

E) Remote object activation

169.                How would you create a scrollable ResultSet?

A) Statement st = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATEABLE ); ResultSet rs = st.executeQuery(

sqlString );

B) ResultSet rs = new ResultSet(); rs.setScrollable(true); rs.execute(sqlString);

C) Statement st = new Statement(); st.setCursorType(

Statement.TYPE_SCROLLABLE, Statement.CONCUR_READ_ONLY );

ResultSet rs = st.executeSQL( sqlString );

D) ScrollableResultSet srs = new ScrollableResultSet();

srs.openResultSet(sqlString);

E) Statement st = con.createStatement(); ResultSet rs = st.executeQuery(

sqlString, ResultSet.SCROLLABLE );

Sample Code

class A implements Runnable {

170.                What code will create a daemon thread of a class A object with the code above?

A) Thread t = new Thread(A, true);

B) Daemon t = new Thread(new A());

C) A a = new A().setDaemon(true);

Thread t = new Thread(a);

D) A a = new A();

Thread t = new Thread(a);

t.setDaemon(true);

E) A a = new A();

Daemon t = new Thread(a);

171.                How can you know when a user closes a window so you can perform cleanup?

A) Java does cleanup automatically when a window is closed.

B) By implementing FrameListener and placing cleanup code in a

frameClosing(FrameEvent e) method.

C) By creating an inner class called WindowListener, extending

WindowEventHandler, then putting cleanup code in a processEvent(Event e)

method.

D) By placing cleanup code in a try - catch block that catches a

FrameClosingException.

E) By implementing WindowListener and putting cleanup code in a public void

windowClosing(WindowEvent e) method.

Sample Code

String sql = "SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEE WHERE ID='123'";

Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATEABLE);

ResultSet rs = st.executeQuery(sql);

rs.first();

rs.updateString(1,"Tom");

rs.updateString(2,"Smith");

172.                Given the above sample code, what would you insert after the last line in order to write the changes to the database?

A) rs.close();

B) con.commit();

C) st.saveChanges();

D) rs.updateRow();

E) rs.next();

Sample Code

public void createTempFiles(String d) {

File f = new File(d);

f.mkdirs();

// more code here ...

}

173.                What is the result when the following statement is invoked on the code above on a Unix platform?

createTempFiles( "/tmp/myfiles/_3214" );

A) The "myfiles" directory is created in the "/tmp" directory.

B) A java.lang.SecurityException is thrown.

C) The directory "/tmp/myfiles/_3214" is created if it doesn't already exist.

D) The file "_3214" is created in the "/tmp/myfiles" directory.

E) A java.io.DirectoryNotCreatedException is thrown.

Sample Code

public class TestServlet extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response){

// insert code here

}

}

174.                Given the above sample servlet code, what code fragment could you insert to print out the name and value of the cookies passed from the client that initiated this reqest?

A) Cookie[] cookies = request.getCookies(); for(int i=0; i<cookies.length; i++)

System.out.println(cookies[i].getName()+","+cookies[i].getValue());

B) Enumeration cookies = response.getCookies();

while(cookies.hasMoreElements()){ Cookie cookie =

(Cookie)cookies.nextElement();

System.out.println(cookie.getName()+","+cookie.getValue()); }

C) The Servlet API does NOT support the use of cookies, since they may not be

available in all browsers.

D) String[] names = request.getSession().getValueNames(); for(int i=0;

i<names.length; i++){ String cookieValue =

request.getSession().getValue(names[i]);

System.out.println(names[i]+","+cookieValue); }

E) The Servlet API only supports the use of cookies for maintaining a sessionID

on the client.

Sample Code

public void paint(Graphics g){

Graphics2D g2d = (Graphics2D) g;

// turn off antialiasing here

// display text

}

175.                Given the above sample code, how would you turn off text antialiasing before you display the text?

A) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,

RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

B) RenderingHints hint = new

RenderingHints(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_OFF); g2d.addRenderingHint(rh);

C) SwingUtilities.setAntialisingEnabled(false);

D) UIManager.setRenderingHints(Graphics2D.TEX_ANTIALIASING_ENABLED,

false);

E) You CANNOT control whether antialiasing is enabled. It depends on the native

windowing system.

Sample Code

public class SaveObject{

public static void main( String[] args ){

Employee smith = new Employee("012345","Smith","James","Payroll");

FileOutputStream fos = new FileOutputStream("smith.dat");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(smith);

fos.close();

}

}

176.                Given the above sample code, which of the following would prevent the code from working properly?

A) The class Employee does NOT implement Serializable.

B) The file "smith.dat" does NOT already exist.

C) The class Employee implements Externalizable.

D) The file "smith.dat" already exists.

E) The class Employee is declared as transient.

177.                In JavaIDL programming, the NamingContext allows you to bind objects to the naming service and look up objects. Which code fragment correctly gets a reference to the NamingContext (given that 'orb' is a reference to the ORB)?

A) NamingContext nc = orb.getNamingContext("NameService");

B) org.omg.CORBA.ObjectHolder oh = orb.lookup_reference("NameService");

NamingContext nc = ObjectHelper.toNamingContext(oh);

C) org.omg.CORBA.Any any = orb.resolve_name_service("NameService");

NamingContext nc = NamingContextHolder.convert(any);

D) java.lang.Object o = orb.lookup("NameService"); NamingContext nc =

(NamingContext) o;

E) org.omg.CORBA.Object o = orb.resolve_initial_references("NameService");

NamingContext nc = NamingContextHelper.narrow(o);

178.                Which of the following types of audio files does JDK 1.2 NOT support?

A) WAV

B) RMF

C) MIDI

D) AU

E) MP3

Sample Code

public class ArrayTest{

public static void main(String[] args){

// insert code here

}

}

179.                Given the above sample code, what would you insert to print out a list of the command-line arguments?

A) for(int i=0; i<args.length(); i++) System.out.println(args[i]);

B) for(int i=0; i<sizeof(args); i++) System.out.println(args[i]);

C) for(int i=0; i<args.length; i++) System.out.println(args[i]);

D) for(int i=0; i<args.getLength(); i++) System.out.println(args[i]);

E) for(int i=0; i<args.size(); i++) System.out.println(args[i]);

180.                When designing a custom GUI component, which interface should you implement to provide support for assistive technologies such as screen magnifiers and speech recognition?

A) You do NOT have to implement an interface; simply have your component

extend JComponent to inherit the functionality.

B) Observer

C) Externalizable

D) Accessible

E) InputMethodListener

Sample Code

static {

Additional code here

}

181.                In reference to the above, what does a static code block mean?

A) Internal variables are erased when the object is written to persistent storage.

B) All methods and variables defined inside block are implicitly static.

C) All internal variables must be "static".

D) The internal code will be executed once when the class is first loaded.

E) A compiler error will occur due to an incomplete method definition.

Sample Code

class Employee{

protected String name, salary;

public Employee() {}

public Employee(String aName, String aSalary) {

name=aName; salary=aSalary;

}

public String toString(){ return (name + ", " + salary); }

}

class Manager extends Employee{

protected String car;

public Manager(String aName, String aSalary, String aCar) {

car = aCar;

super( aName, aSalary );

}

public String toString(){ return (name + ", " + salary + ", " + car); }

}

public class EmployeeTest{

public static void main( String[] args ){

Employee[] employees = new Employee[3];

employees[0] = new Employee("Smith","$25,000");

employees[1] = new Employee("Jones","$35,000");

employees[2] = new Manager("Wilson","$45,000","BMW");

for(int i=0; i<employees.length; i++)

System.out.println(employees[i]);

}

}

182.                Given the above sample code, what will be the result when the code is run?

A) The code will NOT compile, because the Manager class cannot access name

and salary from the Employee class.

B) Smith, $25,000 Jones, $35,000 Wilson, $45,000, BMW

C) The code will NOT compile, because System.out.println() does not take an

Employee parameter.

D) The code will NOT compile, because "super(aName,aSalary);" must be the first

line in the Manager constructor.

E) Smith, $25,000 Jones, $35,000 Wilson, $45,000

183.                When are constructors invoked?

A) When the object needs garbage collection.

B) When the java virtual machine begins garbage collection.

C) When a superclass object is instantiated.

D) When any method is invoked on an object.

E) When a new instance of a class is instantiated.

Sample Code

class A {

int getAbs(int i) {

return Math.abs(i);

}

}

184.                Why is an object of class Math was not instantiated before calling abs()?

A) Any class's methods can be invoked without instantiating first.

B) Math is a final class.

C) There is an error.

D) Because method abs() is static.

E) Math belongs to the java.lang package.

Sample Code

class MyXML implements java.io.Serializable {

transient String name;

transient String value;

Vector subTree = new Vector();

public MyXML() {}

public void insert(MyXML x) { subTree.addElement( x ); }

static final long serialVersionUID = 3487495895819393L;

}

185.                What would happen if you modified the class above by removing the transient keywords and then loading a previously serialized object?

A) The object would be deserialized with name and value set to null.

B) A new "empty" instance of class MyXML would be created.

C) The object would load normally with name and value set to their previous state.

D) Nothing. A compiler error would occur because serialVersionUID is defined.

E) An exception would be thrown.

186.                What is Java serialization?

A) Distributed persistence.

B) The ability transform the state of an object into bits and resurrect a copy of the

object from those bits.

C) Remote method invocation.

D) Marshaling and unmarshaling of remote objects.

E) The ability to examine the encapsulated data of a class.

187.                How can you ensure compatibility of persistent object formats between different class versions?

A) Add "transient" variables.

B) Implement java.io.Serilizable, add a serial version UID, and write your own

readObject() method to handle the different versions.

C) Make the whole class transient.

D) Implement java.io.Serializable.

E) Override the default ObjectInputStream and ObjectOutputStream.

188.                What are the two main types of persistence for entity EJBs?

A) Bean-managed and Container-managed

B) Client-managed and Server-managed

C) Context-managed and Session-managed

D) Applet-managed and Servlet-managed

E) Application-managed and Database-managed

189.                What are the two main types of persistence for entity EJBs?

A) Bean-managed and Container-managed

B) Client-managed and Server-managed

C) Context-managed and Session-managed

D) Applet-managed and Servlet-managed

E) Application-managed and Database-managed

Sample Code

class A{ }

class B extends A{ }

class C extends A{ }

class Test{

public static void main(String[] args){

A a = new A();

B b = new B();

C c = new C();

// assignment here

}

}

190.                Given the above sample code, which of the following assignments would be legal?

A) c=a

B) a=b

C) b=a

D) b=c

E) None of the above.

Sample Code

// C++ Constant Definition

#define ANSWER_TO_ULTIMATE_QUESTION 42

191.                Referring to the code above, how would do you define an equivalent constant in Java?

A) static int ANSWER_TO_ULTIMATE_QUESTION = 42;

B) public transient int ANSWER_TO_ULTIMATE_QUESTION = 42;

C) public static native long ANSWER_TO_ULTIMATE_QUESTION = 42L;

D) static volatile int ANSWER_TO_ULTIMATE_QUESTION = 42;

E) public static final int ANSWER_TO_ULTIMATE_QUESTION = 42;

Sample Code

class HelloWorld extends java.awt.Canvas {

String str = "Hello World";

public void paint(java.awt.Graphics g) {

FontMetrics fm = g.getFontMetrics();

g.setColor(java.awt.Color.black);

Dimension d = getSize();

__?__

}

}

192.                Which code segment below can be inserted into the method above to paint "Hello World" centered within the canvas?

A) g.drawText( str, d.width, d.height, Font.CENTERED );

B) g.drawString( str, d.width/2, d.height/2 );

C) g.drawString( str, d.width/2 - fm.stringWidth(str)/2, d.height/2 -

fm.getHeight()/2);

D) g.drawText( str, 0, 0);

E) g.translate( d.width/2 - fm.stringWidth(str), d.height/2 - fm.getHeight());

g.drawString( str, 0, 0);

193.                Which of the following Swing components is NOT a lightweight component?

A) JButton

B) JPanel

C) JFrame

D) JRootPane

E) JList

Sample Code

class StopWatch {

java.util.Calendar cal1,cal2;

public void start() {

cal1 = java.util.Calendar.getInstance();

}

public void stop() {

cal2 = java.util.Calendar.getInstance();

}

public long getDifference() {

long diff = 0;

try {

diff = ________________________;

} catch (Exception e) {

diff = -1;

}

return diff;

}

}

194.                Referring to the above, what should the local variable "diff" be set to, in the getDifference() method, so that the number of seconds elapsed is returned?

A) cal2.getTimeInMillis() - cal1.getTimeInMillis()

B) (long) (cal2 - cal1)

C) cal2.get(java.util.Calendar.SECOND) - cal1.get(java.util.Calendar.SECOND)

D) (cal2.getTime().getTime() - cal1.getTime().getTime()) / 1000

E) None, as the calendar class doesn't keep track of time, just dates.

195.                How may an applet be sent unsolicited messages from a remote (server) application?

A) By installing a SecurityManager that permits listening on a port.

B) By creating and exporting a remote object, then sending a reference to the

server for RMI updates.

C) By registering with a remote application on a platform different from that which

served the applet.

D) By setting up a socket that listens on a specific port.

E) By setting the java.rmi.server.codebase property to the remote server location.

196.                An applet requires a method in java.awt.Panel that became available in the java 1.1 release. If the applet loads in a browser that only supports java 1.0, what will the browser do?

A) It will request the class file from the web server.

B) It will throw a NoSuchMethodException, ignore the missing methods, and

continue.

C) It will reject the entire web page and revert to the previous page.

D) It will open a window asking permission to load a core java class from an

untrusted source.

E) It will throw a NoSuchMethodError and not load the applet.

Sample Code

public class Test{

public static void main(String[] args){

int x=5, y=7;

swap(x,y);

System.out.println("x = " + x + ", y = " + y );

}

static void swap(int a, int b){

int c = a;

a = b;

b = c;

}

}

197.                Given the above sample code, what will be printed when the Test program is run?

A) x = 5, y = 7

B) x = 12, y = 12

C) x = 7, y = 5

D) x = 0, y = 0

E) The code will not compile, because the swap() method is not visible from

main().

Sample Code

static {

System.loadLibrary("mNativeLib");

}

public int myMethod(int count) {

Additional code here

}

198.                In reference to the above, if myMethod() is implemented in native code library "mNativeLib", how must its declaration be changed?

A) Replace it with native myMethod(int count) {}.

B) Move it into the static code block.

C) Replace it with public System.nativeMethod("myMethod(int)");.

D) Replace myMethod()'s code with System.execute("mNativeLib",

myMethod(count));.

E) Replace it with public native int myMethod(int count);.

Widget

199.                The widget shown above is similar to which standard java.awt class?

A) TextBox

B) Entry

C) TextField

D) TextArea

E) Label

Sample Code

public class RefTest{

private WeakReference wr;

public static void main(String[] args){

setWeak();

System.out.println("wr = " + wr.get());

}

public static void setWeak(){

String s = "Test";

wr = new WeakReference(s);

}

}

200.                Given the above sample code, what will be printed when the code is run?

A) wr = null

B) A NullPointerException will be thrown.

C) wr = Test

D) It depends on whether the garbage collector has run. If it has NOT: wr = Test If

it has: wr = null

E) The code will NOT compile, because the private variable wr is not visible to

main().

201.                What does it mean if a method is final synchronized?

A) Methods which are synchronized cannot be final.

B) Only one synchronized method can be invoked at a time for the entire class.

C) All final variables referenced in the method can be modified by only one thread

at a time.

D) The method cannot be overridden and is therefore certain to be threadsafe.

E) This is the same as declaring the method private.

Sample Code

public void parseUserList( List users ){

Iterator iterator = users.iterator();

while( iterator.hasNext() ){

String user = iterator.next();

if( user.equals("Smith") )

iterator.remove();

}

}

202.                The above sample code is a method that takes a list of usernames and parses them to remove any users named "Smith". What is wrong with the code?

A) Iterator does not have a method called next(); it should be nextElement().

B) Iterator does not have a method called hasNext(); it should be

hasMoreElements().

C) next() returns an Object, NOT a String, so you have to cast the returned value

to a String.

D) Iterator does not support removing elements from the underlying List; you

should use users.remove("Smith").

E) List does not have a method called iterator(); it should be getIterator().

Sample Code

Object open(String clsName) throws Exception {

Class cls = Class.forName( clsName );

return cls.newInstance();

}

203.                What would happen if the open() method as shown above was called with "java.io.FileInputStream" as the parameter?

A) A java.lang.InstantiationException exception is thrown.

B) A new java.io.FileStream instance is returned.

C) A java.io.FileNotFound exception is thrown.

D) Nothing. A compilation error would occur.

E) A java.lang.SecurityException exception is thrown.

Sample Code

import java.awt.*;

class A extends Frame implements ActionListener,

WindowListener {

Button button1;

public A() {

button1 = new Button("Click Me");

button1.addActionListener(this);

add(button1);

show();

}

public actionPerformed(ActionEvent e) {}

void b1() { return; }

}

204.                In reference to the above, what statement should be added to actionPerformed() so that b1() is invoked for a click on button1?

A) if(e.getActionCommand().equals("button1")) b1();

B) if(e.type == ButtonAction) b1();

C) if(e.getSource().equals(button1)) b1();

D) if(e.target == button1) b1();

E) b1();

Sample Code

import java.awt.*;

class A extends Frame implements ActionListener,

WindowListener {

Button button1;

public A() {

button1 = new Button("Click Me");

button1.addActionListener(this);

add(button1);

show();

}

public actionPerformed(ActionEvent e) {}

void b1() { return; }

}

205.                In reference to the above, what statement should be added to actionPerformed() so that b1() is invoked for a click on button1?

A) if(e.getActionCommand().equals("button1")) b1();

B) if(e.type == ButtonAction) b1();

C) if(e.getSource().equals(button1)) b1();

D) if(e.target == button1) b1();

E) b1();

206.                Which web technology do Servlets replace?

A) CGI scripts

B) Cookies

C) Dynamic HTML

D) JavaScript

E) HTTPS

Sample Code

public class SetTest{

public static void main(String[] args){

SortedSet ss = new TreeSet();

for(int j=0; j<args.length; j++){

ss.add(args[j]);

}

Iterator i = ss.iterator();

while( i.hasNext() ){

System.out.println(i.next());

}

}

}

207.                Given the above sample code, what will be printed when the program is run with the following command-line? >java SetTest red blue red green

A) blue green red

B) red blue

C) red blue red green

D) red blue green

E) blue green red red

Sample Code

public class Test{

public static void main(String[] args){

StringBuffer[] messages = new StringBuffer[5];

messages[0].append("Hello world!");

System.out.println("First message is " + messages[0]);

}

}

208.                What will be the output when the above sample code is run?

A) First message is null.

B) First message is Hello World!

C) A NullPointerException will be thrown.

D) An ArrayIndexOutOfBounds will be thrown.

E) The code would not compile.

Sample Code

big_loop: for(int i = 0; i < 3; i++) {

try {

for(int j = 0; j < 3; j++) {

if (i==j) continue;

else if (i>j) continue big_loop;

System.out.print("A ");

}

}

finally {

System.out.print("B ");

}

System.out.print("C ");

}

209.                What is the output from the program above?

A) A B C A B C A B C

B) A A A B C A A A B C A A A B C

C) A A B C B B

D) A A B B C A C A

E) None. The program will enter into an infinite loop.

210.                When a remote class is loaded, how does java (JVM) ensure the bytecode is safe?

A) The RMIClassLoader verifies the digital signature of the class.

B) The RMIClassLoader performs bytecode verification.

C) The JVM performs bytecode verification.

D) If the SecurityManager object permits the load, it is considered safe.

E) Remote object stubs use a separate memory space inside the JVM.

211.                What class could be subclassed to package several locale-specific versions of a set of greetings used by an application?

A) java.text.RuleBasedCollator

B) java.text.CollationKey

C) java.util.Locale

D) java.util.TimeZone

E) java.util.ResourceBundle

212.                Which of the following is NOT an advantage of using Swing?

A) Swing components will run in all commercially available browsers.

B) Lightweight components give a standard look and feel across platforms.

C) It provides greater functionality than standard AWT components.

D) Pluggable look and feel allows the end-user to easily change the appearance

of an application.

E) It uses native OS widgets for more compliant look and feel.

Sample Code

class A {

int i=0;

public A() { i=8; }

public static void main(String args[]) {

A h = new A();

while (h.i <= 10) h.doIt();

}

public static void doIt() {

i++;

System.out.println("Hello");

}

}

213.                What will the above program do?

A) It will print "Hello" once.

B) It will print "Hello" twice.

C) It will not run because the proper packages have not been imported.

D) It will not compile because doIt() cannot reference non-static variable i.

E) It will print "Hello" 11 times.

214.                What happens if a parameter is passed to a remote object (using RMI) which does NOT implement Remote or Serializable?

A) A java.rmi.MarshallException is thrown.

B) A java.lang.NullPointerException is thrown.

C) It is passed by value.

D) It is passed by reference.

E) The code will not compile.

Sample Screen

Object 1 Here

Object 2 Here Object 3 Here Object 4 Here

Object 5 Here

215.                To display five objects as shown above using all available screen space, what Layout Manager would be easiest?

A) BorderLayout

B) CardLayout

C) GridLayout

D) null

E) FlowLayout

216.                How can you know when a user closes a window so you can perform cleanup?

A) By creating an inner class called WindowListener, extending

WindowEventHandler, then putting cleanup code in a processEvent(Event e)

method.

B) By implementing FrameListener and placing cleanup code in a

frameClosing(FrameEvent e) method.

C) By placing cleanup code in a try - catch block that catches a

FrameClosingException.

D) By implementing WindowListener and putting cleanup code in a public void

windowClosing(WindowEvent e) method.

E) Java does cleanup automatically when a window is closed.

Sample Code

public drawThickLine(Graphics2D g, x1, y1, x2, y2){

// set line thickness here

g.drawLine(x1,y1,x2,y2);

}

217.                Given the above sample code, what code would you insert at the indicated point to make the method draw a line that is ten pixels wide?

A) g.setPen( new DefaultPen(10) );

B) g.setLineWidth(10);

C) g.setBrush( new Brush(10.0) );

D) g.setStroke( new BasicStroke(10.0f) );

E) Stroke s = new Stroke(); s.setWidth(10); g.setStroke(s);

218.                Which code segment could execute the stored procedure "countRecs()" located in a database server?

A) PreparedStatement pstmt = connection.prepareStatement("countRecs()");

pstmt.execute();

B) Statement stmt = connection.createStatement();

stmt.executeStoredProcedure("countRecs()");

C) Statement stmt = connection.createStatement();

stmt.execute("COUNTRECS()");

D) StoredProcedureStatement spstmt =

connection.createStoredProcedure("countRecs()");

spstmt.executeQuery();

E) CallableStatement cs = con.prepareCall("{call COUNTRECS}");

cs.executeQuery();

219.                JDK 1.2 includes Reference objects such as WeakReference and PhantomReference. How would you create your own type of Reference object?

A) Extend Reference.

B) Write methods to interact with the garbage collector.

C) You CANNOT create your own Reference type.

D) Implement Reference.

E) Create a class with a Reference attribute.

220.                Which Java API would you use while writing Java objects that act as servers for distributed CORBA objects written in C++?

A) JNI

B) JDBC

C) Infobus

D) JavaIDL

E) RMI

221.                Which of the following commands starts the Java IDL name service on port 1234?

A) nameserver -InitialPort 1234

B) tnameserv -ORBInitialPort 1234

C) cosnaming -COSInitialPort 1234

D) idlregistry -IDLInitialPort 1234

E) nameservice 1234

222.                What is Java serialization?

A) Distributed persistence.

B) The ability to examine the encapsulated data of a class.

C) Remote method invocation.

D) The ability transform the state of an object into bits and resurrect a copy of the

object from those bits.

E) Marshaling and unmarshaling of remote objects.

223.                How would you create a menu item "Save" with a shortcut key of "Ctrl+S"?

A) JMenuItem save = new JMenuItem("Save"); save.addShortcutKey( new

KeyStroke(KeyStroke.S | KeyStroke.CTRL_KEY) );

B) JMenuItem save = new JMenuItem("Save"); save.setMnemonic("Ctrl+S");

C) You would have to override the KeyPressed event of the top level Frame, and

handle the "Ctrl+S" to call the menu item's actionPerformed.

D) JMenuItem save = new JMenuItem("Save");

save.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_S,Event.CTRL_MASK));

E) JMenuItem save = new JMenuItem("Save");

save.enableShortcut(KeyEvent.CTRL_KEY + KeyEvent.S);

public void print(Printable p){

PrinterJob pj = PrinterJob.getPrinterJob();

PageFormat pf = pj.pageDialog(pj.defaultPage());

pj.setPrintable(p,pf);

// now get user to select properties and confirm print

}

224.                Given the above sample code, which takes a Printable object and sets up a PrinterJob to print that object, what code would you use to allow the user to select properties for the print job, confirm, and then print?

A) p.print();

B) pj.printerDialog(pj.getDefaultPrinterOptions()); if( pj.printConfirmed() ) p.print();

C) PrinterDialog pd = new PrinterDialog(); if( pd.show() == Dialog.OK ) pj.print(p);

D) Properties props = pj.getUserOptions();

if(((Boolean)props.getValue(PrinterJob.CONFIRM)).equals(true)) p.print(pj);

E) if( pj.printDialog() ) pj.print();

225.                What is an RMI "stub"?

A) It acts as a client-side proxy to receive RMI calls and pass them to the server.

B) It receives RMI calls from the server to enable applet callbacks.

C) It is used by the client to find remote objects on a server.

D) It is the interface implemented by both the client and server objects.

E) It enables applets to make RMI calls without violating browser security.

226.                Which of the following types of audio files does JDK 1.2 NOT support?

A) MIDI

B) RMF

C) AU

D) MP3

E) WAV

1: Date myDate = new Date();

2: DateFormat dateFormat = DateFormat.getDateInstance();

3: String myString = dateFormat.format(myDate);

4: System.out.println( "Today is " + myString );

227.                How can you change line 2 above so that the date is displayed in the same format used in China?

A) DateFormat dateFormat = DateFormat.getDateInstance();

dateFormat.setLocale( java.util.Locale.CHINA );

B) DateFormat dateFormat = DateFormat.getDateInstance(

DateFormat.SHORT, java.util.Locale.CHINA);

C) java.util.Locale locale = java.util.Locale.getLocale("China");

DateFormat dateFormat = DateFormat.getDateInstance( locale );

D) DateFormat.setLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance();

E) java.util.Locale locale = java.util.Locale.getLocale( java.util.Locale.CHINA );

DateFormat dateFormat = DateFormat.getDateInstance( locale );

228.                How would you implement a text field for entering a password in a Login dialog using Swing components?

A) By using a JTextField and call setEchoChar('*').

B) By using a JPasswordField.

C) By using a JTextField and adding an event handler for the KeyPressed event

to echo a '*' character.

D) By creating your own class which extends JTextField and overrides the

keyDown() method to echo a '*' character.

E) use a JTextComponent and call

setTextDisplay(JTextComponent.PASSWORD).

229.                Which aspect(s) of the bean is used to modify or retrieve the JavaBeans properties?

A) Accessor methods

B) Persistence mechanism

C) propertyManager() method (required in all beans)

D) Event adapters

E) Associated java.beans.PropertyChangeListener class methods

class A {

Object get(Object o) {

try {

return o.getClass().getName();

} catch (Exception e) {

return null;

}

}

}

230.                Referring to the above, what is the expected output when the following code is executed?

A a = new A();

Vector v = new Vector();

System.out.println( a.get( v ) );

A) NullPointerException

B) A

C) Object

D) null

E) java.util.Vector

231.                What does double-buffering in animations do?

A) It draws the next frame to an off-screen image object before displaying to

eliminate flicker.

B) It prevents "hanging" using a MediaTracker object to ensure all frames are

loaded before beginning.

C) It puts multiple frame in the same file and uses cropImage() to select the

desired frame.

D) It uses a small image as wallpaper and a transparent image as the actual

frame.

E) It draws each image to the screen twice to eliminate white spots.

class Class1 {

int total=0;

public static void main(String args[]) {

doIt();

}

void doIt() {

for(int i=0;i<5;i++) total += i;

System.out.println(total);

}

}

232.                In reference to the above, how should the first line of method main() be changed to call doIt()?

A) Class1();

B) Class1 class1 = new Class1();

C) (new Class1()).doIt();

D) Class1().doIt();

E) No change is necessary.

233.                In a CORBA application, how would a client create a new remote object on the server?

A) By calling an existing server object's "factory" method which would create a

new object and return a reference to the client.

B) By using com.omg.CORBA.ORB.string_to_object() method to instantiate a new

object from a stringified object reference.

C) By using a naming service, such as the tnameserv in JDK 1.2, to create the

object.

D) By using the Remote Object Activation facility.

E) By using the server objects Home interface which provides methods for finding,

creating, and deleting objects.

static {

System.loadLibrary("mNativeLib");

}

public int myMethod(int count) {

Additional code here

}

234.                In reference to the above, if myMethod() is implemented in native code library "mNativeLib", how must its declaration be changed?

A) Replace myMethod()'s code with System.execute("mNativeLib",

myMethod(count));.

B) Replace it with native myMethod(int count) {}.

C) Replace it with public System.nativeMethod("myMethod(int)");.

D) Move it into the static code block.

E) Replace it with public native int myMethod(int count);.

235.                Which of the following is a requirement of a JavaBean?

A) Define a java.beans.PropertyEditor.

B) Use of the java.beans.PropertyChangeListener.

C) Provide a no-argument constructor.

D) Implement the java.beans.BeanInfo interface.

E) Extend java.beans.BeanDescriptor.

236.                How would you disable tooltips in a Swing based Java application?

A) Tool tip support is determined by the underlying windowing system, and cannot

be changed by a Java application.

B) UIManager.disableToolTips();

C) ToolTipManager.sharedInstance().setEnabled(false);

D) For each component in the application call: JComponent.setToolTipText(null);

E) SwingUtilities.setToolTipsEnabled(false);

237.                Which of the following is NOT a valid java.lang.String declaration?

A) String myString = new String();

B) String cde = "cde";

C) String myString = new String(5);

D) char data[] = {'a','b','c'};

String str = new String(data);

E) String myString = new String("Hello");

238.                Which of the following is true for untrusted applets running on most browsers?

A) Applets can connect to computers other than the codebase.

B) Applets can read to or write from files in the "/tmp" or "c:\tmp" directory.

C) Applets can change the ClassLoader.

D) Applets can retrieve the user's account name.

E) Applet frames display a warning.

239.                In reference to the above, when you click on the button the applet changes background colors. Which method must it call to do this?

A) repaint()

B) shade()

C) draw()

D) setbgcolor()

E) restart()

240.                In what way is it possible to circumvent applet security restrictions?

A) Install a different SecurityManager.

B) Attach a trusted digital signature to the downloaded applet JAR file.

C) Replace the default ClassLoader.

D) Connect to a ActiveX control located in the same web page.

E) There is no way to circumvent applet security restrictions.

1: class C extends Thread {

2: public void run() {

3: while(true) {

4: System.out.println("Hello World!");

5: try {

6: sleep(100);

7: } catch(Exception e) {}

8: }

9: }

10: public static void main(String[] s) {

11: C c = new C();

12: c.start();

13: }

14: }

241.                What is the result of the program above?

A) A java.lang.StackOverflowException is thrown.

B) The CPU is used complete up by the infinite loop.

C) Nothing. Compiler error on line 6.

D) The system exits immediately with little or no output.

E) "Hello World!" is printed forever.

public class TestApplet extends JApplet{

public void init(){

JButton b1 = new JButton("one");

JButton b2 = new JButton("two");

JButton b3 = new JButton("three");

JButton b4 = new JButton("four");

JButton b5 = new JButton("five");

getContentPane().add(b1);

getContentPane().add(b2);

getContentPane().add(b3);

getContentPane().add(b4);

getContentPane().add(b5);

}

}

242.                Given the above sample code of a JApplet, what would be displayed when the applet is run?

A) Only the button "five", occupying the entire area of the applet.

B) Five buttons, "one","two","three","four","five", in a column top to bottom.

C) Five buttons, "one","two","three","four","five", in a row left to right.

D) Only the button "one", occupying the entire area of the applet.

E) Five buttons, "one","two","three","four","five", randomly located within the

applet.

 

package mypackage;

class MyException extends java.lang.Exception {

public MyException() { super(); }

public MyException( String s ) { super(s); }

}

243.                Referring to the above, which code segment properly generates an exception of type "MyException"?

A) exception new MyException();

B) new Exception( MyException );

C) catch( MyException e) { }

D) throw new MyException("Error Occurred!");

E) MyException e = new MyException();

return e;

 

244. Which of the following class defines a legal abstract class ?

    1. class Animal { abstract void grow1( ); }
    2. adstract Animal { abstract void grow1( ); }
    3. class abstract Animal { abstract void grow1( ); }
    4. abstract class Animal { abstract void grow1( ); }
    5. abstract class Animal { abstract void grow1( );

{ System.out.println(grow1); } }

245. For an object to be a target foe a thread, that object must be of type ________

246. What is the proper way of defining a class named key so that it cannot be subclassed ?

    1. class Key { }
    2. abstract final class Key { }
    3. native class Key { }
    4. class Key { final: }
    5. final class key { }

247. What modes are legal for creating a new RandomAccessFile object ?

    1. w
    2. r
    3. x
    4. rw
    5. xrw

248. In RMI, Using which class to create ServerSide Object.

    1. ServerSocket
    2. Server
    3. UnicastRemoteObject
    4. MulicastSocket

249. In RMI application, using whaic object to interact with Server object from the Client Object.

    1. Remote
    2. RMIServer
    3. Skeleton
    4. Stub

250. In RMI which class is using to bind the Server object with 'rmiregistry'.

    1. ServerScoket
    2. Naming
    3. Binding
    4. MultiSocket

251. In RMI Server application you must extend the which interface.

    1. RMIServer
    2. RemoteServer
    3. Remote
    4. None of the above.

252. Given the following code:

Class Tester {

Public static void mani (String [ ] args) {

CellPhone cell = new CellPhone( );

Cell.emergency( );

}

}

class Phone

{

final void dial911( )

{

//code to dial 911 here . . .

}

}

class CellPhone extends Phone {

void emergency( ) {

}

}

What will happen when you try to compile and run the Tester class ?

    1. The code will not compile because Phone is not also declared as final.
    2. The code will not compile because you cannot invoke a final method from a subclass.
    3. The code will compile but will throw a NoSuchMethodException when Tester is run.
    4. Phone and CellPhone are fine but Tester will not compile because it cannot create an instance of a class that derives from a class defining a final method.

253. Which assignments are legal ? (Select all valid answers)

    1. long test = 043;
    2. float f = -293;
    3. int other = (int) true;
    4. double d = 0x12345678;
    5. short s = 10;

254. Given this class definitions:

Abstract class Transaction implements Runnable { }

class Deposit extends Transaction {

protected void process( ) {

addAmount( );

}

void undo(int I) {

System.out.println("Undo");

}

}

255. Using which interface in the java.sql package to establish the connection between and database Server.

    1. Connection
    2. Statement
    3. SqlConnection

256. Before create connection to database server using ODBC from java application, we must load the which class.

    1. java.jdbc.odbc.Odbc
    2. java.odbc.jdbc.JdbcOdbcDriver
    3. java.jdbc.odbc.JdbcDriver
    4. java.jdbc.odbc.JdbcOdbcDriver

257. Which class we can create parameterized querys in JDBC application.

    1. Statement
    2. PreparedStatment
    3. CallableStatement
    4. None of the above

258. Which method in the Connection Interface, we get the Statement object based on the SQL query.

    1. executeQuery( )
    2. getStatement( )
    3. createStatement( )
    4. getResultSet( )

259. Whenever you submit your request to the Servlet application using GenericServlet, Which method is called

    1. doGet( )
    2. doPost( )
    3. service( )
    4. all of the above

260. Which class in the Servlet application is using to get parameters from client application.

    1. ServletClient
    2. Request
    3. GenericServlet
    4. ServletRequest

261. Which method in the ServletResponse class to give the reference of the client page, to give the plain text response to the client page.

    1. getClientPage( )
    2. getOutputStream( )
    3. getWriter( )
    4. getResponse( )

262. What will happen if we attempted to complie the code ? Select the one right answer.

    1. This code will not compile because the parameter I is not used in undo( ).
    2. This code will not compile because there is not main( ) method.
    3. This code will not compile because Deposit must be an abstract class.
    4. This code will not compile because Deposit is not declared public
    5. Everything will compile fine.

263. Which exception might wait( ) throw ? ___________

264. Which of the following are not Java keywords

abstract, double, int, static, boolean, else, interface, super, break, extends, long, superclass, byte, final, native, switch, case, finally, new, synchronized, catch, float, null, this, char, for, open, throw, class, if, private, transient, const, implements, protected, try, continue, import, public, void, default, instanceOf, return, volatile, do, integer, short, while (Select all valid answers);

    1. superclass
    2. goto
    3. open
    4. close
    5. integer
    6. goto, import
    7. goto, superclass, open, close
    8. they are all valid keywords.

265. Which of the following represents an octal number ?

    1. 0x12
    2. 320
    3. 032
    4. (octal) 2
    5. 1

266. What will run on the standard output when we run the Tester class ?

class Tester {

int var;

Tester(double var) {

This.var = (int) var;

}

Tester(int var) {

this("hello");

}

Tester(string s) {

this( );

System.out.println(s);

}

Tester( ) {

System.out.println("good bye");

}

public static void main(String [ ] arg) {

Tester t = new Tester(5);

}

}

    1. noting
    2. "hello"
    3. 5
    4. "hello" followed by "good bye"
    5. "good bye" followed by "hello"

267. Write a line of code to use the String[ ] s substring( ) method to obtain the substring "lip" a string instance named s that is set to "tupil". _______________.

268. There a number of labels in the source code below. These are labeled a through I. Which label identifies the earliest point where, after that line has executed, the object referred to by the variable first may be garbage collected ?

class Riddle {

public static void mani(String[ ] args) {

String first, second;

String riddle;

If (arg.length < 2)

return;

1: first = new String) args[0]);

2: second = new String(args[1]);

3: riddle = "when is a " + first;

4: first = null;

5: riddle += "like a" + second + "?";

6: second = null;

7: System.out.println(riddle);

8: args[0] = null;

9: args[1] = null;

}

}

select the right answer:

    1. 4:
    2. 5:
    3. 8:
    4. 9:

269. What are the range of values for a variable of type byte ?

    1. -2^7 to 2^7 - 1
    2. 0 to 2^7
    3. 2^15 to 2^15
    4. 2^15 to 2^15 - 1
    5. 2^15 - 1 to 2^15

270. What is a Thread?

    1. a process
    2. a task
    3. a sequence of execution
    4. a program

271. Which method is Thread class gives the reference of the currently active Thread.

    1. activeThread( )
    2. getActiveThread( )
    3. currentThread( )
    4. getCurrentThread( )

272. Whenever a thread starts executing which method is executing automatically.

    1. run( ).
    2. start( )
    3. main( )
    4. execute( )

273. Which keyword in the method declaration is used to lock the object when the Thread starts execute the method.

    1. lock
    2. synchronized
    3. block
    4. transient

274. Which class in the java.net package, we can get the Ipaddress of the one computer.

    1. IPaddress
    2. ServerAddress
    3. InetAddress
    4. Socket

275. Which method in the ServerSocket class is using to listen for client request.

    1. getConnection( )
    2. wait( )
    3. listen( )
    4. accept( )

276. Which class in swing package we can create Border for one Component.

    1. Border
    2. BorderFactory
    3. Line
    4. Rect

277. Which class in swing to change the appearance of the Frame at runtime.

    1. Jframe
    2. UIManager
    3. UserInterface
    4. Jpanel

278. Which is True statement

    1. Swing is creating components using platform depentent API, but AWT is using its own API.
    2. Swing and AWT are creating components using its own API.
    3. Swing and AWT are creating components using platform depentent API.
    4. Swing is creating components using its own API, but AWT is using platform depentent API.
    5. None of the above.

279. Consider the following code:

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?

b. i = 0 j = 1

c. i = 0 j = 2

d. i = 1 j = 0

f. i = 1 j = 2

280. What is the range of values that can be assigned to a variable of type short?

281. Which of the statements below are true? (Chose none, some, or all.)

a. UTF characters are as big as they need to be.

b. Unicode characters are all 16 bits. There is no

c. such thing as a Bytecode character; bytecode is the

d. format generated by the Java compiler.

282. True or false: A signed data type has an equalnumber of non-zero positive and negative values available.

283. What results from the following fragment of code?

1. int x = 1;

2. String [] names = { "Fred", "Jim", "Sheila" };

3. names[--x] += ".";

4. for (int i = 0; i < names.length; i++) {

5. System.out.println(names[i]);

6. }

Consider the following line of code:

int x[] = new int[25];

After execution, which statement or statements are true?

What is the output of this code fragment?

1. int x = 3; int y = 10;

2. System.out.println(y % x);

284. True or False: in the code fragment below, after execution of line 1, sbuf references an instance of the StringBuffer class. After execution of line 2, sbuf still references the same instance.

1. StringBuffer sbuf = new StringBuffer("abcde");

2. sbuf.insert(3, "xyz");

285. Which are the foll. is illegal.

a.friendly string s;

b.transient int i = 41;

c.public final static native int w();

d.abstract double d;

e.abstract final doubnle byperboliccosine();

A is illegal because friendly is not a keyword.

B is a legal transient declaration.

C is strange but legal.

D is illegal because only methods and classes may

be abstract.

E is illegal because abstract and final

are contradictory.

286. You execute the code below in an empty directory. What is the result?

1. File f1 = new File("dirname");

2. File f2 = new File(f1, "filename");

287. True or False: in the code fragment below, after execution of line 1, sbuf references an instance of the StringBuffer class. After execution of line 2, sbuf still references the same instance.

1. StringBuffer sbuf = new StringBuffer("abcde");

2. sbuf.append(3, "xyz");

288. After execution of the code fragment below, what are the values of the variables x, a, and b?

1. int x, a = 6, b = 7;

2. x = a++ + b++;

289. Consider the following application:

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.

10. class Decrementer {

11. public void decrement(double decMe) { decMe = decMe - 1.0; }

12. }

What value is printed out at line 6?

290. Which one statement is true about the application below?

1. class StaticStuff

2. {

3. static int x = 10;

4.

5. static { x += 5; }

6.

7. public static void main(String args[])

8. {

9. System.out.println("x = " + x);

10. }

11.

12. static {x /= 5; }

13. }

291. Which of the following statements are true? (Choose one or more.)

a: an inner jclass may be declared private.

b: an inner class may be declared static.

c: construction of an inner class may requiere an

instance of the outer class.

292. 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;

293. Which of the following may a menu contain

a: a separator

b: a menu

294. 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 of the statements is correct?

295. The code below draws a line. What color is the line?

1. g.setColor(Color.red.green.yellow.red.cyan);

2. g.drawLine(0, 0, 100, 100);

296. Consider these classes, defined in separate source files:

1. public class Test1 {

2. public float aMethod(float a, float b) throws IOException {

3. }

4. }

1. public class Test2 extends Test1 {

2.

3. }

Which of the following methods would be legal (individually) at line 2 in class Test2?

a: public int a method(INT A,INTB) throws exception {}

b: public float aMethod(float p,float q) {}

297. What results from attempting to compile and run the following code?

1. public class Ternary {

2. public static void main(String args[]) {

3. int x = 4;

4. System.out.println("value is " +

5. ((x > 4) ? 99.99 : 9));

6. }

7. }

298. true or false.

a:abstract class maynot contain final method.

b:final class maynot have any abstract

ans:b

299. A Java object is:

A.  An instance of a class. In it there are the data and the methods

which manage these data

B.  A variable of any type

C.  A particular structure, like a record , in which there are variables

of different types

300. Two different objects belonging to the same class:

A.  Share data

B.  Share the structure. They can share data too, through the static

keyword

C.  Share data and methods

D.  Share only methods

301. A class is:

A.  A collection of objects. The linking of objects represents the

Encapsulation

B.  type from which you can instantiate objects

C.  The implementation of an object in Java syntax

302. Inheriting a class B from another class A:

A.  B inherits all members from A. It's possible to exclude from inheriting some members with the static keyword

B.  B inherits all members from A. It's possible to exclude from inheriting some members with the protected keyword

C.  You instantiate different objects with same structure. It's the implementation of "polymorphism",one of the milestone of OO programming

D.  B inherits all attrubutes and methods from A, but it can access only the public, protected and package ones

303. What is function overloading?

A.  Happens when you declare too many functions in a Java block of code. In java this limit is fixed to 65536 functions

A.  It's the assigning of many tasks to one (or more) methods. It's an OOP milestone

B.  It's the assigning of the same name to many methods. It can be useful in presence of similar methods which behaves differently or have different parameters

304. What is method overriding?

A.  An overloading alias

B.  It doesn't exists, you invented it

C.  Redefining a method inherited from superclass, you specify its tasks

D.  Redefining a method inherited from superclass, you generalize its tasks

305. If class C extends B which in turn extends A and c, b, a are three instances of respective classes, which of next sentences are true:

A.  I can assign b to a

B.  I can assign a to b

C.  I can assign c to a

D.  I can assign a to c

E.  To an Object handle o I can assign a or b or c

306. Supposing in the AWT package (Abstract Window Toolkit) exists a graphic class "Button", what happens in this code fragment?

1.  

2.   Button p,q;

3.   p = new Button ("Ok");

4.   q = p;

5.   q.setLabel("Cancel");

6.  

A.  Two buttons, with "OK" and "Cancel" labels

B.  Two overlapping buttons, the last with "Cancel" label

C.  Two buttons, with "Cancel" and "Cancel" labels

D.  Only one button, with "Cancel" label

307. Supposing you have a class hierarchy with a "Shape" superclass, What does this code fragment do?

1.   public abstract class Shape{

2.  

3.   public void draw(int anX, int anY){...}

4.   }

5.  

6.   public class Square extends Shape{

7.   public void draw(int unX, int unY){\\ draw a square}

8.   }

9.  

10.   public class Circle extends Shape{

11.   public void draw(int unX, int unY){\\ draw a circle}

12.   }

13.  

14.   Square q = new Circle(x, y);

15.   q.draw();

16.  

A.  It's a typical example of polymorphism, but you should declare q of Shape type, not Square.

B.  It's a typical example of polymorphism. Being Square and Circle both of Shape type, the handles are compatible, and the mechanism of dynamic binding choose the method at run-time instead of compile-time

C.  It's a typical example of polymorphism, but you should declare q of Circle type, not Square.

308. What happens in this code fragment?

1.  

2.   String a = new String("Test");

3.   String b = new String("test");

4.   if (a==b)

5.   System.out.println(" Same");

6.   else

7.   System.out.println(" Different");

A.  Prints "Different", because a and b points to strings which are different for letter casing, and Java is case-sensitive

B.  Prints "Same", because the "==" operator is overridden in the String class

C.  Prints "Different", and it should do the same with any value

D.  Prints "Same", and it should do the same with any value

309. Which of the following are collection classes?
1) Collection
2) Iterator
3) HashSet
4) Vector

310. Which of the following are true about the Collection interface?
1) The Vector class has been modified to implement Collection
2) The Collection interface offers individual methods and Bulk methods such as addAll
3) The Collection interface is backwardly compatible and all methods are available within the JDK 1.1 classes
4) The collection classes make it unnecessary to use arrays

311. Which of the following are true?
1) The Set interface is designed to ensure that implementing classes have unique members
2) Classes that implement the List interface may not contain duplicate elements
3) The Set interface is designed for storing records returned from a database query
4) The Map Interface is not part of the Collection Framework

312. Which of the following are true?

313. Which method can be used to compare two strings for equality?

314. Which method can be used to perform a comparison between strings that ignores case differences?

315. What is the use of valueOf( ) method?

316. What are the uses of toLowerCase( ) and toUpperCase( ) methods?

317. Which method can be used to find out the total allocated capacity of a StrinBuffer?

318. Which method can be used to set the length of the buffer within a StringBuffer object?

319. What is the difference between String and StringBuffer?

320. What are wrapper classes?

321. Which of the following is not a wrapper class?

a.   String

b.   Integer

c.   Boolean

d.   Character

313. You wish to store a small amount of data and make it available for rapid access. You do not have a need for the data to be sorted, uniqueness is not an issue and the data will remain fairly static Which data structure might be most suitable for this requirement?


1) TreeSet
2) HashMap
3) LinkedList
4) an array

314. Which of the following are Collection classes?

1) ListBag
2) HashMap
3) Vector
4) SetList

315. How can you remove an element from a Vector?


1) delete method
2) cancel method
3) clear method
4) remove method


Author & Copyrights 2004: Narayanaswami Banukumar