Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   105 Multiple Choice Questions in Java (http://www.go4expert.com/articles/105-multiple-choice-questions-java-t8/)

shabbir 20Jul2004 07:20

105 Multiple Choice Questions in Java
 
1. How 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.



2. Which 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.



3.
Code:

public 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?
Code:

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.



4. Which 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().



5. The 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



6.
Code:

int 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



7. What causes an IllegalMonitorStateException?
Choice 1
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.



8.
Code:

double 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



9.
Code:

class Class1 {
        public static void main(String args[]) {
                int total = 0;
                int[] i = new int[3];
                for(int j=1;j<= i.length; j++)
                        total += (i[j] = j);
                System.out.println(total);
        }
}

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.



10.
Code:

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



11.
Code:

char 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'
Choice 2
'2'
Choice 3
'3'
Choice 4
'4'
Choice 5
null



12. Which 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"



13.
Code:

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



14. How 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.



15.
Code:

static {
        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) {}.



16. Which one of the following is the equivalent of main() in a thread?
Choice 1
start()
Choice 2
go()
Choice 3
run()
Choice 4
begin()
Choice 5
The class constructor



17. What 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.



18.
Code:

class 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()



19.
Code:

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



20.
Code:

try {
        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
Choice 5
1 2 3 4 3 2 1 3



21. native 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



22.
Code:

int 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;



23.
Code:

class 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?
Code:

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



24.
What 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



25.
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;
}

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



26.
Code:

short 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]



27. Which 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



28. What 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.



29. What limitation subclassing the Thread class have?
Choice 1
Must catch the FatalThread exception.
Choice 2
Implement the Threadable interface.
Choice 3
Cannot include static methods in the class.
Choice 4
Class must be final class.
Choice 5
Cannot subclass any other class.



30.
Code:

char 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



31.
Code:

1: 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();



32. Which 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 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



33.
Code:

String 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



34.
Code:

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



35. What 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



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



37. Compared to connection-oriented sockets, which statement about connectionless sockets is true?
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.



38.
Code:

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



39. What 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



40. 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("countRecs()");
spstmt.executeQuery();
Choice 4
PrepareStatement pstmt = connection.prepareStatement("countRecs()");
pstmt.execute();
Choice 5
Statement stmt = connection.createStatement();
stmt.executeStoredProcedure("countRecs()");



41.
Code:

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



42.
Code:

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.



43. 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 {



44.
Code:

public 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?
Choice 1
1
Choice 2
2
Choice 3
3
Choice 4
4
Choice 5
The system will exit



45. Which 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.



46. Which 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;



47.
Code:

import 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.
Choice 4
5 copies of the myClass object are created.
Choice 5
The number of MyClass fields described in "cl" is set to 5.



48.
Code:

XXX = 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



49. What 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



50.
Code:

class 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);



51.
Code:

void 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



52.
Code:

class 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 ");
                        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



53. How 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



54. What 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.



55.
Code:

class 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 );



56.
Code:

String 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();
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();



57. What 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.



58. Which 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.



59.
Code:

1: 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 );
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();



60. Which one of the following operators has a higher precedence than the modulus operator, % ?
Choice 1
-
Choice 2
*
Choice 3
+
Choice 4
/
Choice 5
. (dot)



61.
Code:

double 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



62. How 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.



63.
Code:

import 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



64.
Code:

float ff;
int gg = 99;

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



65. Which 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();



66
Code:

int 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



67.
Code:

package 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



68. A 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
thread3.notify();
Choice 2
m.notify(thread3);
Choice 3
thread3.start();
Choice 4
notify(thread3);
Choice 5
thread3.run()



69. What is the limitation of class derived from the Thread class?
Choice 1
Must implement Threadable interface.
Choice 2
Cannot have static methods in the class.
Choice 3
Class must be declared as final.
Choice 4
Must Catch an exception.
Choice 5
Cannot be a subclass of any other class.



70
Code:

String 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");



71.
Code:

static 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; 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



72.
Code:

