Top Banner
Question Number 1 Which code segment could execute the stored procedure "countRecs()" located in a database server? Choice 1 Statement stmt = connection.createStatement(); stmt.execute("COUNTRECS()"); Choice 2 CallableStatement cs = con.prepareCall("{call COUNTRECS}"); cs.executeQuery(); Choice 3 StoreProcedureStatement spstmt = connection.createStoreProcedure("co untRecs()"); spstmt.executeQuery(); Choice 4 PrepareStatement pstmt = connection.prepareStatement("countR ecs()"); pstmt.execute(); Choice 5 Statement stmt = connection.createStatement(); stmt.executeStoredProcedure("countR ecs()"); ----------------------------------- ------------------------- Question Number 2 if(check4Biz(storeNum) != null) {} Referring to the above, what datatype could be returned by method check4Biz()? Choice 1 Boolean Choice 2 int Choice 3 String Choice 4 char Choice 5 byte ----------------------------------- ------------------------- Question Number 3 int j; for(int i=0;i<14;i++) { if(i<10) { j = 2 + i; } System.out.println("j: " + j + " i: " + i); } What is WRONG with the above code? Choice 1 Integer "j" is not initialized. Choice 2 Nothing. Choice 3 You cannot declare integer i inside the for-loop declaration. Choice 4 The syntax of the "if" statement is incorrect. Choice 5 You cannot print integer values without converting them to strings. ----------------------------------- ------------------------- Question Number 4 Which one of the following is a valid declaration of an applet? Choice 1 Public class MyApplet extends java.applet.Applet { Choice 2 Public Applet MyApplet { Choice 3 Public class MyApplet extends applet implements Runnable { Choice 4 Abstract class MyApplet extends java.applet.Applet { Choice 5 Class MyApplet implements Applet { ----------------------------------- ------------------------- Question Number 5
30
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 43486184-Java-MCQ-s

Question Number 1Which code segment could execute the stored procedure "countRecs()" located in a database server? Choice 1 Statement stmt = connection.createStatement(); stmt.execute("COUNTRECS()"); Choice 2 CallableStatement cs = con.prepareCall("{call COUNTRECS}"); cs.executeQuery(); Choice 3 StoreProcedureStatement spstmt = connection.createStoreProcedure("countRecs()"); spstmt.executeQuery(); Choice 4 PrepareStatement pstmt = connection.prepareStatement("countRecs()"); pstmt.execute(); Choice 5 Statement stmt = connection.createStatement(); stmt.executeStoredProcedure("countRecs()"); ------------------------------------------------------------Question Number 2if(check4Biz(storeNum) != null) {} Referring to the above, what datatype could be returned by method check4Biz()? Choice 1 Boolean Choice 2 int Choice 3 String Choice 4 char Choice 5 byte ------------------------------------------------------------Question Number 3int j; for(int i=0;i<14;i++) { if(i<10) { j = 2 + i; } System.out.println("j: " + j + " i: " + i); } What is WRONG with the above code? Choice 1 Integer "j" is not initialized. Choice 2 Nothing. Choice 3 You cannot declare integer i inside the for-

loop declaration. Choice 4 The syntax of the "if" statement is incorrect. Choice 5 You cannot print integer values without converting them to strings. ------------------------------------------------------------Question Number 4Which one of the following is a valid declaration of an applet? Choice 1 Public class MyApplet extends java.applet.Applet { Choice 2 Public Applet MyApplet { Choice 3 Public class MyApplet extends applet implements Runnable { Choice 4 Abstract class MyApplet extends java.applet.Applet { Choice 5 Class MyApplet implements Applet { ------------------------------------------------------------Question Number 5int values[] = {1,2,3,4,5,6,7,8}; for(int i=0;i< X; ++i) System.out.println(values[i]); Referring to the above, what value for X will print all members of array "values"? Choice 1 1 Choice 2 7 Choice 3 8 Choice 4 9 Choice 5 None, since there is a syntax error in the array declaration ------------------------------------------------------------Question Number 6public int m1(int x) { int count=1; try { count += x; count += m2(count); count++; } catch(Exception e) { count -= x; } return count; } Referring to the above, when m1(2) is invoked, m2() throws an ArithmeticException and m1() returns which one of the following?

Page 2: 43486184-Java-MCQ-s

Choice 1 1 Choice 2 2 Choice 3 3 Choice 4 4 Choice 5 The system will exit ------------------------------------------------------------Question Number 7System.getProperties().put( "java.rmi.server.codebase", "http://www.domain.com/classes/"); Which one of the following is a capability of the above code? Choice 1 Override CLASSPATH Choice 2 Register an rmi server on its host system Choice 3 Set the location of all applets in a web server Choice 4 Append CLASSPATH Choice 5 Facilitate dynamic class loading for remote objects ------------------------------------------------------------Question Number 8Which one of the following statements is FALSE? Choice 1 Java supports multi-threaded programming. Choice 2 Threads in a single program can have different priorities. Choice 3 Multiple threads can manipulate files and get user input at the same time. Choice 4 Two threads can never act on the same object at the same time. Choice 5 Threads are created and started with different methods. ------------------------------------------------------------Question Number 91 public static void main(String[] s) { 2 String n1, n2, n3; 3 n1 = "n1"; 4 n2 = "n2"; 5 n3 = "n3"; 6 { 7 String n4 = "inner";

8 n2 = n1; 9 } 10 n3 = null; 11 } How many instances of the String will be eligible for garbage collection after line 10 in the above code snippet is executed? Choice 1 0 Choice 2 1 Choice 3 2 Choice 4 3 Choice 5 The code will not compile. ------------------------------------------------------------

Question Number 10Which code declares class A to belong to the mypackage.financial package? Choice 1 package mypackage; package financial; Choice 2 import mypackage.*; Choice 3 package mypackage.financial.A; Choice 4 import mypackage.financial.*; Choice 5 package mypackage.financial;

Question Number 1How can you store a copy of an object at the same time other threads may be changing the object's properties? Choice 1 Override writeObject() in ObjectOutputStream to make it synchronized. Choice 2 Clone the object in a block synchronized on the object and serialize the clone. Choice 3 Nothing special, since all ObjectOutputStream methods are synchronized. Choice 4 Implement java.io.Externalizable instead of java.io.Serializable. Choice 5 Give the thread performing storage a higher priority than other threads.

Page 3: 43486184-Java-MCQ-s

------------------------------------------------------------Question Number 2Which statement about static inner classes is true? Choice 1 Static inner classes may access any of the enclosing classes members. Choice 2 Static inner classes may have only static methods. Choice 3 Static inner classes may not be instantiated outside of the enclosing class. Choice 4 Static inner classes do not have a reference to the enclosing class. Choice 5 Static inner classes are created when the enclosing class is loaded. ------------------------------------------------------------Question Number 3public void createTempFiles(String d) { File f = new File(d); f.mkdirs(); // more code here ... } What is the result if the createTempFiles statement below is executed on the code above on a Unix platform? if (System.getSecurityManager() == null) createTempFiles( "/tmp/myfiles/_3214" ); Choice 1 A java.lang.SecurityException is thrown. Choice 2 The file "_3214" is created in the "/tmp/myfiles" directory. Choice 3 The "myfiles" directory is created in the "/tmp" directory. Choice 4 A java.io.DirectoryNotCreatedException is thrown. Choice 5 The directory "/tmp/myfiles/_3214" is created if it doesn't already exist. ------------------------------------------------------------Question Number 4Which one of the following is NOT a valid difference between java.awt.Canvas and Panel? Choice 1 Canvas's can display images directly.

Choice 2 Panel can hold other components (including Canvas). Choice 3 You can draw bit-oriented items (lines and circles) onto a Canvas. Choice 4 Layout managers work with Panel objects. Choice 5 Panel cannot be redrawn by a call to repaint(). ------------------------------------------------------------Question Number 5The javadoc utility produces which one of the following? Choice 1 A listing of key features of all classes and methods in the source document Choice 2 An html document for each class, interface, or package Choice 3 A document for each program that outlines flow, structure, inputs, and outputs Choice 4 A listing of all classes and packages used by a program Choice 5 A list of all qualified comment tags in a source document with the source code removed ------------------------------------------------------------Question Number 6int values[] = {1,2,3,4,5,6,7,8}; for(int i=0;i< X;) System.out.println(values[i++]); Referring to the above, what value for X will print all members of array "values"? Choice 1 7 Choice 2 8 Choice 3 9 Choice 4 None, because the first value is never printed Choice 5 None, since there is a syntax error in the array declaration ------------------------------------------------------------Question Number 7What causes an IllegalMonitorStateException? Choice 1

Page 4: 43486184-Java-MCQ-s

A thread calls wait() or notify() before acquiring an object's monitor. Choice 2 Two threads call a static synchronized method at the same time. Choice 3 A thread invokes wait() on an object that is already waiting. Choice 4 A thread invokes notify() on an object that is not waiting. Choice 5 Two threads modify the same variable in the same object at the same moment. ------------------------------------------------------------Question Number 8double x=0; x= (check().equals("1")) ? getSales() : nextStore(); What datatype could be returned by method check() as shown above? Choice 1 int Choice 2 boolean Choice 3 Object Choice 4 byte Choice 5 char ------------------------------------------------------------Question Number 91: class Class1 { 2: public static void main(String args[]) { 3: int total = 0; 4: int[] i = new int[3]; 5: for(int j=1;j<= i.length; j++) 6: total += (i[j] = j); 7: System.out.println(total); 8: } 9: } What is the output of the program above? Choice 1 3 Choice 2 4

Choice 3 6 Choice 4 None. The system will throw an ArrayIndexOutOfBoundsException. Choice 5 None. The compiler will throw a syntax error on line 6. ------------------------------------------------------------Question Number 10System.getProperties().put( "java.rmi.server.codebase", "http://www.domain.com/classes/"); Which one of the following is a capability of the above code? Choice 1 Set the location of all applets in a web server Choice 2 Append CLASSPATH Choice 3 Register an rmi server on its host system Choice 4 Facilitate dynamic class loading for remote objects Choice 5 Override CLASSPATH ------------------------------------------------------------

Question Number 11char ch1,ch2; try { ch1 = (char) System.in.read(); } catch(Exception e) {} switch(ch1) { case 'a': ch2 = '1'; case 'b': ch2 = '2'; case 'c': ch2 = '3'; default: ch2 = '4'; } Referring to the above, during execution the user presses "b", what is the ending value of "ch2"? Choice 1 '1'

Page 5: 43486184-Java-MCQ-s

Choice 2 '2' Choice 3 '3' Choice 4 '4' Choice 5 null ------------------------------------------------------------Question Number 12Which java.sql class can return multiple result sets? Choice 1 Statement Choice 2 PreparedStatement Choice 3 Any class derived from Statement that implements MultiResultSet Choice 4 CallableStatement Choice 5 ResultSet with the "multiple" property set to "true" ------------------------------------------------------------Question Number 13class A { B b = new B(); C c = (C) b; } Referring to the above, when is the cast of "b" to class C allowed? Choice 1 B and C are subclasses of the same superclass. Choice 2 If B and C are superclasses of the same subclass. Choice 3 C is a final class. Choice 4 B is a subclass of C. Choice 5 B is a superclass of C. ------------------------------------------------------------Question Number 14How can you have a "try" block that invokes methods that throw two different exceptions? Choice 1

Catch one exception in a "catch" block and the other in a "finally" block. Choice 2 Setup nested "catch" blocks for each exception. Choice 3 Catch one exception in a "catch" block and the other via the return value. Choice 4 Use wait() between the calls to process all exceptions before continuing. Choice 5 Include a "catch" block for each exception. ------------------------------------------------------------Question Number 15static {System.loadLibrary("mNativeLib");}

public int myMethod(int count) {

Additional code here

} Referring to the above, if myMethod() is implemented in native code library "mNativeLib", how must its declaration be changed?Choice 1 Replace it with public System.nativeMethod("myMethod(int)");. Choice 2 Replace myMethod()'s code with System.execute("mNativeLib", myMethod(count));. Choice 3 Move it into the static code block. Choice 4 Replace it with public native int myMethod(int count);. Choice 5 Replace it with native myMethod(int count) {}. ------------------------------------------------------------Question Number 16Which one of the following is the equivalent of main() in a thread? Choice 1 start()

Page 6: 43486184-Java-MCQ-s

Choice 2 go() Choice 3 run() Choice 4 begin() Choice 5 The class constructor ------------------------------------------------------------Question Number 17What happens if a class defines a method with the same name and parameters as a method in its superclass? Choice 1 The compiler automatically renames the subclass method. Choice 2 The program runs since because overriding methods is allowed Choice 3 The program throws a DuplicateMethod exception. Choice 4 The subclass methods will be ignored. Choice 5 The compiler shows a DuplicateMethod error. ------------------------------------------------------------Question Number 18class A { static int getIt(int i) { return i; } } What is a consequence of "static" in the code above? Choice 1 getIt() returns a static int Choice 2 getIt() can only access static properties of class A Choice 3 getIt() can be overridden Choice 4 getIt() is invoked only by other static methods Choice 5 Subclasses of class A must override method getIt() ------------------------------------------------------------

Question Number 191 public static void main(String[] s) { 2 String n1, n2, n3; 3 n1 = "n1"; 4 n2 = "n2"; 5 n3 = "n3"; 6 { 7 String n4 = "inner"; 8 n2 = n1; 9 } 10 n3 = null; 11 } How many instances of the String will be eligible for garbage collection after line 10 in the above code snippet is executed? Choice 1 0 Choice 2 1 Choice 3 2 Choice 4 3 Choice 5 The code will not compile. ------------------------------------------------------------Question Number 20try { int values[] = {1,2,3,4,3,2,1}; for (int i = values.length-1; i >= 0; i++) System.out.print( values[i] + " " ); } catch (Exception e) { System.out.print("2" + " "); } finally { System.out.print("3" + " "); } What is the output of the program above? Choice 1 1 2 Choice 2 1 3 Choice 3 1 2 3 4 3 2 1 Choice 4 1 2 3

Page 7: 43486184-Java-MCQ-s

Choice 5 1 2 3 4 3 2 1 3 ------------------------------------------------------------Question Number 21native int computeAll(); Referring to the above, the keyword "native" indicates which one of the following? Choice 1 That computeAll() is undefined and must be overridden Choice 2 That computeAll() is an external method implemented in another language Choice 3 That computeAll() is defined in the superclass Choice 4 That the compiler must use file computeAll.java for platform-specific code Choice 5 That computeAll() is an operating system command ------------------------------------------------------------Question Number 22int i=0; double value = 1.2; String str = new String("1.2"); Boolean flag = true; Which is a valid use of variable "value" as shown above? Choice 1 value = str; Choice 2 if(value.equals( str )) System.out.println(str); Choice 3 if(value) i++; Choice 4 value += flag; Choice 5 value = ++i; ------------------------------------------------------------Question Number 23class A implements Cloneable { public int i, j, k; String str = ("Hello There");

public Object clone() {

try { return super.clone(); } catch (CloneNotSupportedException e) {} } }

class B extends A { public B() { i = 5; j = 3; k= -4; } } Referring to the above, what will happen when the following code is executed?

B a = new B(); B b = (B) a.clone(); Choice 1 A CloneNotSupportedException is thrown. Choice 2 Two identical class B objects are created. Choice 3 One instance of class B is created with two pointers: "a" and "b". Choice 4 Identical threads "a" and "b" are created. Choice 5 Object "a" is instantiated and "b" is created as an inner class of "B". ------------------------------------------------------------Question Number 24What class represents the U.S. Mountain time zone in date/time calculations? Choice 1 java.util.Locale Choice 2 java.util.GregorianCalendar Choice 3 java.util.Date Choice 4 java.util.Calendar Choice 5 java.util.SimpleTimeZone ------------------------------------------------------------

Page 8: 43486184-Java-MCQ-s

Question Number 25public 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; } Referring to the above, what value is returned when method func(4) is invoked? Choice 1 -2 Choice 2 -1 Choice 3 0 Choice 4 1 Choice 5 2 ------------------------------------------------------------Question Number 26short tri[][] = new short[10][]; for(int i = 0,count =0 ; i < tri.length; i++ ) { tri[i]= new short[i+1]; for(int j = 0 ; j < tri[i].length; j++ ) { tri[i][j]= (short) count++; } } At what array index does the array "tri" have the value 18 as shown above? Choice 1 tri[3][3] Choice 2 tri[4][4] Choice 3

tri[5][3] Choice 4 tri[6][2] Choice 5 tri[4][5] ------------------------------------------------------------Question Number 27Which one of the following is NOT addressed by the java.security package? Choice 1 Message digests Choice 2 Access control lists Choice 3 Cookies Choice 4 Key management Choice 5 Digital signatures ------------------------------------------------------------Question Number 28What concern is legitimate when overriding the java.lang.Object.finalize method? Choice 1 The method must be thread safe. Choice 2 The method may never execute. Choice 3 The method must handle all exceptions. Choice 4 The method must handle multiple concurrent invocations. Choice 5 The method must ensure all object references are set to null. ------------------------------------------------------------Question Number 29Which one of the following is a limitation of subclassing the Thread class? Choice 1 You must catch the ThreadDeath exception. Choice 2 You must implement the Threadable interface. Choice 3 You cannot have any static methods in the class.

Page 9: 43486184-Java-MCQ-s

Choice 4 You must declare the class final. Choice 5 You cannot subclass any other class. ------------------------------------------------------------Question Number 30char ch1=' '; int j = 0;

for(int i = 0 ; i < 5; i++) { try { ch1 = (char) System.in.read(); } catch(Exception e) {}

if (ch1 == 'a') break; else if (ch1 == 'b') continue; else if (ch1 == 'c') i--; else if (ch1 == 'd') j++;

j++; } System.out.println( j ); What is the output during execution if the user types in "bdcda" as shown above? Choice 1 2 Choice 2 3 Choice 3 4 Choice 4 5 Choice 5 6 ------------------------------------------------------------Question Number 311: import java.io.*; 2: class PrintThread extends Thread { 3: private static Object o = new Object(); 4: private static DataOutputStream out = //... set to some output file 5: private int I; 6: 7: public PrintThread(int I) { 8: this.I = I; 9: }

10: public void run() { 11: while(true) { 12: try { 13: out.writeBytes("Hello all from thread " + I +"\r\n"); 14: } catch (Exception e) {} 15: } 16: } 17: public static void main(String[] s) { 18: for (int i = 0; i < 5; i++ ) { 19: (new PrintThread(i)).start(); 20: } 21: } 22: } How could you ensure that each line of output from the above program came from an individual thread? Choice 1 Make the run method "synchronized". Choice 2 Insert the following code between line 11 and 12: try { sleep(100); } catch(Exception e) {} Choice 3 Add the "synchronized" modifier to the DataOuputStream "out" variable declaration. Choice 4 Insert the following line between line 12 and 13: synchronized(o) {

and this line between line 13 and 14 } Choice 5 Insert the following code between line 11 and 12: yield(); ------------------------------------------------------------Question Number 32Which one of the following is a reason to double-buffer animations? Choice 1 To draw each image to the screen twice to eliminate white spots Choice 2 To use a small image as wallpaper and a transparent

Page 10: 43486184-Java-MCQ-s

image as the actual frame Choice 3 To put multiple frame in the same file and uses cropImage() to select the desired frame Choice 4 To draw the next frame to an off-screen image object before displaying to eliminate flicker Choice 5 To prevent "hanging" using a MediaTracker object to ensure all frames are loaded before beginning ------------------------------------------------------------Question Number 33String s1 = new String("AbraCadabra"); String s2 = new String(" willow woo");

String s3; s3=s1.substring(1,5) + s2.toUpperCase().trim().substring(1,5); Referring to the above, what is in s3 after execution? Choice 1 braCaWILLO Choice 2 braCILLO Choice 3 braCWILL Choice 4 braCaILLOW Choice 5 AbraC WILL ------------------------------------------------------------Question Number 34class Class1 { static int i=0; public static void main(String args[]) { for(int j=1;j<args.length;j+=2) { i += Integer.parseInt(args[j]); } System.out.println(i); } } What parameters could be passed on the command-line so that the output of the program above is "6"? Choice 1

1 2 3 4 Choice 2 6 5 1 Choice 3 6 Choice 4 None. The system will throw an ArrayIndexOutOfBounds Exception. Choice 5 None. The compiler will issue an error message because an exception must be caught when invoking parseInt(). ------------------------------------------------------------Question Number 35What is the purpose of the java.text package? Choice 1 To perform font management between different platforms Choice 2 To provide classes for manipulating Strings Choice 3 To allow formatting of text data for specific geographic locations Choice 4 To facilitate spelling and grammar checks Choice 5 To render text strings on java.awt.Container objects ------------------------------------------------------------Question Number 36

Which class formats the exact time for a web page used by people in India? Choice 1 java.util.GregorianCalendar Choice 2 java.util.Time Choice 3 java.text.TimeFormat Choice 4 java.util.Date Choice 5 java.text.SimpleDateFormat ------------------------------------------------------------Question Number 37Compared to connection-oriented sockets, which statement about connectionless sockets is true?

Page 11: 43486184-Java-MCQ-s

Choice 1 They support only character streams. Choice 2 They do not support two-way communication. Choice 3 They do not guarantee delivery or order of receipt. Choice 4 They can transmit to multiple receivers at the same time. Choice 5 They are less efficient and slower. ------------------------------------------------------------Question Number 38class MyButton extends Button { private int pressCount=0; private static Panel panel;

public MyButton(String txt) { super( txt ); if (panel != null) panel=new Panel(); } protected void finalize() throws Throwable { panel.add( this ); System.out.println("GoodBye!"); } } What is WRONG with the code above? Choice 1 Super class Button doesn't have a public constructor which takes a String as a parameter. Choice 2 The finalize method must be declared public. Choice 3 Accessing a static method inside the constructor call. Choice 4 The paint() method is not overridden. Choice 5 class MyButton cannot ever get garbage collected correctly. ------------------------------------------------------------Question Number 39_______________| Choice A \/ |The widget shown above is similar to which

standard java.awt class? Choice 1 Menu Choice 2 PullMenu Choice 3 List Choice 4 Choice Choice 5 Select ------------------------------------------------------------Question Number 40What class is subclassed to package several locale-specific versions of a set of greetings used by an application? Choice 1 java.text.RuleBasedCollator Choice 2 java.text.CollationKey Choice 3 java.util.ResourceBundle Choice 4 java.util.TimeZone Choice 5 java.util.Locale

Question Number 1import java.lang.reflect.Field; MyClass myClass = new MyClass(); try { Class cl=Class.forName("MyClass"); Field res=cl.getDeclaredField("count"); res.set(myClass,"5"); } catch(Exception e) {} What is accomplished by the above code? Choice 1 The first 5 member variables of myClass are copied to "res". Choice 2 The value of myClass.count is set to 5. Choice 3 Object "res" is created with its "count" member set to 5.

Page 12: 43486184-Java-MCQ-s

Choice 4 5 copies of the myClass object are created. Choice 5 The number of MyClass fields described in "cl" is set to 5. ---------------------------------------------------------------------Question Number 2XXX = new Integer("155").toString(); What datatype or class is XXX in the above code segment? Choice 1 byte Choice 2 char[] Choice 3 StringBuffer Choice 4 String Choice 5 long ---------------------------------------------------------------------Question Number 3What class can access file attributes, create new files and create directories? Choice 1 java.io.FileSystem Choice 2 java.io.RandomAccessFile Choice 3 java.util.Writer Choice 4 System or Runtime Choice 5 java.io.File ---------------------------------------------------------------------Question Number 4class A { int i, j, k; public A(int ii) { i = ii; } public A() { k = 1; } } Referring to the above, what code instantiates an object of class A?

Choice 1 new A(this); Choice 2 A a = new A(3); Choice 3 A(3) a; Choice 4 A a = new A(4,8); Choice 5 A a = new A(3.3); ---------------------------------------------------------------------Question Number 5void printOut( int I ) { if (I==0) return; for(int i=I;i>0;i--) { System.out.println("Line " + i); } printOut(I-1); } What value should be passed to the method printOut, shown above, so that ten lines will be printed? Choice 1 2 Choice 2 3 Choice 3 4 Choice 4 5 Choice 5 6 ---------------------------------------------------------------------Question Number 6class A { public static void main(String args[]) { char initial = "c"; switch (initial) { case "j": System.out.print("John "); break; case "c": System.out.print("Chuck "); case "t": System.out.print("Ty ");

Page 13: 43486184-Java-MCQ-s

break; case "s": System.out.print("Scott "); default: System.out.print("All"); } } } What is the output from the code above? Choice 1 John Chuck Ty Scott All Choice 2 A compilation error will occur. Choice 3 Chuck Ty Choice 4 Ty Choice 5 Chuck ---------------------------------------------------------------------Question Number 7How can you insure compatibility of persistent object formats between different versions of Java? Choice 1 Override the default ObjectInputStream and ObjectOutputStream. Choice 2 Implement your own writeObject() and readObject() methods. Choice 3 Add "transient" variables. Choice 4 Implement java.io.Serializable. Choice 5 Make the whole class transient ---------------------------------------------------------------------Question Number 8What does it mean if a method is final synchronized? Choice 1 Methods which are synchronized cannot be final. Choice 2 This is the same as declaring the method private. Choice 3 Only one synchronized method can be invoked at a

time for the entire class. Choice 4 The method cannot be overridden and is always threadsafe. Choice 5 All final variables referenced in the method can be modified by only one thread at a time. ---------------------------------------------------------------------Question Number 9class HelloWorld extends java.awt.Canvas { String str = "Hello World";

public void paint(java.awt.Graphics g) { java.awt.FontMetrics fm = g.getFontMetrics(); g.setColor(java.awt.Color.black); java.awt.Dimension d = getSize(); __?__ } } Which one of the following code segments can be inserted into the method above to paint "Hello World" centered within the canvas? Choice 1 g.drawText( str, 0, 0); Choice 2 g.drawString( str, d.width/2, d.height/2 ); Choice 3 g.drawString( str, d.width/2 - fm.stringWidth(str)/2, d.height/2 - fm.getHeight()/2); Choice 4 g.translate( d.width/2 - fm.stringWidth(str), d.height/2 - fm.getHeight()); g.drawString( str, 0, 0); Choice 5 g.drawText( str, d.width, d.height, Font.CENTERED ); ---------------------------------------------------------------------Question Number 10String url=new String("http://www.tek.com"); How can you retrieve the content of the above URL? Choice 1 Socket content = new Socket(new URL(url)).collect();

Page 14: 43486184-Java-MCQ-s

Choice 2 String content = new URLConnection(url).collect(); Choice 3 Object content = new URL(url).getContent(); Choice 4 Object content = new URLConnection(url).getContent(); Choice 5 String content = new URLHttp(url).getString(); ---------------------------------------------------------------------Question Number 11What is NOT a typical feature of visual JavaBeans? Choice 1 Persistence, so a bean can be customized in an application builder, saved, and reloaded later. Choice 2 Properties, both for customization and for programmatic use. Choice 3 Customization, so that when using an application builder a developer can customize the appearance and behavior of a bean. Choice 4 Distributed framework, so the visual component resides on the client, while the logic resides on the server. Choice 5 Events, so that a simple communication metaphor can be used to connect beans. ---------------------------------------------------------------------Question Number 12Which one of the following describes the difference between StringBuffer and String? Choice 1 StringBuffer is used only to buffer data from an input or output stream. Choice 2 StringBuffer allows text to be changed after instantiation. Choice 3 StringBuffer holds zero length Strings. Choice 4 StringBuffer supports Unicode. Choice 5 StringBuffer is an array of Strings.

---------------------------------------------------------------------Question Number 13public 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; y *= -9.0; try { y = SquareRoot( y ); } catch(ArithmeticException e) { y /= 3; } finally { y += 10; } return y; } Referring to the above, what value is returned when method func(9) is invoked? Choice 1 -37 Choice 2 -27 Choice 3 -17 Choice 4 9 Choice 5 NaN ---------------------------------------------------------------------Question Number 141: Date myDate = new Date(); 2: DateFormat dateFormat = DateFormat.getDateInstance(); 3: String myString = dateFormat.format(myDate); 4: System.out.println( "Today is " + myString ); How can you change line 2 above so that the date is displayed in the same format used in China? Choice 1 java.util.Local locale = java.util.Locale.getLocale( java.util.Locale.CHINA ); DateFormat dateFormat = DateFormat.getDateInstance( locale );

Page 15: 43486184-Java-MCQ-s

Choice 2 java.util.Local locale = java.util.Locale.getLocale("China"); DateFormat dateFormat = DateFormat.getDateInstance( locale ); Choice 3 DateFormat dateFormat = DateFormat.getDateInstance(); dateFormat.setLocale( java.util.Locale.CHINA ); Choice 4 DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.SHORT, java.util.Locale.CHINA); Choice 5 DateFormat.setLocale( java.util.Locale.CHINA ); DateFormat dateFormat = DateFormat.getDateInstance(); ---------------------------------------------------------------------Question Number 15Which one of the following operators has a higher precedence than the modulus operator, % ? Choice 1 - Choice 2 * Choice 3 + Choice 4 / Choice 5 . (dot) ---------------------------------------------------------------------Question Number 16double dd; java.util.Random r = new Random(33); dd = r.nextGaussian(); Referring to the above, after execution, double dd contains a value that is distributed approximately ________ with a standard deviation of ________ and mean of ________. Choice 1 uniformly, 0, 33 Choice 2 normally, 1, 0 Choice 3

uniformly, 1, 33 Choice 4 normally, 1, 33 Choice 5 normally, 3, 3 ---------------------------------------------------------------------Question Number 17How can you give other classes direct access to constant class attributes but avoid thread-unsafe situations? Choice 1 Declare the attributes as public static final. Choice 2 Implement the "java.lang.SingleThreaded" interface. Choice 3 Declare the attributes to be synchronized. Choice 4 This is not possible. Choice 5 Declare the attributes as protected. ---------------------------------------------------------------------Question Number 18import java.io.*; import java.net.*; public class NetClient { public static void main(String args[]) { try { Socket skt = new Socket("host",88); In the above code, what type of connection is Socket object "skt"? Choice 1 UDP Choice 2 Connectionless Choice 3 FTP Choice 4 HTTP Choice 5 Connection-oriented ---------------------------------------------------------------------Question Number 19float ff; int gg = 99;

Page 16: 43486184-Java-MCQ-s

Referring to the above, what is the correct way to cast an integer to a float? Choice 1 ff = (float) gg Choice 2 ff (float) = gg Choice 3 ff = (float: gg Choice 4 ff = (float) %% gg Choice 5 You cannot cast an integer to a float ---------------------------------------------------------------------Question Number 20Which one of the following is a reason to double-buffer animations? Choice 1 To draw each image to the screen twice to eliminate white spots Choice 2 To prevent "hanging" using a MediaTracker object to ensure all frames are loaded before beginning Choice 3 To draw the next frame to an off-screen image object before displaying to eliminate flicker Choice 4 To put multiple frame in the same file and uses cropImage() to select the desired frame Choice 5 To use a small image as wallpaper and a transparent image as the actual frame ---------------------------------------------------------------------Question Number 21Which one of the following is NOT a valid java.lang.String declaration? Choice 1 String myString = new String("Hello"); Choice 2 char data[] = {'a','b','c'}; String str = new String(data); Choice 3 String myString = new String(5); Choice 4 String cde = "cde"; Choice 5

String myString = new String(); ---------------------------------------------------------------------Question Number 22int count = 0; while(count++ < X ) { System.out.println("Line " + count); } What value for X above will print EXACTLY 10 lines to standard output? Choice 1 0 Choice 2 5 Choice 3 9 Choice 4 10 Choice 5 11 ---------------------------------------------------------------------Question Number 23package mypackage.compute.financial; Referring to the above, where must Class files belonging to the package be stored? Choice 1 In any classpath directory Choice 2 In directory mypackage under the current working directory Choice 3 In mypackage/compute/financial under any directory in the classpath Choice 4 In mypackage/compute/classpath under any directory Choice 5 In any directory defined in the path of the java interpreter ---------------------------------------------------------------------Question Number 24A monitor called "m" has two threads waiting with the same priority. One of the threads is "thread3". How can you inform "thread3" so that it alone moves from the Waiting state to the Ready state? Choice 1

Page 17: 43486184-Java-MCQ-s

thread3.notify(); Choice 2 m.notify(thread3); Choice 3 thread3.start(); Choice 4 notify(thread3); Choice 5 thread3.run() ---------------------------------------------------------------------Question Number 25if(check4Biz(storeNum) < 10) {} Referring to the above, what datatype could be returned by method check4Biz()? Choice 1 char[] Choice 2 Boolean Choice 3 int Choice 4 String Choice 5 java.util.Bitset ---------------------------------------------------------------------Question Number 26Which one of the following is a limitation of subclassing the Thread class? Choice 1 You must implement the Threadable interface. Choice 2 You cannot have any static methods in the class. Choice 3 You must declare the class final. Choice 4 You must catch the ThreadDeath exception. Choice 5 You cannot subclass any other class. ---------------------------------------------------------------------Question Number 27String os = System.getProperty("os.name"); When the above code is executed in an untrusted applet, which code segment will the JVM execute internally? Choice 1

throw new java.lang.SecurityException(); Choice 2 System.checkStackTrace(); Choice 3 return SecurityManager.getProperty("os.name"); Choice 4 SecurityManager().getAccess("Property", "os.name"); Choice 5 System.getSecurityManager().checkPropertyAccess("o s.name"); ---------------------------------------------------------------------Question Number 28public void createTempFiles(String d) { File f = new File(d); f.mkdirs(); // more code here ... } What is the result if the createTempFiles statement below is executed on the code above on a Unix platform? if (System.getSecurityManager() == null) createTempFiles( "/tmp/myfiles/_3214" ); Choice 1 The file "_3214" is created in the "/tmp/myfiles" directory. Choice 2 A java.lang.SecurityException is thrown. Choice 3 The "myfiles" directory is created in the "/tmp" directory. Choice 4 A java.io.DirectoryNotCreatedException is thrown. Choice 5 The directory "/tmp/myfiles/_3214" is created if it doesn't already exist. ---------------------------------------------------------------------Question Number 29static void printIt( int count ) { if ((count % 2) == 0) System.err.println("StdErr: Line " + count + "\n"); else { System.out.println("StdOut: Line " + count + "\n"); } if (count == 0) return;

Page 18: 43486184-Java-MCQ-s

else printIt(count-1); }

public static void main(String [] args) { printIt( X ); } What value for X above will print EXACTLY ten lines to standard output, in the fewest number of recursive calls? Choice 1 5 Choice 2 9 Choice 3 10 Choice 4 19 Choice 5 20 ---------------------------------------------------------------------Question Number 30for(int i=0;i<5;i= X ) { System.out.println("Line " + i); i++; } Referring to the above, what value for X will cause a never-ending loop? Choice 1 A compiler error occurs Choice 2 4 Choice 3 5 Choice 4 6 Choice 5 10 ---------------------------------------------------------------------Question Number 31System.err represents an instance of what class? Choice 1 java.lang.System Choice 2 java.io.PrintWriter Choice 3

java.io.OutputStreamWriter Choice 4 java.io.PrintStream Choice 5 java.io.BufferedOutputStream ---------------------------------------------------------------------Question Number 32<import java.io.*;

Additional code here

FileInputStream f = new FileInputStream("store");ObjectInputStream in = new ObjectInputStream(f);Object obj = in.readObject(); Referring to the above, what additional code will produce the type of object represented by "obj"? Choice 1 Classloader.getInstance(obj); Choice 2 obj.getClass().getName(); Choice 3 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; Choice 4 obj.toString(); Choice 5 new Class.getName(obj); ---------------------------------------------------------------------Question Number 33What code declares a two dimensional array of integers called "intArray"? Choice 1 int intArray[] = {int intArray[]}; Choice 2 int intArray[][]; Choice 3 two dimensional arrays are not allowed in java Choice 4 int intArray{int intArray[]}; Choice 5 int **intArray;

Page 19: 43486184-Java-MCQ-s

---------------------------------------------------------------------Question Number 34class PrimeThread extends Thread { long minPrime; long result;

PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime // . . . } } Referring to the above, which code segment could create and start PrimeThread? Choice 1 Thread p = new Thread(new PrimeThread(143)); p.run(); Choice 2 PrimeThread p = new PrimeThread(); p.run(); Choice 3 PrimeThread(143).run(); Choice 4 Runnable r = new Runnable( PrimeThread(143) ); r.start(); Choice 5 (new PrimeThread(143)).start(); ---------------------------------------------------------------------Question Number 35class MyCanvas extends java.awt.Canvas { int count = 0; public MyCanvas() {} public void paint(Graphics g) { super.paint(g); } public int paint(Graphics g) { super.paint(g); return ++count; } } Referring to the above, what is WRONG with class MyCanvas? Choice 1

All methods must declare return datatypes. Choice 2 There are multiple methods named paint(). Choice 3 A method cannot have the same name as its class. Choice 4 Overloaded methods cannot have the same input types with a different return type. Choice 5 java.awt.Canvas is an interface, so it must be implemented, not extended. ------------------------------------------------------------------Question Number 36Objects can be cast to another class when which one of the following is the case? Choice 1 Both classes are direct subclasses of the same superclass. Choice 2 The source class is not abstract or static. Choice 3 The target class is a subclass of the source class. Choice 4 Both classes are subclasses of the same abstract superclass. Choice 5 The target class is a final class. ---------------------------------------------------------------------Question Number 37What happens if you load a JDBC driver that is NOT fully compliant with JDBC? Choice 1 The driver will fail bytecode verification. Choice 2 The driver would function for applications, but not applets. Choice 3 The driver may work for some actions and not for others. Choice 4 The SecurityManager will throw a SecurityException when a connection is attempted. Choice 5 The DriverManager object will refuse to register it. ---------------------------------------------------------------------

Page 20: 43486184-Java-MCQ-s

Question Number 38To sign a .class file, the javakey tool does which one of the following? Choice 1 Embeds a signature flag in the class file attributes Choice 2 Places a signature byte[] array at the bottom of the class file Choice 3 Creates an inner class containing the signature data Choice 4 Places a signature byte[] array at the top of the class file Choice 5 Places special signature files in a JAR bundle ------------------------------------------------------------------Question Number 39float f = 5.0f; float g = 2.0f; double h;

h = 3+f%g+2; Referring to the above, what is the expected value for h after execution? Choice 1 5.2 Choice 2 6 Choice 3 7 Choice 4 7.5 Choice 5 9 ------------------------------------------------------------------Question Number 40Connection con = DriverManager.getConnection ( "jdbc:odbc:wombat", "login", "password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { Integer x = rs.getInt("c"); String s = rs.getString("a"); Float f = rs.getFloat("b"); } What is WRONG with the code above? Choice 1 Retrieval of the fields is in the wrong order. Choice 2 The password must be encrypted before

being sent to the DriverManager. Choice 3 The Driver's URL is in the wrong format. Choice 4 The ResultSet class returns primitive types for integers and floats. Choice 5 The SQL statement is invalid.

Question 1.Read this piece of code carefully

if("String".toString() == "String")System.out.println("Equal");

elseSystem.out.println("Not Equal");

Answers1. the code will compile an print “Equal”.2. the code will compile an print “Not Equal”.3. the code will cause a compiler error.

Question 2.Read this piece of code carefully

if("String".trim() == "String")System.out.println("Equal");

elseSystem.out.println("Not Equal");

Answers1. the code will compile an print “Equal”.2. the code will compile an print “Not Equal”.3. the code will cause a compiler error

Question 3.Read the code below. Will be the result of attempting to compile and run the code below.

public class AQuestion {public void method(Object o){

System.out.println("Object Verion");

}public void method(String s){

System.out.println("String Version");

}public static void main(String args[]){

AQuestion question = new AQuestion();

question.method(null);}

}

Answers1. The code does not compile.2. The code compiles cleanly and shows “Object

Page 21: 43486184-Java-MCQ-s

Version”.3. The code compiles cleanly and shows “String Version”4. The code throws an Exception at Runtime.

Question 4.Read the code below. Will be the result of attempting to compile and run the code below.

public class AQuestion{public void method(StringBuffer sb){

System.out.println("StringBuffer Verion");

}public void method(String s){

System.out.println("String Version");

}public static void main(String args[]){

AQuestion question = new AQuestion();

question.method(null);}

}

Answers1. The code does not compile.2. The code compiles cleanly and shows “StringBuffer Version”.3. The code compiles cleanly and shows “String Version”4. The code throws an Exception at Runtime.

Question 5.Read the following code below.

public interface AQuestion{public abstract void someMethod() throws

Exception;}

A Class implementing this interface should1. Necessarily be an abstract class.2. Should have the method public abstract void someMethod();3. Should have the method public void someMethod() which has to throw an exception which is a subclass of java.lang.Exception.4. Should have the method public void someMethod() which need not throw an Exception.

Question 6.An Interface can never be private or protected.

AnswersTrueFalse

Question 7.A Vector class in jdk 1.2

1. is public2. is final3. implements java.util.List4. is serializable5. has only One constructor

Question 8.A String Class

1. is final2. is public3. is serializable4. has a constructor which takes a StingBuffer Object as an Argument

Question 9.

public interface AQuestion{void someMethod();

}

The class which implements AQuestion1. Should have someMethod which must necessarily be public.2. Should have someMethod which could be “friendly” or public3. Should have someMethod which should not throw any checked exceptions.4. Should have someMethod which cannot be sychronized as sychronized is not in the signature of the interface defination

Question 10.

public class AQuestion{private int i = j;private int j = 10;public static void main(String args[]){

System.out.println((new AQuestion()).i);

}}

Answers

1. Compiler error complaining about access restriction of private variables of AQuestion.

Page 22: 43486184-Java-MCQ-s

2. Compiler error complaining about forward referencing.

3. No error - The output is 0;

4. No error - The output is 10;

Q: What is the difference between declaring a variable and defining a

variable?

A: In declaration we just mention the type of the variable and it’s name. We do not

initialize it. But defining means declaration + initialization.

e.g String s; is just a declaration while String s = new String (“abcd”); Or String s =

“abcd”; are both definitions. 

 Q: What is the default value of an object reference declared as an instance

variable?

A: null unless we define it explicitly. 

 Q: Can a top level class be private or protected?

A: No. A top level class can not be private or protected. It can have either “public” or

no modifier. If it does not have a modifier it is supposed to have a default access.If a

top level class is declared as private the compiler will complain that the “modifier

private is not allowed here”. This means that a top level class can not be private.

Same is the case with protected. 

 Q: What type of parameter passing does Java support?

A: In Java the arguments are always passed by value . 

 Q: Primitive data types are passed by reference or pass by value?

A: Primitive data types are passed by value. 

 Q: Objects are passed by value or by reference?

A: Java only supports pass by value. With objects, the object reference itself is passed

by value and so both the original reference and parameter copy both refer to the

same object . 

 Q: What is serialization?

A: Serialization is a mechanism by which you can save the state of an object by

converting it to a byte stream.