for (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



73. System.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



74.
Code:

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



75. What 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;



76.
Code:

class 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();



77.
Code:

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



78. Objects 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.



79. What 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.



80. To 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



81
Code:

float 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



82.
Code:

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



83. How can a MediaTracker object inform multiple threads that file downloads are complete?
Choice 1
Invoke notifyAll()
Choice 2
Invoke ThreadGroup.notify() on the parent ThreadGroup.
Choice 3
Invoke notify()
Choice 4
Create a MediaLoaded Event
Choice 5
The MediaTracker should call destroy()



84
Code:

public class MailChecker extends Thread {
        static Mailbox myMail;
        public MailChecker() {
                start();
        }
        public void run() {
                while( true ) {
                        if (myMail.newMsg) {
                                System.out.println(myMail.msg);
                                myMail.newMsg = false;
                        }
                        try {
                                sleep(50);
                        }
                        catch(InterruptedException e ) {
                        }
                }
        }
}
class Mailbox {
        public Boolean newMsg;
        public String msg;
}

What problem would cause the above code to execute INCORRECTLY?
Choice 1
Sleeping only 50 milliseconds will use too much CPU cycles.
Choice 2
Access to myMail is not thread safe.
Choice 3
There could be data corruption with the myMail attribute.
Choice 4
Class Mailbox doesn't encapsulate its data with accessors.
Choice 5
Modifying the myMail static instance will cause an exception.



85.
Code:

double x = 0, y = 5.4324;
try {
        System.out.println( (y/x) );
}
catch (Exception e) {
        System.out.println("Exception");
}
catch (Throwable t) {
        System.out.println("Error");
}

What is the output of the above code?
Choice 1
-1
Choice 2
0
Choice 3
Error
Choice 4
Infinity
Choice 5
Exception



86. How do you get a reference to the clipboard?
Choice 1
java.awt.datatransfer.Clipboard.getDesktopClipboar d()
Choice 2
new java.awt.datatransfer.Clipboard()
Choice 3
Java 1.1.x can't get access to the clipboard.
Choice 4
java.awt.Toolkit.getDefaultToolkit().getSystemClip board()
Choice 5
System.lang.ClipBoard



87. When do you set a thread as a daemon?
Choice 1
To access to the System and Runtime objects directly
Choice 2
When the thread will execute native methods.
Choice 3
For a utility thread that will stop running when the application has completed
Choice 4
To make the thread available to any other object created in the java virtual machine
Choice 5
To set the thread's priority as low as possible.



88. To access runtime type information for a class, array, or primitive datatype, you can use which one of the following classes?
Choice 1
Runtime
Choice 2
System
Choice 3
ClassLoader
Choice 4
Object
Choice 5
Class



89
Code:

java.util.Hashtable ht = new java.util.Hashtable();
java.util.Vector v = new java.util.Vector();
for (int i = 0; i < 10; i++) {
        v.addElement( new Integer( i ) );
        ht.put( new Integer( i ), v );
}

Which code segment will print the keys and elements of the Hashtable above?
Choice 1
Enumeration e = ht.keys();
for(int i=0; i < ht.size(); i++) {
Object o = e.nextElement();
System.out.print(o + " = " + ht.get(o) );
}
Choice 2
for(Enumeration e=ht.elements(); e.hasMoreElements();) {
Integer i = (Integer) e.nextElement();
System.out.print(i.toString() + " = " + ht.get(i) );
}
Choice 3
for(Enumeration e=v.elements(); e.hasMoreElements();)
Integer i = (Integer) e.nextElement();
System.out.print(i.toString() + " = " + v.get(i.intValue()) );
}
Choice 4
for(int i=0; i < ht.size(); i++)
System.out.print(ht.elementAt(i,0) + " = " + ht.elementAt(i,1) );
Choice 5
int j=0;
while(j < ht.size()) {
int i = (int) ht.elementAt(j);
System.out.print(i + " = " + ht.get(i));
j++;
}



90.
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);

Referring to the above, which command executes procedure proc(), which includes two INSERT SQL statements and one OUT parameter?
Choice 1
ResultSet = cs.runQuery()
Choice 2
cs.execute()
Choice 3
cs.executeQuery()
Choice 4
cs.prepareCall().execute()
Choice 5
con.getConnection(cs)



91.
Code:

public int increment() {
        counter++;
        out.write(counter);
        catch(Exception e) {
        }
        return counter;
}

Referring to the above, what is missing from method increment()?
Choice 1
A "finally" code block must follow the catch block.
Choice 2
"counter" must be declared inside increment()
Choice 3
There is no "try" block enclosing the code before the "catch" block.
Choice 4
This method should be synchronized.
Choice 5
An explicit "catch" block catching a java.io.IOException is required.



92.
Code:

int shifter(int[] array, int arrayLength) {
        synchronized (array) {
                for (int i=1;i<arrayLength;i++) {
                        array[i-1] = array[i];
                }
        }
}

Referring to the above, what is the purpose of the "synchronized (array)" code block?
Choice 1
It forces the thread to obtain the monitor for "array" before continuing.
Choice 2
It ensures that any threads created in the code block begin execution in the "array" object.
Choice 3
It is the same as declaring shifter() as synchronized.
Choice 4
It sets all methods of the object to synchronized while the code block executes.
Choice 5
It forces the virtual machine to treat "array" as a static object.



93.
Code:

package B;
public class A {
        int getSquare(int i) {
                return i*i;
        }
}

Referring to the above, what classes can access method getSquare() in class A?
Choice 1
Class A.
Choice 2
Class A and classes in package B only.
Choice 3
Class A, all subclasses of A, and classes in package B only.
Choice 4
Class A and its subclasses only.
Choice 5
Class A, all subclasses of A, classes in package B, and all classes in sub-packages of B.



94.
Code:

public void printIt(String txt) {
        java.util.StringTokenizer st = new java.util.StringTokenizer(txt);
        while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
        }
}

Referring to the above, what is the result when the following statement is invoked? printIt(" Hello\n World\t!" );
Choice 1
The following is outputted:
Hello
World
!
Choice 2
The following is outputted:
HelloWorld!
Choice 3
java.util.NoSuchElementException is thrown.
Choice 4
The following is outputted:
Hello

World
!
Choice 5
The following is outputted:
Hello

World!



95.
Code:

class A {
        private int x=0;
        public synchronized void update() {
                x++;
        }
        public class B {
                public synchronized void update() {
                        x++;
                }
        }
}

Referring to the above, what happens if the following code is executed?
Code:

A a = new A();
A.B b = a.new B();
b.update();

Choice 1
There is a compiler error
Choice 2
"b" acquires both the monitors of "a" and "b" and increment "x"
Choice 3
"a" acquires its own monitor and update "x"
Choice 4
"b" acquires its own monitor and then increment "x"
Choice 5
"b" acquires the monitor of "a" and increment "x"



96. Which code segment listens for a socket connection?
Choice 1
(new MulticastSocket(8080)).joinGroup();
Choice 2
Socket socket = new Socket();
Choice 3
Socket socket = HttpURLConnection.open(8080);
Choice 4
Socket socket = (new ServerSocket(8080)).accept();
Choice 5
Socket socket = SocketImpl.listen(8080);



97.
Code:

import java.awt.*;
class A extends Frame implements ActionListener, WindowListener {
        public A() {
                Button button1 = new Button("Click Me");
                button.addActionListener(this);
                add(button1);
                show();
        }
        public actionPerformed(ActionEvent e) {
        }
        void b1() {
                return;
        }
}

Referring to the above, what statement is added to actionPerformed() so that b1() is invoked for a click on button1?
Choice 1
b1();
Choice 2
if(e.getActionCommand().equals("button1")) b1();
Choice 3
if(e.target == button1) b1();
Choice 4
if(e.getSource().equals(button1)) b1();
Choice 5
if(e.type == ButtonAction) b1();



98.
Code:

String s = "Chase the ball.";
StringBuffer sb = new StringBuffer(s);

Which code segment below produces a string equal to "Chase kicked the ball." using s and sb as shown above?
Choice 1
sb.delete(6,15);
sb.append("kicked the ball.");
s = sb.toString();
Choice 2
sb.insert(6,"kicked ");
s = sb.toString();
Choice 3
sb.substring(0,6);
sb.append("kicked the ball.");
s = sb.toString();
Choice 4
sb.append(8,"kicked ");
s = sb.toString();
Choice 5
sb.append(6,"kicked ");
s = sb.toString();



99. Which code segment loads and plays a sound in an applet?
Choice 1
getAppletContext().getAudioClip( new URL( getDocumentBase().toString() +
"/jaws.wav" ) ).start();
Choice 2
Play( getDocumentBase(),"jaws.wav" );
Choice 3
getAudioClip( new URL( getDocumentBase().toString() + "/jaws.wav" ) ).play();
Choice 4
getAppletContext().playAudio( new URL( getDocumentBase().toString() + "/jaws.wav" ) );
Choice 5
Play( getDocumentBase().toString() + "/jaws.wav" );



100.
Code:

int shifter(int[] array, int arrayLength) {
        for (int i=1;i<arrayLength;i++) {
                array[i-1] = array[i];
        }
}

Referring to the above, how do you prevent other threads from changing data in "array" while method shifter() is executing?
Choice 1
Declare shifter as synchronized
Choice 2
Add "synchronized" to the "array[i-1] = array[i];" statement
Choice 3
Declare "array" as static
Choice 4
Enclose all code in all classes changing "array" in a synchronized (array) code block
Choice 5
Call wait() before executing the for-loop



101. Which socket class can send packets unreliably?
Choice 1
java.net.DatagramSocket()
Choice 2
java.net.URL()
Choice 3
java.net.URLConnection()
Choice 4
java.net.Socket()
Choice 5
java.net.UDPSocket()



102.
Code:

if(check4Biz(str).equals("Y") || count == 2) {}
Referring to the above, what datatype is returned by method check4Biz()?
Choice 1
String
Choice 2
byte
Choice 3
Boolean
Choice 4
char
Choice 5
int



103.
Code:

int count=0, i=0;
do {
        count *= i;
        i++;
        if(count == 1) continue;
        count++;
}
while(i<3);

Referring to the above, what is the value of "count" after execution?
Choice 1
0
Choice 2
3
Choice 3
4
Choice 4
6
Choice 5
10



104. Which one of the following is true of a java.text.Collator object's "strength"?
Choice 1
It sets the java.util.Locale used for string comparisons.
Choice 2
It sets whether CollationKey or String objects are compared.
Choice 3
It indicates if string comparisons use ASCII or Unicode.
Choice 4
It determines the degree of comparison used to rank strings.
Choice 5
It is a multiplier for difference values between strings.



105.
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 ");
}

What is the output from the program above?
Choice 1
A B C A B C A B C
Choice 2
A A A B C A A A B C A A A B C
Choice 3
A A B C B B
Choice 4
A A B B C A C A
Choice 5
None. The program will enter into an infinite loop.

prashantSum 16Nov2005 12:12

Re: Some Multiple choice questions in Java
 
hi shabbir,

thanks for providing these questions,
I want more objectives on core java and advanced java, where can I get it...

coderzone 2Apr2006 14:40

Re: Some Multiple choice questions in Java
 
Hey very nice collection of questions

devom 8May2006 13:08

Re: Some Multiple choice questions in Java
 
Hi,
the questions are really good. but plz provide their answers too as early as possible.........

shabbir 8May2006 20:01

Re: Some Multiple choice questions in Java
 
Sorry but we dont want to provide the spoilers here so that everyone can try them out. If you are unable to solve any or need any help try creating a new thread with the concerned question instead.

Creator 23May2006 16:35

Re: Some Multiple choice questions in Java
 
Hey good Collection of questions. Thank you..

data77 6Mar2007 00:21

Re: Some Multiple choice questions in Java
 
Can you please send me the answers. I wanna check if i was good ennough
thanks

DaWei 6Mar2007 23:02

Re: Some Multiple choice questions in Java
 
See post #9. It's part of this thread.

siddiquisalman 11Mar2007 10:50

Re: Some Multiple choice questions in Java
 
Hello Guys;
If anybody had solved these multiple choice question, please email me.
:confused:
I am giving my certification exam tomorrow, So I cant discuss and get my queries solved, please email me the answers.

Hope u understand my problem....

Salman

coolrc 27Nov2007 00:10

Re: Some Multiple choice questions in Java
 
Hi
Thanks very much for the post.Can you please send me the answers to my mail I.D reddync@gmail.com so that i can verify mine with correct answers please.


All times are GMT +5.5. The time now is 00:01.