You are on page 1of 125

1.

Which four options describe the correct default values for array elements of the types indicated? 1. 2. 3. 4. 5. 6. int -> 0 String -> "null" Dog -> null char -> '\u0000' float -> 0.0f boolean -> true

A. C.

1, 2, 3, 4 2, 4, 5, 6

B. D.

1, 3, 4, 5 3, 4, 5, 6

Answer & Explanation

Answer: Option B Explanation: (1), (3), (4), (5) are the correct statements. (2) is wrong because the default value for a String (and any other object reference) is null, with no quotes. (6) is wrong because the default value for boolean elements is false. View Answer Workspace Report Discuss in Forum 2.

Which one of these lists contains only Java programming language keywords? A. B. C. D. E. class, if, void, long, Int, continue goto, instanceof, native, finally, default, throws try, virtual, throw, final, volatile, transient strictfp, constant, super, implements, do byte, break, assert, switch, include

Answer & Explanation

Answer: Option B Explanation: All the words in option B are among the 49 Java keywords. Although goto reserved as a keyword

in Java, goto is not used and has no function. Option A is wrong because the keyword for the primitive int starts with a lowercase i. Option C is wrong because "virtual" is a keyword in C++, but not Java. Option D is wrong because "constant" is not a keyword. Constants in Java are marked static and final. Option E is wrong because "include" is a keyword in C, but not in Java. View Answer Workspace Report Discuss in Forum 3.

Which will legally declare, construct, and initialize an array? A. B. C. D. int [] myList = {"1", "2", "3"}; int [] myList = (5, 8, 2); int myList [] [] = {4,9,7,0}; int myList [] = {4, 3, 7};

Answer & Explanation

Answer: Option D Explanation: The only legal array declaration and assignment statement is Option D Option A is wrong because it initializes an int array with String literals. Option B is wrong because it use something other than curly braces for the initialization. Option C is wrong because it provides initial values for only one dimension, although the declared array is a two-dimensional array. View Answer Workspace Report Discuss in Forum 4.

Which is a reserved word in the Java programming language? A. C. method subclasses B. D. native reference

E.

array

Answer & Explanation

Answer: Option B Explanation: The word "native" is a valid keyword, used to modify a method declaration. Option A, D and E are not keywords. Option C is wrong because the keyword for subclassing in Java is extends, not 'subclasses'. View Answer Workspace Report Discuss in Forum 5.

Which is a valid keyword in java? A. C. interface Float B. D. string unsigned

Answer & Explanation

Answer: Option A Explanation:

interface is a valid keyword.
Option B is wrong because although "String" is a class type in Java, "string" is not a keyword. Option C is wrong because "Float" is a class type. The keyword for the Java primitive is float. Option D is wrong because "unsigned" is a keyword in C/C++ but not in Java. View Answer Workspace Report Discuss in Forum 6. Which three are legal array declarations? 1. 2. 3. 4. 5. int [] myScores []; char [] myChars; int [6] myScores; Dog myDogs []; Dog myDogs [7];

A.

1, 2, 4

B.

2, 4, 5

2 and 3 3. and final. but it's perfectly legal to split the brackets in a multidimensional array. 2. With an array declaration. 2. /* Line 3 */ } Which three piece of codes are equivalent to line 3? 1. Interface constant declarations of public. volatile int k = 4. and final are optional in any combination. public int k = 4. 5 and 6 Answer & Explanation Answer: Option A Explanation: (1). Answer & Explanation Answer: Option A Explanation: (1). 1. based on the type of array and the size). static int k = 4. abstract int k = 4. View Answer Workspace Report Discuss in Forum 7. 5. All are correct. Although coding this way would only annoy your fellow programmers. (2). 4 D. 3 and 4 4. 4 and 5 B.static. A. for the exam. static. 6. 3. and place them on both sides of the identifier. protected int k = 4. and (4) are legal array declarations. final int k = 4. D. . 4. 3. Option A looks strange. public interface Foo { int k = 4. The size is only needed when the array is actually instantiated (and the JVM needs to know how much space to allocate for the array. Interfaces can have constants. 2. you need to know it's legal.C. C. which are always implicitly public. you can place the brackets to the right or left of the identifier. (3) and (5) are wrong because you can't declare an array with a size. (2) and (3) are correct.

3.22. Option C is wrong because it shows a legal array declaration.20. you can be certain there is no actual array object! In other words. A. 0xbeef. \u0022. Array a = new Array(5). 2.21. passing the integer value 5 to the object's constructor. Which three are valid declarations of a char? 1. 6. C. Which one of the following will declare an array and initialize it with five numbers? A. 1.19}. 3. '\iface'. 5 . but with no initialization. int [] a = {23. Option A is wrong because it shows an example of instantiating a class namedArray. Arrays must never be given a size when declared. Option D is wrong (and will not compile) because it declares an array with a size. int a [] = new int[5]. 5. '\uface'. Answer & Explanation Answer: Option B Explanation: Option B is the legal way to declare and initialize an array with five elements. C. View Answer Workspace Report Discuss in Forum 9. 4. B. 4 1. B. 2. D. 6 3. char char char char char char c1 c2 c3 c4 c5 c6 = = = = = = 064770.View Answer Workspace Report Discuss in Forum 8. int [5] array. anArray object (instance of class Array) is not the same as an array object. If you don't see the brackets. 'face'.

The only other acceptable char literal that can go between single quotes is a Unicode value.D. is wrong because the single quotes are missing. is an octal representation of the integer value 27128. public final double methoda(). D. but starts with '\i' rather than '\u'. A final method cannot be abstract. and Unicode literals must always start with a '\u'. char c2 = 'face'. Option C is wrong. static is concerned with the class and not an instance. is wrong because you can't put more than one character in a char literal. is wrong because it appears to be a Unicode representation (notice the backslash). The final modifier means that this method cannot be constructed in a subclass. B. public double methoda(). static void methoda(double d1). (3). char c4 = \u0022. A public access modifier is acceptable. The method prototypes in an interface are all abstract by virtue of their declaration. is a hexadecimal representation of the integer value 48879. char c1 = 064770. Which is the valid declarations within an interface definition? A. char c6 = '\uface'. View Answer Workspace Report Discuss in Forum 10. which fits into an unsigned 16-bit integer. char c5 = '\iface'. and (6) are correct.char c3 = 0xbeef. . Answer & Explanation Answer: Option A Explanation: Option A is correct. and should not be declared abstract. 5 only Answer & Explanation Answer: Option B Explanation: (1). is a Unicode representation of a character. protected void methoda(double d1). Option B is wrong. which is legal because it fits into an unsigned 16-bit integer. C.

Option D is wrong. C. View Answer Workspace Report Discuss in Forum 12. 3. C.0D. you may not use the private and protected specifiers when declaring members of an interface. Member declarations in an interface disallow the use of some declaration modifiers. D. boolean b1 = 0. 1. float float float float float float f1 f2 f3 f4 f5 f6 = = = = = = -343. A. 6. 5. 3. 3. 4. 2. 2. protected is not permitted when declaring a method of an interface. 0x12345. you cannot use transient. Also. 2. boolean b2 = 'false'. View Answer Workspace Report Discuss in Forum 11. 4. See information below. 42e7. 5 2. 2. E. volatile. boolean b4 = Boolean. B. or synchronized in a member declaration in an interface.81F. boolean b3 = false. Answer & Explanation Answer: Option C Explanation: A boolean can only be assigned the literal true or false. 2001. Which one is a valid declaration of a boolean? A.14. Which three are valid declarations of a float? 1. 4 1. 6 Answer & Explanation Answer: Option C . 3. boolean b5 = no. D.false(). 6 B.

-128 to 127 0 to 32767 B. Option B is wrong because null cannot be in single quotes.Explanation: (1) and (3) are integer literals (32 bits). View Answer Workspace Report Discuss in Forum 14. Which is a valid declarations of a String? A. B. -(215) to (215) . and integers can be legally assigned tofloats (also 32 bits). String s1 = null.and (5) are all doubles. What is the numerical range of a char? A. Answer & Explanation Answer: Option A Explanation: Option A sets the String reference to null. (6) is correct because (F) is appended to the literal. C. declaring it as a float rather than a double (the default for floating point literals). Option D is wrong because you can't cast a char (primitive) to a String (object). View Answer Workspace Report Discuss in Forum 13. String s3 = (String) 'abc'. (4). Option C is wrong because there are multiple characters between the single quotes ('abc'). (2).1 0 to 65535 Answer & Explanation Answer: Option D Explanation: . C. D. String s4 = (String) '\ufeed'. String s2 = 'null'. D.

Method and variable members are given access control in exactly the same way. C. private transient Answer & Explanation Answer: Option C Explanation: Access modifiers dictate which classes. You want subclasses in any package to have access to members of a superclass. not which instances. can access the member (assuming the class itself is visible) final makes it impossible to extend a class. Methods and variables are collectively known as members.A char is really a 16-bit integer behind the scenes. may access features. public means that all other classes regardless of the package that they belong to. Which is the most restrictive access that accomplishes this objective? A. . D. so it supports 216 (from 0 to 65535) values. public protected B. View Answer Workspace Report Discuss in Forum 1. when applied to a variable it makes it impossible to reinitialise a variable once it has been initialised abstract declares a method that has not been implemented. when applied to a method it prevents a method from being overridden in a subclass. private makes a member accessible only from within its own class protected makes a member accessible only to classes in the same package or subclass of the class default access is very similar to protected (make sure you spot the difference) default access makes a member accessible only to classes in the same package.

non-static variable cannot be referenced from a static context. Option B gives error . Option C package ot does not exist. . volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. D. //At line 5 new Inner(). View Answer Workspace Report Discuss in Forum 2.protected. C.transient indicates that a variable is not part of the persistent state of an object. //Line 10 } } Which of the following code fragments inserted. will allow to compile? A. //At line 10 Answer & Explanation Answer: Option A Explanation: Option A compiles without problem. B. //At line 10 new ot. A is also a contender but C is more restrictive. public class Outer { public void someOuterMethod() { //Line 5 } public class Inner { } public static void main(String[] argv) { Outer ot = new Outer(). new Inner().Inner().Inner(). After examining the above it should be obvious that the access modifier that provides the most restrictions for methods to be accessed from the subclasses of the class from another package is C . //At line 10 new Outer. B would be the answer if the constraint was the "same package" instead of "any package" in other words the subclasses clause in the question eliminates default.

5. C. 3. byte m2(short s). abstract class Class2 extends Base { public boolean m1(){ return true. Which three form part of correct array declarations? 1. abstract class Class2 implements Base { protected boolean m1(){ return (5 > 7) }} A. (1) is incorrect because interfaces don't implement anything. } which two code fragments will compile? 1. abstract class Class2 implements Base { public boolean m1(){ return (7 > 4). abstract class Class2 implements Base {} 4. D. View Answer Workspace Report Discuss in Forum 4. 1 and 2 3 and 4 B. (5) is incorrect because interface methods are implicitly public.non-static variable cannot be referenced from a static context. public int a [ ] static int [ ] a public [ ] int a private int a [3] private int [3] a [ ] public final int [ ] a . 2. 2 and 3 1 and 5 Answer & Explanation Answer: Option C Explanation: (3) is correct because an abstract class doesn't have to implement any or all of its interface's methods. interface Base2 implements Base {} 2. interface Base { boolean m1 (). View Answer Workspace Report Discuss in Forum 3. }} 5.Option D gives error . 4. (2) is incorrect because classes don't extend interfaces. so the methods being implemented must be public. 6. }} 3. (4) is correct because the method is correctly implemented ((7 > 4) is a boolean).

1. Option (3) is not a correct array declaration. C. D. D. View Answer Workspace Report Discuss in Forum 5. 5 2. 6 Answer & Explanation Answer: Option C Explanation: (1). 2. 2. 4 1. public class Test { } What is the prototype of the default constructor? A. The compiler complains with: ']' expected. 3. The compiler complains with: illegal start of type. Test(void) public Test(void) Answer & Explanation Answer: Option C Explanation: Option A and B are wrong because they use the default access modifier and the access modifier for the class is public (remember. 6 B. The following works:private int a [] Option (5) is not a correct array declaration. The void makes the compiler think that this is a method specification . View Answer Workspace Report Discuss in Forum . (2) and (6) are valid array declarations.A. the default constructor has the same access modifier as the class). 4.in fact if it were a method specification the compiler would spit it out. The brackets are in the wrong place. The following would work:public int[ ] a Option (4) is not a correct array declaration. 5. C. Test( ) public Test( ) B. A closing bracket is expected in place of the 3. Option D is wrong. A closing bracket is expected in place of the 3 and <identifier> expected A variable name is expected after a[ ] . The compiler complains with 2 errors: ']' expected.

protected abstract void m1(). E. Option A and C are wrong because public and protected are less restrictive.6. Option B and D are wrong because abstract and synchronized are not access modifiers. 4. C. 3. abstract synchronized Answer & Explanation Answer: Option E Explanation: default access is the "package oriented" access modifier. C. D. public protected default access B. B. 1 and 3 2 and 4 1 only All of them are legal declarations. A. View Answer Workspace Report Discuss in Forum . What is the most restrictive access modifier that will allow members of one class to have access to members of another class in the same package? A. static final void m1(){} synchronized public final void m1() {} private native void m1(). Which of the following is/are legal method declarations? 1. D. View Answer Workspace Report Discuss in Forum 7. 2. Answer & Explanation Answer: Option D Explanation: All the given statements are legal declarations.

"Zeus"}. private int getArea(). String cats[ ] = {"Fluffy". int [ ][ ] scores = {2. Which cause a compiler error? A. new Integer(5).7. whereas your intention was to create one 3 x 3 two-dimensional array. true}. View Answer Workspace Report Discuss in Forum 9. Integer results[ ] = {new Integer(3).3. public float getVol(float x).45}. 1 and 2 3. false. A. C. 7}. boolean results[ ] = new boolean [] {true. E. {9. 2. public void main(String [] args). 2. 5. 3. new Integer(8)}. {9. To correct the problem and make option B compile you need to add an extra pair of curly brackets: int [ ] [ ] scores = { {2.3. The compiler thinks you are trying to create two arrays because there are two array initialisers to the right of the equals. "Spot". D. Answer & Explanation Answer: Option B Explanation: Option B generates a compiler error: <identifier> expected.6}. and 5 B. D. 3 and 5 2 and 4 Answer & Explanation Answer: Option B Explanation: . boolean setFlag(Boolean [] test). public static void main(String [] args).7.8. 4. Which three are valid method signatures in an interface? 1.45} }. 4. 5. B.6}. int[ ] scores = {3. C.

int long B. These are all valid interface method signatures. You want a class to have access to members of another class in the same package. What is the narrowest valid returnType for methodA in line 3? public class ReturnIt { returnType methodA(byte x. It is the .(2). double y) /* Line 3 */ { return (long)x / y * 2. B and C are all wrong. Each of these would result in a narrowing conversion. if it is not explicitly declared public it will be made public implicitly. } } A. Don't be put off by the long cast. Which is the most restrictive access that accomplishes this objective? A. is incorrect because an interface method must be public. private default access Answer & Explanation Answer: Option D Explanation: The only two real contenders are C and D. public protected B. D. (3). therefore the only correct answer is D. and (5). byte double Answer & Explanation Answer: Option D Explanation: However A. Protected access Option C makes a member accessible only to classes in the same package or subclass of the class. (4) is incorrect because interface methods cannot be static. this applies only to the variable x and not the rest of the expression. (1). View Answer Workspace Report Discuss in Forum 11. Whereas we want a widening conversion. C. D. View Answer Workspace Report Discuss in Forum 10. While default access Option D makes a member accessible only to classes in the same package. C.

int b) { return 0.because it can't override as there are less access privileges in the subclass method1. a long. or a double. . } private int method1(int a.From a short. } static protected int method1(int a.From a long to a float. a float. or a double. the return type needs to be an integer. or a double. an int.variable y (of type double) that forces the widening conversion to double.From a float to a double. } } Which is valid in a class that extends class A? A. . View Answer Workspace Report Discuss in Forum 12. int b) {return 0.From an int to a long. D. . . a float.because the class that extends A is just simply overridingmethod1.because to override it. C. int b) { return 0. public int method1(int a. or a double.From a byte to a short. Option C is wrong . a float. Java's widening conversions are: . an int. class A { protected int method1(int a. } Answer & Explanation Answer: Option A Explanation: Option A is correct . } public short method1(int a. int b) { return 0. The different return type means that the method is not overriding but the same argument list means that the . a float. or a double. a long.From a char to an int. a long. int b) { return 0. Option B is wrong . . B.

final abstract class Test {} public static interface Test {} final public class Test {} protected abstract class Test {} protected interface Test {} abstract public class Test {} . 5. It uses correct array declaration and correct array construction. It generates a compiler error: incompatible types because a string literal is not assignable to a character type variable. Option D is wrong . { 1.compile time error. but it is supplied with a primitive type in the declaration. Conflict . View Answer Workspace Report Discuss in Forum 13.3 }. Option B is incorrect. 6 }. Option C is incorrect. Which one creates an instance of an array? A. char[ ] ca = "Some String". whereas your intention was to create a 3 x 3 two-dimensional array. The array construction expects a reference type.2. 2. It generates a compiler error: incompatible types because the array variable declaration is not correct. View Answer Workspace Report Discuss in Forum 14. The compiler thinks that you are trying to create two arrays because there are two array initialisers to the right of the equals. using static. it generates a compiler error <identifier> expected. 3.e. Option D is wrong. B. 6. 5.method is not overloading. Which two of the following are legal declarations for nonnested classes and interfaces? 1. 4. int ia[ ] [ ] = { 4. int[ ] ia = new int[15]. C. float fa = new float[20]. Answer & Explanation Answer: Option A Explanation: Option A is correct. D.because you can't override a method and make it a class method i.

float f3[ ] = new float[3].A. transient int b = 3. C. Which two cause a compiler error? 1. (6). float f2[ ] = new float[ ]. . Both are legal class declarations. D. float[ ]f1 = new float[3]. D. 2. Answer & Explanation Answer: Option C Explanation: Option C will not compile. C. Option A and B will compile because protected and transient are legal variable modifiers. View Answer Workspace Report Discuss in Forum 15. 2 and 5 4 and 6 Answer & Explanation Answer: Option C Explanation: (3). private synchronized int e. 1 and 4 3 and 6 B. (4) and (5) are wrong because classes and interfaces cannot be marked as protected. B. volatile int d. 3. 4. Option D will compile because volatile is a proper variable modifier. (2) is wrong because interfaces and classes cannot be marked as static. View Answer Workspace Report Discuss in Forum 16. Which of the following class level (nonlocal) variable declarations will not compile? A. protected int a. float[ ] f = new float(3). (1) is wrong because a class cannot be abstract and final—there would be no way to use such a class. the synchronized modifier applies only to methods.

5 1. 4 4. B. Option A. static protected Answer & Explanation Answer: Option C Explanation: The private access modifier limits access to members of the same class. what access modifier do you use to restrict access to that method to only the other members of the same class? A. View Answer Workspace Report Discuss in Forum 17.0f}. and (5) compile without error. static.0f. (2) causes a compiler error ( '{' expected ) because the array constructor does not specify the number of elements in the array. The following is the correct syntax: float[ ] f = new float[3]. D. 2 Answer & Explanation Answer: Option D Explanation: (1) causes two compiler errors ( '[' expected and illegal start of expression) because the wrong type of bracket is used. ( ) instead of [ ]. 2. View Answer Workspace Report Discuss in Forum 18. Given a method in a protected class. The following is the correct syntax:float f2[ ] = new float[3]. (3). D.0f. (4). and E are wrong because protected are the wrong access modifiers. 2. and volatile are modifiers but not access modifiers. final private volatile B. float f5[ ] = {1.5. 3. A. C. D. Which is a valid declaration within an interface? . and final. C. E. 2. 5 B.

Answer & Explanation Answer: Option A Explanation: (A) is valid interface declarations. View Answer Workspace Report Discuss in Forum 1. (B) and (C) are incorrect because interface variables cannot be either protected ortransient. What will be the output of the program? class PassA { public static void main(String [] args) { . (D) is incorrect because interface methods cannot be final or static.A. B. C. public static short stop = 23. final void madness(short stop). D. protected short stop = 23. transient short stop = 23.

15 15 375375 Answer & Explanation Answer: Option B Explanation: Output: 15 15 The reference variables a1 and a3 refer to the same long array object. long [] a2 = fix(a1).PassA p = new PassA(). C. } boolean fix(boolean b1) . The reference variable a2 refers to the same array object.4.out. } void start() { long [] a1 = {3. What will be the output of the program? class Test { public static void main(String [] args) { Test p = new Test(). } } A.print(a1[0] + a1[1] + a1[2] + " ").println(a2[0] + a2[1] + a2[2]). return a3. System. } void start() { boolean b1 = false. boolean b2 = fix(b1).println(b1 + " " + b2). System. D. it is updating the array referred to bya1.start().out.out. 12 15 345375 B.5}. } long [] fix(long [] a3) { a3[1] = 7. p. When the[1] element is updated in the fix() method. p.start(). View Answer Workspace Report Discuss in Forum 2. System.

C.start(). } } A. View Answer Workspace Report Discuss in Forum 3. B. false true false false Answer & Explanation Answer: Option B Explanation: The boolean b1 in the fix() method is a different boolean than the b1 in thestart() method. System. String s2 = fix(s1). System. return b1. } String fix(String s1) { s1 = s1 + "stream". true true true false B. return "stream". C.{ b1 = true.out. } } A. What will be the output of the program? class PassS { public static void main(String [] args) { PassS p = new PassS(). p.println(s1 + " " + s2). slip stream slipstream stream stream slip stream . The b1 in the start() method is not updated by the fix()method.print(s1 + " "). D. } void start() { String s1 = "slip".out.

referred to by s2 and with a value of "stream". C. What will be the output of the program? class BitShift { public static void main(String [] args) { int x = 0x80000000. Fix()'s s1 is reassigned to a new object that is created when the concatenation occurs (this second String object has a value of "slipstream"). start()'s s1 and fix()'s s1 reference variables both refer to the same String object (with a value of "slip").out. -2147483648 and 1 0x80000000 and 0x00000001 -2147483648 and -1 1 and -2147483648 Answer & Explanation Answer: Option A Explanation: Option A is correct. When the program returns tostart(). zero filling the left bits. View Answer Workspace Report Discuss in Forum 4. System.print(x + " and "). The >>> operator moves all bits to the right.println(x). The bit transformation looks like this: Before: 1000 0000 0000 0000 0000 0000 0000 0000 . System. slipstream slip stream Answer & Explanation Answer: Option D Explanation: When the fix() method is first entered.out. D. } } A.D. x = x >>> 31. another String object is created. B.

What will be the output of the program? . the output would be false. View Answer Workspace Report Discuss in Forum 6. as shown. The == operator compares values to produce a boolean. C. boolean b = (x = y). and D are incorrect because the code does not get as far as compiling. double y = 100. What will be the output of the program? class Equals { public static void main(String [] args) { int x = 100. which in this case changes the sign of x. B. View Answer Workspace Report Discuss in Forum 5. true false Compilation fails An exception is thrown at runtime Answer & Explanation Answer: Option C Explanation: The code will not compile because in line 7. the line will work only if we use (x==y)in the line. Option D is incorrect because this is the reverse order of the two output numbers. /* Line 7 */ System. whereas the =operator assigns a value to variables.1.out.println(b). B. Option B is incorrect because the output method print() always displays integers in base 10. Option A.After: 0000 0000 0000 0000 0000 0000 0000 0001 Option C is incorrect because the >>> operator zero fills the left bits. D. } } A. If we corrected this code.

tiny Compilation fails Answer & Explanation Answer: Option B Explanation: This is an example of a nested ternary operator. int y= 0. String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge". C.out. small huge B. D. D.println(sup). z++) { if (( ++x > 2 ) && (++y > 2)) { x++. } } A. 52 63 B.class Test { public static void main(String [] args) { int x=20. 53 64 Answer & Explanation Answer: Option C . What will be the output of the program? class Test { public static void main(String [] args) { int x= 0.println(x + " " + y). z < 5. so the "tiny" value is assigned to sup. } } A. View Answer Workspace Report Discuss in Forum 7. C.out. System. for (int z = 0. The second evaluation (x < 22)is true. } } System.

View Answer Workspace Report Discuss in Forum 9. What will be the output of the program? class Bitwise { public static void main(String [] args) { int x = 11 & 9.println(x + " " + y). What will be the output of the program? class Test { public static void main(String [] args) { int x= 0. and in the fifth iteration x is doubly incremented and y is incremented. for (int z = 0.out. The short circuit or operator || keeps y from ever being incremented again and x is incremented twice on each of the last three iterations. In the third and forth iterations x and y are each incremented. int y= 0.Explanation: In the first two iterations x is incremented once and y is not because of the short circuit && operator. View Answer Workspace Report Discuss in Forum 8. z++) { if (( ++x > 2 ) || (++y > 2)) { x++. 53 83 B. D. On the third iteration x is incremented. z < 5. } } A. . 82 85 Answer & Explanation Answer: Option B Explanation: The first two iterations of the for loop both x and y are incremented. and for the first time becomes greater than 2. C. } } System.

The result of the & operation is 9.out.println("dokey"). 7 14 Answer & Explanation Answer: Option D Explanation: The & operator produces a 1 bit when both bits are 1.int y = x ^ 3. D. if ( b1 & b2 | b2 & b3 | b2 ) /* Line 8 */ System. the result of this operation is 14. D. ok dokey ok dokey No output is produced Compilation error Answer & Explanation . B.println( y | 12 ). the result of this operation is 10. boolean b3 = true.print("ok "). E. View Answer Workspace Report Discuss in Forum 10. } } A. C. What will be the output of the program? class SSBool { public static void main(String [] args) { boolean b1 = true. if ( b1 & b2 | b2 & b3 | b2 | b1 ) /*Line 10*/ System. boolean b2 = false. } } A. C. The ^ operator produces a 1 bit when exactly one bit is 1. System. The | operator produces a 1 bit when at least one bit is 1.out. 0 8 B.out.

print(a + b).print(" " + 7 System. What will be the output of the program? class SC2 { public static void main(String [] args) { SC2 s = new SC2(). int b = 4.println(a + b } String foo() { return "foo".start(). Answer & Explanation Answer: Option D Explanation: Because all of these expressions use the + operator. 9 7 7 foo 7 7foo 72 34 34 foo34 34foo 9 7 7 foo34 34foo 72 7 34 foo34 7foo + 2 + " "). s. a + b + " ").out.out. } void start() { int a = 3.out. } } A.out. System.print(foo() + System. C.out. there is no precedence to worry about and all . D. + b + " ").Answer: Option B Explanation: The & operator has a higher precedence than the | operator so that on line 8 b1and b2 are evaluated together as are b2 & b3. The final b1 in line 10 is what causes that if test to be true. Hence it prints "dokey". System. B. View Answer Workspace Report Discuss in Forum 11. + foo()).print(" " + a System.

println(s).out. twice(x).of the expressions will be evaluated from left to right. the + operator will concatenate the two operands. Start()'s x is not affected by the twice() method. } void start() { int x = 7. } void twice(int x) { x = x*2. The instance variables is updated by twice()'s x. s = x. System. What will be the output of the program? class Two { . View Answer Workspace Report Discuss in Forum 13. C. If either operand being evaluated is a String. 77 14 0 B.print(x + " "). 7 14 14 14 Answer & Explanation Answer: Option B Explanation: The int x in the twice() method is not the same int x as in the start()method. the + operator will add the two operands. } } A. if both operands are numeric. System. View Answer Workspace Report Discuss in Forum 12. D. which is 14.out. p.start(). public static void main(String [] args) { Test p = new Test(). What will be the output of the program? class Test { static int s.

x + " " + t2. int i) { x[i] = true.out. return tt.x in the fix() method updates t. } class PassO { public static void main(String [] args) { PassO p = new PassO().out.x + " "). void set(boolean [] x. C.x(they are one in the same object). Two t2 = fix(t). } Two fix(Two tt) { tt.x = 42. p. } public static void main(String [] args) . D.byte x.println(t.x).print(t. System. 0 0 42 000 Answer & Explanation Answer: Option C Explanation: In the fix() method.start(). Updating tt. ++count. null null 42 0 42 42 B. } void start() { Two t = new Two(). What will be the output of the program? class BoolArray { boolean [] b = new boolean[3]. int count = 0. } } A. the reference variable tt refers to the same object (classTwo) as the t reference variable. Remember also that the instance variable x in the Two class is initialized to 0. System. View Answer Workspace Report Discuss in Forum 14.

out. ba. 2 8 B. ba. } public static void main(String args[]) { int i = 4. C. D. ba. Because of the && short circuit operator.b. 2).set(ba.2)] ) count += 7. count = 0 count = 3 B. System.{ BoolArray ba = new BoolArray(). leftshift(i.b. and once again when the first if test is true. if ( b[1] && b[(++count .printIn(i). } } A. j). 0). C.set(ba. } void test() { if ( b[0] && b[1] | b[2] ) count++. int j) { i <<= j. What will be the output of the program? public class Test { public static void leftshift(int i.println("count = " + count). D. count = 2 count = 4 Answer & Explanation Answer: Option C Explanation: The reference variables b and x both refer to the same boolean array. j = 2. 4 16 Answer & Explanation . View Answer Workspace Report Discuss in Forum 15. count is not incremented during the second if test.out. System.test(). } } A. count is incremented for each call to the set() method.

Answer: Option B Explanation: Java only ever passes arguments to a method by value (i.out. If you had 128 right shifted by 2 bits then 128 / 2 / 2 = 32. a copy of the variable) and never by reference. } else /* Line 11 */ { if ( !b ) { System. boolean b) { if( a ) { System. } } } A.println( "A && B"). View Answer Workspace Report Discuss in Forum 1. If a is true and b is true then the output is "A && B" . Therefore the value of the variable i remains unchanged in the main method.println("A").out.println( "ELSE" ) . you don't have to go converting to binary to do the left and right bit shifts. If you are clever you will spot that 16 is 4 multiplied by 2 twice.out. /* Line 5 */ } else if(a && b) /* Line 7 */ { System. } else { System. Keeping these points in mind. (4 * 2 * 2) = 16.out. If you had 16 left shifted by three bits then 16 * 2 * 2 * 2 = 128.println( "notB") .e. public void foo( boolean a.

B. C. D.

If a is true and b is false then the output is "notB" If a is false and b is true then the output is "ELSE" If a is false and b is false then the output is "ELSE"

Answer & Explanation

Answer: Option C Explanation: Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get some chance of executing. Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be "A && B". Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. Option D is wrong. The output is "notB". View Answer Workspace Report Discuss in Forum 2.

switch(x) { default: System.out.println("Hello"); } Which two are acceptable types for x? 1. 2. 3. 4. 5. 6. byte long char float Short Long

A. C.

1 and 3 3 and 5

B. D.

2 and 4 4 and 6

Answer & Explanation

Answer: Option A Explanation:

Switch statements are based on integer expressions and since both bytes and chars can
implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables. View Answer Workspace Report Discuss in Forum 3.

public void test(int x) { int odd = 1; if(odd) /* Line 4 */ { System.out.println("odd"); } else { System.out.println("even"); } } Which statement is true? A. B. C. D. Compilation fails. "odd" will always be output. "even" will always be output. "odd" will be output for odd values of x, and "even" for even values.

Answer & Explanation

Answer: Option A Explanation: The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer. View Answer Workspace Report Discuss in Forum 4.

public class While { public void loop() { int x= 0; while ( 1 ) /* Line 6 */

{ System.out.print("x plus one is " + (x + 1)); /* Line 8 */ } } } Which statement is true? A. B. C. D. There is a syntax error on line 1. There are syntax errors on lines 1 and 6. There are syntax errors on lines 1, 6, and 8. There is a syntax error on line 6.

Answer & Explanation

Answer: Option D Explanation: Using the integer 1 in the while statement, or any other looping or conditional construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java. A, B and C are incorrect because line 1 is valid (Java is case sensitive so While is a valid class name). Line 8 is also valid because an equation may be placed in a String operation as shown. View Answer Workspace Report Discuss in Forum 1. What will be the output of the program?

int i = l, j = -1; switch (i) { case 0, 1: j = 1; /* Line 4 */ case 2: j = 2; default: j = 0; } System.out.println("j = " + j); A. C. j = -1 j=1 B. D. j=0 Compilation fails.

Answer & Explanation

Answer: Option D Explanation: The case statement takes only a single argument. The case statement on line 4 is given two

println("i = " + i + " and j = " + j). and then tests the loop condition. } j--. so i can reach the value of 5 before it fails. 10 2. if bigger. which always executes the code block within the block at least once. 9 3. i = 6 and j = 5 i = 6 and j = 4 B. do { if(i > j) { break. System. test i against j. where a pre-incremented by one i is tested for being lower than 5. 6 loop condition fails. So it goes. C. The test is at the end of the loop. start: 1. What will be the output of the program? .out. View Answer Workspace Report Discuss in Forum 2. D.arguments so the compiler complains. decrements j by one. 8 4. it breaks from the loop. } while (++i < 5). A. The order is. rather than at the beginning. 7 5. This particular loop is exited prematurely if i becomes greater than j. What will be the output of the program? int i = 1. due to the testing condition being at the end of the loop. View Answer Workspace Report Discuss in Forum 3. j = 10. i = 5 and j = 5 i = 5 and j = 6 Answer & Explanation Answer: Option D Explanation: This loop is a do-while loop.

which means the expressions can be evaluated at compile time. public static void main(String [] args) { for (int z=0. What will be the output of the program? public class SwitchTest { public static void main(String[] args) { System. public static int y = 0.print("0 ").out. x is matched.public class Switch2 { final static short x = 2. case 2: j++. In the first iteration of the for loop case x-2 matches. case 4: j++. View Answer Workspace Report Discuss in Forum 4. z++) { switch (z) { case x: System. D.out. } } } } A.out. once a match is found all remaining statements are executed until a break statement is encountered). . 012 210100 B. case 5: j++. In the third iteration.print("2 "). z < 3.println("value =" + switchIt(4)). x-1 is matched so 1 and 2 are printed (remember. In the second iteration. case 3: j++.print("1 "). so 2 is printed. So 0 1 and 2 are printed.out. case x-2: System. } public static int switchIt(int x) { int j = 1. case x-1: System. switch (x) { case l: j++. 012122 212012 Answer & Explanation Answer: Option D Explanation: The case expressions are all legal because x is marked final. C.

value = 2 value = 6 B. } } A. 0 B.println(x). once the desired result is found. } } System. C. value = 4 value = 8 Answer & Explanation Answer: Option D Explanation: Because there are no break statements.out. } return j + x. x++. the program continues though each of the remaining options. } } A. if ( !b1 ) /* Line 7 */ { if ( !b2 ) /* Line 9 */ { b1 = true. else if ( b1 | b2 ) /* Line 21 */ x = x + 1000. else if ( b2 = true ) /* Line 19 */ x = x + 100. View Answer Workspace Report Discuss in Forum 5. if ( 5 > 6 ) { x++. } if ( !b1 ) x = x + 10.default: j++. b2. public static void main(String [] args) { int x = 0. 1 . What will be the output of the program? public class If2 { static boolean b1. D.

public static int y = 0. B. What will be the output of the program? public class Switch2 { final static short x = 2. 012 012122 Compilation fails at line 11. Since line 19 was successful.print("1 "). /* Line 13 */ } } } } A. Since x is marked final. View Answer Workspace Report Discuss in Forum 6. lines 12 and 13 are . The next if test to succeed is on line 19 (note that the code is not testing to see if b2 is true. it is setting b2 to be true). subsequent else-if's (line 21) will be skipped. C. public static void main(String [] args) { for (int z=0.out. D. Compilation fails at line 12. Answer & Explanation Answer: Option C Explanation: Case expressions must be constant expressions. 111 Answer & Explanation Answer: Option C Explanation: As instance variables. /* Line 11 */ case x-1: System.print("0 ").out. b1 and b2 are initialized to false. z++) { switch (z) { case y: System.out.print("2 ").C. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. /* Line 12 */ case x: System. 101 D. z < 3.

System.println(hand).out. do while ( I < 1 ) System. so the if test on line 7 is true and hand is incremented. What will be the output of the program? public class Test { public static void main(String [] args) { int I = 1. if ( hand < 50 & !b ) /* Line 7 */ hand++. 41 50 B. D. } } A. public static void main(String [] args) { short hand = 42. 42 51 Answer & Explanation Answer: Option D Explanation: In Java. C. however y is not a final so the compiler will fail at line 11. boolean instance variables are initialized to false.out.legal.print("I is " + I). What will be the output of the program? public class If1 { static boolean b. /* Line 9 */ else if ( hand > 40 ) { hand += 7. View Answer Workspace Report Discuss in Forum 8. Line 9 is legal syntax. } else --hand. if ( hand > 50 ). } . View Answer Workspace Report Discuss in Forum 7. The else-if is true so hand has 7 added to it and is then incremented. while ( I > 1 ) . a do nothing statement. hand++.

View Answer Workspace Report Discuss in Forum 9. } System.println("x = " + x +" y = " + y).out. Both expressions are false and no output is produced. j++) { . y = 6. C. A. B. while (y--) { x++. What will be the output of the program? int I = 0. You are assured that the while expression will be evaluated at least once. D. nested inside the do-while. C. The first is a do-while loop and the second is a while loop. D. followed by an evaluation of the do-while expression. inner: for (int j = 0. View Answer Workspace Report Discuss in Forum 10. outer: while (true) { I++. j < 10. x=7y=0 Compilation fails. What will be the output of the program? int x = l. I is 1 I is 1 I is 1 No output is produced. x=6y=0 x = 6 y = -1 B.} A. The body of the do-while is only a single statement-brackets are not needed. Compilation error Answer & Explanation Answer: Option C Explanation: There are two different looping constructs in this problem.

It is not a recognised variable outside the code block of loop.out.println(i). and the continue statement is never reached. 024 01234 B. View Answer Workspace Report Discuss in Forum 11. A. D.println(i). if (j == 3) continue inner. 0245 Compilation fails. i += 2) { System. i < 4. break outer. then I will be incremented (by zero) when the for loop is entered. at which point I is printed and the fragment is done.out. Thebreak statement tells the JVM to break out of the outer loop. C. 2 4 Answer & Explanation Answer: Option A Explanation: The program flows as follows: I will be incremented after the while loop is entered. } System. The ifstatement evaluates to false. C.print(i + " "). /* Line 5 */ A. What will be the output of the program? . Answer & Explanation Answer: Option D Explanation: Compilation fails on the line 5 . } System. D.println(I).out. View Answer Workspace Report Discuss in Forum 12.I += j. What will be the output of the program? for (int i = 0. as the variable i has only been declared within the for loop. } continue outer.out.System. 1 3 B.

the if statement receives an integer value instead of a boolean.println("Zero"). C. default: System. C. switch (f) { case 12: System.println("Default").out. Zero Default B.out. int y = 1. The code runs with no output. B. Here a Float wrapper object is used and so the compilation .int x = 3. Twelve Compilation fails Answer & Explanation Answer: Option D Explanation: The switch statement can only be supported by integers or variables more "narrow" than an integer i.out.println("x =" + x). D. What will be the output of the program? Float f = new Float("12"). char. x=1 x=3 Compilation fails. D. } A.println("Twelve"). case 0: System. Answer & Explanation Answer: Option C Explanation: Line 3 uses an assignment as opposed to comparison. short. Because of this. byte. And so the compilation fails.out. if (x = y) /* Line 3 */ { System.e. View Answer Workspace Report Discuss in Forum 13. } A.

foo('B') && (i < 2). C. In Java. } } } . View Answer Workspace Report Discuss in Forum 14. return true. } public static void main( String[] argv ) { int i = 0.fails. i=3 Compilation fails. for (foo('A').println("i = " + i). foo('D'). while(1) { if(i == 4) { break. A. 1 does not represent the true state of a boolean.out. View Answer Workspace Report Discuss in Forum 15. What will be the output of the program? int i = O.print(c). rather it is seen as an integer. What will be the output of the program? public class Delta { static boolean foo(char c) { System. } ++i. Answer & Explanation Answer: Option D Explanation: Compilation fails because the argument of the while loop. foo('C')) { i++.out. D. } System. the condition. i=0 i=4 B. must be of primitive type boolean.

'D' is printed as it is in the loop. ABDCBDCB ABCDABCD Compilation fails. What will be the output of the program? for(int i = 0. At this point the test fails because the other part of the test (i < 2) is no longer true. case 3: System. B. An exception is thrown at runtime.out.print("one "). C. i++) { switch(i) { case 0: break.out.A. D. Again 'B' is printed as part of the loop test. 'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop.println("done"). 'B' is printed as it is part of the test carried out in order to run the loop. 'D' is printed as it is in the loop.out. Answer & Explanation Answer: Option A Explanation: 'A' is only printed once at the very start as it is in the initialisation section of the for loop.print("three "). Again 'B' is printed as part of the loop test. i < 3. The loop will only initialise that once. 'C' is printed as it 'increments' at the end of each loop. i has been increased in value by 1for each loop with the line: i++.out. This results in a printout of ABDCBDCB View Answer Workspace Report Discuss in Forum 16. } } System. . case 1: System.print("two "). Here ends the first loop. case 2: System.

0 B. When i is 2. when the for loop finishes "done" will be output. D.out. case 4: j += 1. C. switch(i) { case 2: j += 6.println("j = " + j). View Answer Workspace Report Discuss in Forum 17. j = 0. default: j += 2. 2 . B.A. "one two three" will be output because case 1. nothing will be printed because of the break in case 0. 1 and 2. "two three" will be output because case 2 and case 3 will be executed (again no break statements). done one two done one two three done one two three two three done Answer & Explanation Answer: Option D Explanation: The variable i will have the values 0. When i is 1. When i is 0. } } A. Finally. case 0: j += 4. What will be the output of the program? public class Test { public static void main(String args[]) { int i = 1. } System. case 2 and case 3will be executed (they don't have break statements).

C. D. } else if(!bool) /* Line 10 */ { System. 4 D. b d Answer & Explanation Answer: Option C Explanation: Look closely at line 2. bool is now false so the condition at line 6 is not true.out. then goes to case 0 and adds 4 to the new j. View Answer Workspace Report Discuss in Forum . What will be the output of the program? boolean bool = true. The condition at line 10 checks to see ifbool is not true ( if !(bool == true) ). C.out. is this an equality check (==) or an assignment (=). if(bool = false) /* Line 2 */ { System.println("c").println("d"). } A. View Answer Workspace Report Discuss in Forum 18. The condition at line 2 evaluates to false and also assigns false to bool. 6 Answer & Explanation Answer: Option D Explanation: Because there are no break statements. } else if(bool) /* Line 6 */ { System. a c B. /* Line 12 */ } else { System. The result is j = 6.println("b").out. it isn't so line 12 is executed. the program gets to the default case and adds 2 to j.out.println("a").

tp: for (. z < 4.print("2 ").print("0 "). z++) { switch (z) { case x: System. default. public static void main(String [] args) { for (int z=0. public static int y = 0. 2 1 0 def 1 2 1 0 def 1 def 1 Answer & Explanation Answer: Option D Explanation: When z == 0 . for (. and that it will match when no other cases match (for instance when z==3).out. D. default: System. } } .19. When z == 3. 0 def 1 2 1 0 def def B.. case x. then x-1 are all matched. then default. When z == 2. When z == 1. C. The rules for default are that it will fall through from above like any other case (for instance when z == 2).out. case x-1: System.out. break. j = 5.. then x-1 are matched. View Answer Workspace Report Discuss in Forum 20.) { i++. What will be the output of the program? public class Switch2 { final static short x = 2. case x-1 is matched and then the break occurs. } } } } A.print("def ").out. case x-2 is matched. case x-2: System. What will be the output of the program? int i = 0.) { if(i > --j) { break tp.print("1 ").

i = 1.println("i =" + i + ".out.print("I is " + I). B. C. None of the above Answer & Explanation Answer: Option C Explanation: The code will not compile because a continue statement can only occur in a looping construct. i = 1. I is 0 I is 0 I is 1 Compilation fails. I++. j = 0 i = 3. C. If this syntax were legal. A. j = " + j). Answer & Explanation Answer: Option D Explanation: If you examine the code carefully you will notice a missing curly bracket at the end of the code. label: if (I < 2) { System. this would cause the code to fail. j = 4 Compilation fails. D.out. } A. j = 4 B. View Answer Workspace Report Discuss in Forum What will be the output of the program? int I = 0. View Answer Workspace Report Discuss in Forum . continue label.System. but the compiler will force you to write cleaner code than this. the combination of the continue and the if statements would create a kludgey kind of loop. D.

Finally Compilation fails. The code runs with no output.out. then once execution enters the try block. Answer & Explanation Answer: Option A Explanation: If you put a finally block after a try and its associated catch blocks. An exception is thrown at runtime. D. the code in that finally block will definitely be executed except in the following circumstances: .println( "Finally" ). } finally { System.1. What will be the output of the program? public class Foo { public static void main(String[] args) { try { return. B. } } } A. C.

Exception. by time theArithmeticException has been specified it has already been caught by theException class. B.exit() 4. } System. An exception arising in the finally block itself. D. What will be the output of the program? try { int x = 0. int y = 5 / x.out. Exception Arithmetic Exception Answer & Explanation Answer: Option C Explanation: Compilation fails because ArithmeticException has already been caught. 3.println("Exception"). The death of the thread.out. A. What will be the output of the program? public class X . If ArithmeticException appears before Exception.println("finished").1. then the file will compile. } catch (Exception e) { System.out. View Answer Workspace Report Discuss in Forum 2. C. Turning off the power to the CPU. } catch (ArithmeticException ae) { System. View Answer Workspace Report Discuss in Forum 3.ArithmeticException is a subclass of java.lang. finished Compilation fails. 2. I suppose the last three could be classified as VM shutdown.println(" Arithmetic Exception"). When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses). The use of System.

ABCD Compilation fails.out.print("C"). } finally { System. System. } System.out.lang. C.Error).print("A").{ public static void main(String [] args) { try { badMethod(). . } catch (Exception ex) { System.out. C is printed before exiting with an error message. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java. What will be the output of the program? public class X { public static void main(String [] args) { try { badMethod(). } public static void badMethod() { throw new Error(). Answer & Explanation Answer: Option C Explanation: Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. BC is printed before exiting with an error message. B.print("B"). View Answer Workspace Report Discuss in Forum 4. /* Line 22 */ } } A.print("D").out. D.

} catch (RuntimeException ex) /* Line 10 */ { System.out. All the code after the finally statement is run because the exception has been caught.print("hello "). What will be the output of the program? public class RTExcept { public static void throwit () { System.out. BCD BCDE Answer & Explanation Answer: Option C Explanation: A Run time exception is thrown and caught in the catch statement on line 10. } public static void main(String [] args) { try { System.print("C"). View Answer Workspace Report Discuss in Forum 5. .print("D").print("caught ").out.out. D.out. throw new RuntimeException().out. C. } System. } } A.print("A").print("B"). } catch (Exception ex1) { System. throwit().out.System.out. BD BDE B.print("throwit "). } catch (Exception re ) { System. } finally { System.print("E"). } public static void badMethod() { throw new RuntimeException().

println("after "). What will be the output of the program? public class Test { public static void aMethod() throws Exception { try /* Line 5 */ { throw new Exception(). /* Line 7 */ } finally /* Line 9 */ { System. } catch (Exception e) /* Line 20 */ { System. /* Line 11 */ } } public static void main(String args[]) { try { aMethod(). View Answer Workspace Report Discuss in Forum 6.out. } } A. B. finally runs (as it always does). C.out. .out.out.print("finally ").print("finally "). Remember that properly handled exceptions do not cause the program to stop executing. hello throwit caught Compilation fails hello throwit RuntimeException caught after hello throwit caught finally after Answer & Explanation Answer: Option D Explanation: The main() method properly catches and handles the RuntimeException in the catch block. B and C are incorrect based on the program logic described above. } System. D. A.} finally { System.print("exception "). and then the code returns to normal.

/* Line 24 */ } } A. and "finished" is output (line 24).out. What will be the output of the program? public class X { public static void main(String [] args) { try { badMethod(). C. B. View Answer Workspace Report Discuss in Forum 7.} System. System. (5) Lastly program execution continues. (3) The finally block completes normally. This prints "exception". (2) The exception cannot be assigned to the parameter of any catch clause of the try statement therefore the finally block is executed (line 9) and "finally" is output (line 11). D.print("A"). (4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20). } catch (Exception ex) .print("finished"). and then the try statement completes abruptly because of the throw statement (line 7).out. finally exception finished finally exception finished Compilation fails Answer & Explanation Answer: Option C Explanation: This is what happens: (1) The execution of the try block (line 5) completes abruptly because of the throwstatement (line 7). because the exception has been caught.

print("B"). } System. BC ABCD Answer & Explanation Answer: Option C Explanation: There is no exception thrown. } } . /* Line 12 */ } finally /* Line 14 */ { System. D. What will be the output of the program? public class X { public static void main(String [] args) { try { badMethod(). so all the code with the exception of the catch statement block is run. /* Line 16 */ } System.out.out.out.out. /* Line 7 */ System.print("D").out.print("C").out. /* Line 18 */ } public static void badMethod() { throw new RuntimeException().print("B"). } catch (Exception ex) /* Line 10 */ { System.out.{ System. } public static void badMethod() {} } A. View Answer Workspace Report Discuss in Forum 8.print("C"). AC ACD B. C. } finally { System.print("A").print("D").

Nothing. } } } A. AB ABC B. (3) The exception is caught (line 10) and "B" is output (line 12) (4) The finally block (line 14) is always executed and "C" is output (line 16).println("Finally executing "). BC BCD Answer & Explanation Answer: Option D Explanation: (1) A RuntimeException is thrown. C. B. so the program continues with line 18 and outputs "D". Hello world Finally executing Answer & Explanation . this is a subclass of exception. Hello world. Nothing. (2) The exception causes the try to complete abruptly (line 7) therefore line 8 is never executed. View Answer Workspace Report Discuss in Forum 9.A. The program will not compile because no exceptions are specified.out. The program will not compile because no catch clauses are specified.print("Hello world "). (5) The exception was caught. C. } finally { System.out. D. What will be the output of the program? public class MyProgram { public static void main(String args[]) { try { System. D.

C. printing Hello world. Option A. and will then execute the finally block.out. Remember that either a catch or a finally statement must follow a try. B. } catch (Exception e) { System. Ex0 caught exception caught Compilation fails because of an error at line 2. Answer & Explanation Answer: Option A Explanation: . } } } A. printing Finally executing. B.println("Ex0 caught"). What will be the output of the program? class Exc0 extends Exception { } class Exc1 extends Exc0 { } /* Line 2 */ public class Test { public static void main(String args[]) { try { throw new Exc1(). Since the finally is present. View Answer Workspace Report Discuss in Forum 10. the catch is not required.out. D. /* Line 9 */ } catch (Exc0 e0) /* Line 11 */ { System.println("exception caught"). and C are incorrect based on the program logic described above. Compilation fails because of an error at line 9. The program will first execute the try block.Answer: Option D Explanation: Finally clauses are always executed.

including close(). This program fails to compile due to an error at line 13. This program fails to compile due to an error at line 4.").close() in the finally block must fall inside a (in this case nested) try-catch block. or the call to out. View Answer Workspace Report Discuss in Forum 1. the main() method) that throws a checked exception (in this case.close() ) must be called within a try clause. out. } } } and given that all methods of class FileOutputStream. Answer & Explanation Answer: Option D Explanation: Any method (in this case. public class MyProgram { public static void main(String args[]) { FileOutputStream out = null.txt").*. View Answer Workspace Report Discuss in Forum 2. } catch(IOException io) { System. This program will compile successfully. import java.write(122). Either main() must declare that it throws an exception.An exception Exc1 is thrown and is caught by the catch statement on line 11. which of these is true? A. This program fails to compile due to an error at line 6. throw anIOException. try { out = new FileOutputStream("test. B.close(). public class MyProgram { .out. The code is executed in this block. out. or the method must declare that it throws the exception.io.println("IO Error. C. } finally { out. D. There is no finally block of code to execute.

the finally block will be executed and the program will be terminated. then will print Done with try block. and then will print Finally executing.public static void throwit() { throw new RuntimeException().out. System. and then will print Finally executing. C.println("Done with try block "). View Answer Workspace Report Discuss in Forum 3. } public static void main(String args[]) { try { System. throwit(). } } At Point X on line 5. } finally { System. then will print Finally executing. If a method does not handle an exception. The program will print Hello world. } } } which answer most closely indicates the behavior of the program? A. public class ExceptionTest { class TestException extends Exception {} public void runTest() throws TestException {} public void test() /* Point X */ { runTest(). which code is necessary to make the code compile? .out. then will print that a RuntimeExceptionhas occurred. D. The program will print Hello world. then will print that a RuntimeException has occurred. then will print that a RuntimeExceptionhas occurred.println("Finally executing ").out. The program will not compile.println("Hello world "). Answer & Explanation Answer: Option D Explanation: Once the program throws a RuntimeException (in the throwit() method) that is not caught. the finally block is executed before the exception is propagated. The program will print Hello world. B.

} and given that EOFException and FileNotFoundException are both subclasses ofIOException. TestException is a subclass of Exception therefore the test method. System.out. Option A is wrong. } catch(FileNotFoundException e) { System. must throw TestException or some other class further up the Exception tree. try { System.out.print("End of file exception"). Option D is wrong. The compiler complains with the same error as in A above. throws Exception catch ( Exception e ) throws RuntimeException Answer & Explanation Answer: Option B Explanation: Option B is correct. which statement is most true concerning this code? .RuntimeException branch (it is not a superclass ofTestException). /* Line 7 */ catch(EOFException e) { System.out.A.print("Hello world"). This works because it DOES throw an exception if an error occurs. The catch statement belongs in a method body not a method specification.out. Throwing RuntimeException is just not on as this belongs in the java. and further assuming this block of code is placed into a class. in this example. B.print("File not found").print(" Catch Here "). C.print("Start "). No code is necessary. } System. View Answer Workspace Report Discuss in Forum 4. D. If you compile the code as given the compiler will complain: "unreported exception must be caught or declared to be thrown" The class extends Exception so we are forced to test for exceptions.out. Option C is wrong.lang. throw new FileNotFoundException().

Code output: Start Hello world End of file exception. View Answer Workspace Report Discuss in Forum 5. Code output: Start Hello world Catch Here File not found. Option B is wrong. The only legal statements after try blocks are either catch or finally statements. Answer & Explanation Answer: Option A Explanation: Line 7 will cause a compiler error. B. The error class is a subclass of Throwable and not RuntimeException. Any statement that can throw an Error must be enclosed in a try block. C. You do not catch this class of error. and D are incorrect based on the program logic described above. The Error class is a RuntimeException. C. If line 7 was removed.A. . the code would compile and the correct answer would be Option B. B. C. catch(X x) can catch subclasses of X where X is a subclass of Exception. Option D is wrong. Code output: Start Hello world File Not Found. Any statement that can throw an Exception must be enclosed in a try block. If the class specified in the catch clause does have subclasses. Answer & Explanation Answer: Option A Explanation: Option A is correct. Which statement is true? A. D. Option C is wrong. Option B. The code will not compile. D. any exception object that subclasses the specified class will be caught as well. An exception can be thrown to the next method higher up the call stack.

3. (5) and (6) are the only four that can be thrown. An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. 4. D. 5. 1. C. 2. a corresponding finally block will always start to execute. Multiple catch statements can catch the same class of exception more than once. 3. 4. Except in case of VM shutdown. 2. 4 and 5 2. 4. D.View Answer Workspace Report Discuss in Forum 6. if a try block starts to execute. (4). The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch (checked exceptions) RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. or be handled within that method. An Error that might be thrown in a method must be declared as thrown by that method. View Answer Workspace Report Discuss in Forum 7. 2. . Error Event Object Throwable Exception RuntimeException A. The Throwable class is the superclass of all errors and exceptions in the Java language. 5 and 6 B. C. 5 and 6 Answer & Explanation Answer: Option C Explanation: The (1). A try statement must have at least one corresponding catch block. 6. Which four can be thrown using the throw statement? 1. 3 and 4 1. Which statement is true? A. B.

the code in that finally block will definitely be executed except in the following circumstances: 1. but it must have a finallystatement.Exception) have to be caught. They can be passed to another method. An exception arising in the finally block itself. then once execution enters the try block. Exceptions of type Error and RuntimeException do not have to be caught. A try statement can exist without catch. only checked exceptions (java. then control will be transferred to the first such catch clause. 2. However. I suppose the last three could be classified as VM shutdown.exit() 4. 3. If you put a finally block after a try and its associated catch blocks. If a value is thrown and the try statement has one or more catch clauses that can catch it.lang. The death of the thread. If that catch block completes normally. Turning off the power to the CPU. then the try statement completes normally.Answer & Explanation Answer: Option D Explanation: A is wrong. Exceptions do not have to be handled in the same method as the throw statement. speaking of Exceptions. C is wrong. B is wrong. View Answer Workspace Report Discuss in Forum . A try statement executes a block. The use of System.

1.

Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance? A. B. C. D. TreeMap HashMap LinkedHashMap The answer depends on the implementation of the existing instance.

Answer & Explanation

Answer: Option C Explanation: The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted. When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked. The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the newLinkedHashMap. Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection. View Answer Workspace Report Discuss in Forum 2. Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object? A. C. java.lang.String java.lang.StringBuffer B. D. java.lang.Double java.lang.Character

Answer & Explanation

Answer: Option C

Explanation:

java.lang.StringBuffer is the only class in the list that uses the default methods provided by class Object.
View Answer Workspace Report Discuss in Forum 3.

Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? A. C. java.util.HashSet java.util.List B. D. java.util.LinkedHashSet java.util.ArrayList

Answer & Explanation

Answer: Option D Explanation: All of the collection classes allow you to grow or shrink the size of your collection.ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayListfunctionality and has synchronized methods; it is slower than ArrayList. View Answer Workspace Report Discuss in Forum 4.

You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability? A. C. java.util.Map java.util.List B. D. java.util.Set java.util.Collection

Answer & Explanation

Answer: Option B Explanation: Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements. Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of keyvalue mappings. The order of a map is defined as the order in which the iterators on the map's

collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time). Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. Option D is wrong. A collection is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. View Answer Workspace Report Discuss in Forum 5. Which interface does java.util.HashTable implement? A. C. Java.util.Map Java.util.HashTable B. D. Java.util.List Java.util.Collection

Answer & Explanation

Answer: Option A Explanation: Hash table based implementation of the Map interface. View Answer Workspace Report Discuss in Forum 6. Which interface provides the capability to store objects using a key-value pair? A. C. Java.util.Map Java.util.List B. D. Java.util.Set Java.util.Collection

Answer & Explanation

Answer: Option A Explanation: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. View Answer Workspace Report Discuss in Forum 7.

Which collection class allows you to associate its elements with key values, and allows you to

If you need synchronization great. B.TreeMap Answer & Explanation Answer: Option B Explanation: LinkedHashMap is the collection class used for caching purposes.0.SortedMap java. Answer & Explanation Answer: Option A Explanation: . D. To retrieve LinkedHashMap elements in cached order. and provides synchronization? A. View Answer Workspace Report Discuss in Forum 8. java. otherwise. first-out) sequence? A. Which is valid declaration of a float? A. FIFO is another way to indicate caching behavior.util. D.ArrayList java.util. View Answer Workspace Report Discuss in Forum 9.HashMap B.Hashtable Answer & Explanation Answer: Option D Explanation: Hashtable is the only class listed that provides synchronized methods.LinkedHashMap java.TreeMap java.util. float f = 1F. it's faster.util. java. C. Which collection class allows you to access its elements by associating a key with an element's value. float f = "1". D.retrieve objects in FIFO (first-in. java. C.util.0d. java. float f = 1.util. float f = 1.util.util. C. use the values() method and iterate over the resultant collection.TreeSet B. use HashMap.

Option D is incorrect because "d" tells the computer it is a double so therefore you are trying to put a double value into a float variable i. include java. 0 to 32767 B. C.io.e there might be a loss of precision. import java. B.io.true).PrintWriter(). View Answer Workspace Report Discuss in Forum 10.println("Hello"). /* Missing Statement ? */ public class foo { public static void main(String[]args)throws Exception { java.io.Option A is valid declaration of float. out. No statement required.io.io" then the class name in the long run leading to a lot more typing. View Answer Workspace Report Discuss in Forum 11. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java. D.io.OutputStreamWriter(System.PrintWriter.PrintWriter out = new java. } } What line of code should replace the missing statement to make this program compile? A. Option B is incorrect because any literal number with a decimal point u declare the computer will implicitly cast to double unless you include "F or f" Option C is incorrect because it is a String. What is the numerical range of char? A.io. import java.out.*. 0 to 65535 . However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above.*. new java. Answer & Explanation Answer: Option A Explanation: The usual method for using/importing the java packages/classes is by using an import statement at the top of your code.

The range of a variable of type char is from 0 to 2161 or 0 to 65535. 4. 3. Java characters are Unicode. -256 to 255 D.C. View Answer Workspace Report Discuss in Forum 12. then the encoding is the same as seven-bit ASCII.This is a Java keyword (1) .Is incorrect because although it is a method of Thread/Runnable it is not a keyword (4) . 2 and 3 2 and 4 Answer & Explanation Answer: Option B Explanation: (2) .This is not a Java keyword the keyword is implements View Answer Workspace Report Discuss in Forum 1. If the most significant nine bits of a char are 0. What will be the output of the program? public class Test { public static void main (String[] args) { String foo = args[1]. C. run import default implement A. -32768 to 32767 Answer & Explanation Answer: Option B Explanation: The char type is integral but unsigned. Which of the following are Java reserved words? 1. D. .This is a Java keyword (3) . which is a 16-bit encoding capable of representing a wide range of international characters. 2. 1 and 2 3 and 4 B.

String bar = args[2]. B.out. View Answer Workspace Report Discuss in Forum 2. /* Line 8 */ } } And the command line invocation: > java Test red green blue A. } } A. String baz = args[3]. "green" and "blue".println("baz = " + baz). System. args[1] becomes "green" and args[2]becomes "blue". What will be the output of the program? public class Test { public static void main (String args[]) { String str = NULL. C. C. NULL Compile Error Code runs but no output . When dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes "red". baz = null Runtime Exception Answer & Explanation Answer: Option D Explanation: When running the program you entered 3 arguments "red". D.out. System. When the program entcounters line 8 above at runtime it looks for args[3] which has never been created therefore you get an ArrayIndexOutOfBoundsException at runtime.println(str). baz = baz = blue B.

util.Vector. } } public class MyNewVector extends MyVector { public MyNewVector () { i = 4. /* Line 5 */ public MyVector() { i = 2. Compilation will fail at line 5. /* Line 19 */ } } A. Compilation will fail at line 15. What will be the output of the program? package foo. View Answer Workspace Report Discuss in Forum 3. Answer & Explanation Answer: Option B Explanation: . /* Line 15 */ } public static void main (String args []) { MyVector v = new MyNewVector(). Runtime Exception Answer & Explanation Answer: Option B Explanation: Option B is correct because to set the value of a String variable to null you must use "null" and not "NULL". D. /* Line 2 */ private class MyVector extends Vector { int i = 1. Compilation will fail at line 3. import java. Compilation will succeed. C.D. B.

} } A. View Answer Workspace Report Discuss in Forum 5.out. The class is created private and is being used by another class on line 19.e. so since the above code contains no new or size decalarations when you try and access x[0] you are trying to access a member of an array that has been declared but not intialized hence you get a NullPointerException at runtime. 0 null Compile Error NullPointerException at runtime Answer & Explanation Answer: Option D Explanation: In the above code the array reference variable x has been declared but it has not been instantiated i.e. public static void main(String[] args) { System. D. private static int[x] declares a static i. The compiler complains with the error "modifier private not allowed here". B.println(x[0]). class level array. C. int[5] in association with the new sets the size of the array.Option B is correct. What will be the output of the program? public class Test { private static int[] x. View Answer Workspace Report Discuss in Forum 4. the "new" keyword is the word that actually creates said array. What will be the output of the program? . for example: private static int[]x = new int[5]. the new statement is missing.

Prints: false.print(i instanceof ListIterator).0 Runtime Exception Answer & Explanation ."). What will be the output of the program? public class Test { private static float[] f = new float[2]. } } A.print((i instanceof Iterator)+". f[0] = 0.*. } } A. B.out. true. f[0] = 0 Compile Error B."). C.println("f[0] = " + f[0]). true Prints: false. A ListIterator can be obtained by invoking the listIterator method. true. View Answer Workspace Report Discuss in Forum 6. false Prints: false. public static void main (String[] args) { System. System.out. C. it doesn't return a List or a ListIterator object. class I { public static void main (String[] args) { Object i = new ArrayList(). false. false.out.out.util. System.import java. System. D.print((i instanceof List)+". false Prints: false. true Answer & Explanation Answer: Option C Explanation: The iterator() method returns an iterator over the elements in the list in proper sequence. D.iterator().

").e.").false. System.util.*.false Prints: true.out. it is a type that uses decimal point numbers therefore its initial value will be 0.0 and not 0 View Answer Workspace Report Discuss in Forum 7. System.elements().out.true Prints: false.Answer: Option B Explanation: The choices are between Option A and B. } } A.true.print((x instanceof Iterator)+".out. D. . What will be the output of the program? TreeSet map = new TreeSet().print(x instanceof ListIterator).false Prints: false. C. what this question is really testing is your knowledge of default values of an initialized array. System. View Answer Workspace Report Discuss in Forum 8.print((x instanceof Enumeration)+". Prints: false. B.elements method returns an Enumeration over the elements of the vector.false. class H { public static void main (String[] args) { Object x = new Vector(). What will be the output of the program? import java. This is an array type float i.false. Vector implements the List interface and extends AbstractList so it is also possible to get an Iterator over a Vector by invoking the iterator orlistIterator method.false Answer & Explanation Answer: Option D Explanation: The Vector.

add("three").hashCode()). } A.println(obj. D. C. } A.add("one"). also. C. B. map. one two three four four three two one four one three two one two three four one Answer & Explanation Answer: Option C Explanation: TreeSet assures no duplicate entries.add("two"). map. B. System.iterator(). View Answer Workspace Report Discuss in Forum 9. map. map. while (it.out. 42 Runtime Exception Compile Error at line 2 . which typically means alphabetical.next() + " " ). Iterator it = map.print( it.add("one").out. when it is accessed it will return elements in natural order. What will be the output of the program? public static void main(String[] args) { Object obj = new Object() { public int hashCode() { return 42.add("four").map. } }.hasNext() ) { System.

It can extend exactly one class and can implement multiple interfaces. After this class has been declared its methods can be used by that object in the usual way e. It can extend exactly one class or implement exactly one interface. C. It can extend exactly one class and implement exactly one interface. Compile Error at line 5 Answer & Explanation Answer: Option A Explanation: This code is an example of an anonymous inner class.annoymousClassMethod() View Answer Workspace Report Discuss in Forum 1. Within the {} you place the methods you want for that class.g. Which is true about an anonymous inner class? A. In this case the annoynous class is extending the Object class. It can implement multiple interfaces regardless of whether it also extends a class.D.objectname. D. Since they have no name you can not use the "new" keyword on them. B. Answer & Explanation Answer: Option C . They can be declared to extend another class or implement a single interface.

D. Bar f = new Boo(String s) { }. it all works. class Boo { Boo(String s) { } Boo() { } } class Bar extends Boo { Bar() { } Bar(String s) {super(s). which in this case is an anonymous subclass of Bar. Option A is incorrect because it passes an int to the Boo constructor. Answer & Explanation Answer: Option B Explanation: Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. B.Bar(String s) { }. Boo f = new Boo. B.Explanation: Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new. View Answer Workspace Report Discuss in Forum 2. and there is no matching constructor in the Boo class. Boo f = new Boo(24) { }. and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type. Boo f = new Bar() { }. . Since Bar is a subclass of Boo. C. Option A. D.} void zoo() { // insert code here } } which one create an anonymous inner class from within class Bar? A. and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous class extends that one class).

It can be marked static. View Answer Workspace Report Discuss in Forum 4. You must have a reference to an instance of the enclosing class in order to instantiate it. It must be marked final. D. although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful). D. It must extend the enclosing class.Option C is incorrect because it violates the rules of polymorphism—you cannot refer to a superclass type using a reference variable declared as the subclass type. C. It can be marked abstract. Answer & Explanation . The superclass is not guaranteed to have everything the subclass has. It does not have access to nonstatic members of the enclosing class. Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so). C and D are incorrect because a method-local inner class cannot be made public(remember-you cannot mark any local variables as public). Which is true about a method-local inner class? A. C. View Answer Workspace Report Discuss in Forum 3. Answer & Explanation Answer: Option B Explanation: Option B is correct because a method-local inner class can be abstract. B. or static. It can be marked public. It's variables and methods must be static. Which statement is true about a static nested class? A. B. Option D uses incorrect syntax.

It defines an anonymous inner class instance. Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class. C. and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class). View Answer Workspace Report Discuss in Forum 5. There's no rule that says an inner or nested class has to extend anything. Which constructs an anonymous inner class instance? A.out. Option D is wrong because it just is. Option C is incorrect because static nested classes can declare and define nonstatic members. Runnable r = new Runnable { public void run(){}}. System. D.Answer: Option B Explanation: Option B is correct because a static nested class is not tied to an instance of the enclosing class. so it must override the run()method of Runnable. so it violates the rules of interface implementation. B and C use incorrect syntax.println(new Runnable() {public void run() { }}). class Foo { class Bar{ } . which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface. View Answer Workspace Report Discuss in Forum 6. Runnable r = new Runnable() { }. B. Runnable r = new Runnable(public void run() { }). Answer & Explanation Answer: Option D Explanation: D is correct. A is incorrect because it doesn't override the run() method.

Foo. and because the new syntax is wrong.Bar().Bar().Bar b = f. C and D all use incorrect syntax. Bar b = f.new Bar(). then using a reference to the enclosing class to invoke new on the inner class. C. instantiates an instance of the nested class? . /* Line 10: Missing statement ? */ } } which statement. Answer & Explanation Answer: Option B Explanation: Option B is correct because the syntax is correct-using both names (the enclosing class and the inner class) in the reference declaration.} class Test { public static void main (String [] args) { Foo f = new Foo(). C is incorrect because it doesn't use the enclosing class name in the reference variable declaration. D. View Answer Workspace Report Discuss in Forum 7. and also because it includes both names in the new.new Bar(). Foo. creates an instance of Bar? A.Bar b = new Foo. Bar b = new f. D is incorrect because it doesn't use the enclosing class name in the reference variable declaration. if placed in a class other than MyOuter or MyInner. A is incorrect because it doesn't use a reference to the enclosing class. Option A. inserted at line 10. public class MyOuter { public static class MyInner { public static void foo() { } } } which statement. B.

D.MyInner(). View Answer Workspace Report Discuss in Forum 1. B. you do not use the enclosing name.MyInner mi = m.print("hi"). } class Bar { Bar() { System.out.out.out. Option D is incorrect because it doesn't use the enclosing class name in the variable declaration. Option B is incorrect because it doesn't use the enclosing name in the new. } public void go() { System. so it must be instantiated using the fully-scoped name of MyOuter.MyInner(). What will be the output of the program? public class Foo { Foo() { System. The difference between Option A and C is that Option C is calling new on an instance of the enclosing class rather than just new by itself.print("foo").new MyOuter. Option C is incorrect because it uses incorrect syntax. MyOuter m = new MyOuter().MyInner(). MyInner mi = new MyOuter. Answer & Explanation Answer: Option A Explanation: MyInner is a static nested class. MyOuter. MyOuter. MyOuter. When you instantiate a nested class by invoking new on an instance of the enclosing class.print("bar").A. C.MyInner mi = new MyInner(). } } /* class Bar ends */ public static void main (String [] args) { .MyInner m = new MyOuter.MyInner.

which means the go()method prints "hi". View Answer Workspace Report Discuss in Forum 2. /* Line 7 */ public Horse(String s) { name = s.name). Compilation fails. D. It prints "foobarhi" It prints "barhi" Answer & Explanation Answer: Option C Explanation: Option C is correct because first the Foo instance is created. the makeBar() method is invoked which creates a Bar.Foo f = new Foo(). /* Line 14 */ System. which means the Fooconstructor runs and prints "foo". } } /* class HorseTest ends */ A. } } /* class Horse ends */ Object obj = new Horse("Zippo"). and finally the go() method is invoked on the new Bar instance.go(). } void makeBar() { (new Bar() {}). Next.println(h. f. An exception occurs at runtime at line 10. C. } }/* class Foo ends */ A. What will be the output of the program? public class HorseTest { public static void main (String [] args) { class Horse { public String name. which means the Bar constructor runs and prints "bar".out. An error occurs at runtime. /* Line 13 */ Horse h = (Horse) obj. B.makeBar(). .

An exception occurs at runtime. because class Object does not have a name variable. D. C. Compilation fails Answer & Explanation . Answer & Explanation Answer: Option B Explanation: The code in the HorseTest class is perfectly legal. Line 14 casts the Horse object to a Horse reference variable. Compilation fails because of an error on line 7.println(o. Line 13 creates an instance of the methodlocal inner class Horse. It prints "Zippo". which allows line 15 to compile. It prints "true". What will be the output of the program? public class TestObj { public static void main (String [] args) { Object o = new Object() /* Line 5 */ { public boolean equals(Object obj) { return true. using a reference variable declared as type Object. } } A. It prints "Fred".equals("Fred")). the HorseTest code would not compile. View Answer Workspace Report Discuss in Forum 3. If line 14 were removed. D. C. } } /* Line 11 */ System. Compilation fails because of an error on line 13. B.B.out.

println(f. } } A. B. AbstractTest. } }.getNum()). What will be the output of the program? public abstract class AbstractTest { public int getNum() { return 45. D. } } public static void main (String [] args) { AbstractTest t = new AbstractTest() { public int getNum() { return 22.out. } public abstract class Bar { public int getNum() { return 38.new Bar() { public int getNum() { return 57. and a statement needs a closing semicolon! View Answer Workspace Report Discuss in Forum 4. 57 22 45 38 45 57 An exception occurs at runtime. Remember that line 5 is a statement that doesn't end until line 11.Bar f = t. System. C. .getNum() + " " + t. } }.Answer: Option D Explanation: This code would be legal if line 11 ended with a semicolon.

What is the name of the method used to start a thread execution? A. There is no init() method in the Thread class. Remember that to instantiate a Bar instance. The start() method causes this thread to begin execution. and the anonymous class overrides the getNum() method to return 22. C. start(). and the anonymous Bar subclass also overrides the getNum() method (to return 57). The variable referenced by f is an instance of an anonymous subclass of Bar. View Answer Workspace Report Discuss in Forum 1.Answer & Explanation Answer: Option A Explanation: You can define an inner class as abstract. which means you can instantiate only concrete subclasses of the abstract inner class. B. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest. the Java Virtual Machine calls the run method of this thread. run(). Answer & Explanation Answer: Option B Explanation: Option B is Correct. resume(). so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance. D. we need an instance of the enclosingAbstractTest class to tie to the new Bar inner class instance. Option A is wrong. AbstractTestcan't be instantiated because it's abstract. init(). .

3. int priority) A. 1 and 3 1 and 2 B. Which three are methods of the Object class? 1. 7. 2 and 4 2 and 5 Answer & Explanation Answer: Option C Explanation: (1) and (2) are both valid constructors for Thread. and (5) are not legal Thread constructors. isInterrupted(). ThreadGroup g) Thread(Runnable r. 1. 2. (3). If you reverse the arguments in (4). It resumes a suspended thread. View Answer Workspace Report Discuss in Forum 2. 5 . Thread(Runnable r. Which two are valid constructors for Thread? 1.Option C is wrong. 4 B. 4. sleep(long msecs). 2. D. Option D is wrong. 2. notifyAll(). (4). 5. yield(). The resume() method is deprecated. synchronized(). String name) Thread() Thread(int priority) Thread(Runnable r. View Answer Workspace Report Discuss in Forum 3. Starting the thread causes the object's run method to be called in that separately executing thread. The run() method of a thread is like the main() method to an application. C. 6. notify(). 8. 5. 4. wait(long msecs). although (4) is close. 3. A. interrupt(). 2. 4. you'd have a valid constructor.

The methods sleep() and yield() are static methods of Thread. View Answer Workspace Report Discuss in Forum . Answer & Explanation Answer: Option C Explanation: Option C is suitable to start a thread.start(). (5). C. Thread t = new Thread(X). D is incorrect because synchronized is a keyword and the synchronized()construct is part of the Java language. 4 Answer & Explanation Answer: Option C Explanation: (1). 2. View Answer Workspace Report Discuss in Forum 4.start(). 6 D. t. (7). x. (3). t. B. 2.C. Thread t = new Thread(X).run(). (2). The methods isInterrupted() andinterrupt() are instance methods of Thread. They are all related to the list of threads waiting on the specified object. Thread t = new Thread(). Thread t = new Thread(run). class X implements Runnable { public static void main(String args[]) { /* Missing code? */ } public void run() {} } Which of the following line of code is suitable to start a thread ? A. and (6) are correct. and (8) are incorrect answers. D. X run = new X(). 1. 3.

Calling read() method on an InputStream object. 2. (2) and (3) are incorrect because they are methods of the Object class. C. 5. 2 and 3 2 and 4 Answer & Explanation Answer: Option A Explanation: (1) and (4). Which two of the following methods are defined in class Thread? 1. Only start() and run() are defined by the Thread class. Answer & Explanation Answer: Option C Explanation: Option C is correct. View Answer Workspace Report Discuss in Forum 7. 1 and 4 3 and 4 B. Which cannot directly cause a thread to stop executing? A.5. D. D. C. 3. (5) is incorrect because there's no such method in any thread-related class. B. start() wait() notify() run() terminate() A.wakes up a single thread that is waiting on this object's monitor. Calling notify() method on an object. Calling the wait() method on an object. Which three guarantee that a thread will leave the running state? . notify() . View Answer Workspace Report Discuss in Forum 6. 4. Calling the SetPriority() method on a Thread object.

5. assuming that the thread you're calling join() on is alive. notify() exits synchronized code Answer & Explanation Answer: Option A . 2. then the current thread will probably leave the running state. D. (6) is correct because. C. 6. (3) and (4) are incorrect because they don't cause the thread invoking them to leave the running state. 3. (5) is correct because sleep() will always pause the currently running thread for at least the duration specified in the sleep argument (unless an interrupted exception is thrown). 4. (1) is wrong. View Answer Workspace Report Discuss in Forum 8. Which of the following will directly stop the execution of a Thread? A. 1. wait() notifyall() B.1.join() Thread. 2 and 4 3. 5 and 7 Answer & Explanation Answer: Option B Explanation: (2) is correct because wait() always causes the current thread to go into the object's wait pool. C. 2. the thread calling join() will immediately block until the thread you're callingjoin() on is no longer alive. D. although if there are runnable threads of the same priority as the currently running thread. 7. The yield() method is not guaranteed to cause a thread to leave the running state. 5 and 6 4. but tempting. (7) is wrong because there's no such method. yield() wait() notify() notifyAll() sleep(1000) aLiveThread. 4 and 7 B.killThread() A.

Typically. C. At that point. View Answer Workspace Report Discuss in Forum 9. Answer & Explanation . the lock is free until some other thread enters a synchronized method on that object. I think the word directly in the question gives us a clue. void run() public void start() B.Explanation: Option A is correct. Option B is wrong. View Answer Workspace Report Discuss in Forum 10. the thread currently in the synchronized method) exits the synchronized method. start(). the void run() method therefore it must be implemented. The Runnableinterface only contains 1 method. package(default) access is narrower than public access. Option A and D are incorrect because they are narrowing the access privileges i.e. D.lang. releasing a lock means the thread holding the lock (in other words. notify() . wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. run(). Which method must be defined by a class implementing the java. Which will contain the body of the thread? A. public void run() void run(int priority) Answer & Explanation Answer: Option B Explanation: Option B is correct because in an interface all methods are abstract by default therefore they must be overridden by the implementing class.Runnableinterface? A. D. B.wakes up a single thread that is waiting on this object's monitor. Option C is not method in the Runnable interface therefore it is incorrect. Exiting synchronized code does not directly stop the execution of a thread. Option D is wrong. notifyAll() . Option C is wrong. main(). C. stop(). Does entering/exiting synchronized code mean that the thread execution stops? Not necessarily because the thread can still run code that is not synchronized.wakes up all threads that are waiting on this object's monitor.

The run() method to a thread is like the main() method to an application. construct(). View Answer Workspace Report Discuss in Forum 12. register(). There is no register() method in the Thread class. View Answer Workspace Report Discuss in Forum 11. Which method registers a thread in a thread scheduler? A. Answer & Explanation Answer: Option C Explanation: Option C is correct. D. Option B is wrong.Answer: Option A Explanation: Option A is Correct. Starting the thread causes the object's run method to be called in that separately executing thread. the Java Virtual Machine calls the run method of this thread. Option D is wrong. Is the main entry point for an application. Assume the following method is properly synchronized and called from a thread A on an object B: wait(2000). when will the thread A become a candidate to get another turn at the CPU? . The start() method causes this thread to begin execution. start(). There is no construct() method in the Thread class. The stop() method is deprecated. C. the Java Virtual Machine calls the run method of this thread. The start() method causes this thread to begin execution. Option A is wrong. After calling this method. Starting the thread causes the object's run method to be called in that separately executing thread. The run() method of a thread is like the main() method to an application. It forces the thread to stop executing. B. run(). Option D is wrong. Option B is wrong. Option C is wrong.

D. notify() . Option D is wrong. C. Thread Class Answer & Explanation Answer: Option A . wait() sleep() Answer & Explanation Answer: Option A Explanation: Option A is correct. The thread does not lose ownership of any monitors. C. D. Which of the following will not directly cause a thread to stop? A. notify() InputStream access B. sleep() .and notifyAll() methods? A. B. After the lock on B is released. After thread A is notified. the end of the stream is detected. Which class or interface defines the wait(). or after two seconds. Option B is wrong.A. View Answer Workspace Report Discuss in Forum 14. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. Object Runnable B. D. Two seconds after thread A is notified.wakes up a single thread that is waiting on this object's monitor. or an exception is thrown. Option C is wrong. Blocking means that a thread may stop until certain conditions are met. View Answer Workspace Report Discuss in Forum 13. notify().Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. Two seconds after lock B is released. or after two seconds. Methods of the InputStream class block until input data is available. C.

new MyRunnable(). A is incorrect. and D are incorrect because they do not define these methods. new Thread(new MyRunnable()). B is incorrect for the same reason. D is incorrect because MyRunnable doesn't have a start() method. Answer & Explanation Answer: Option C Explanation: Because the class implements Runnable. and then the instance of the Thread has to be started. C. an instance of it has to be passed to theThread constructor.Explanation: The Object class defines these thread-specific methods.start(). Option B. the Java API does define a class called Class.run(). D.start(). new Thread(MyRunnable). though you do not need to know it for the exam. There is no constructor like this for Runnable because Runnable is an interface. And yes.start(). View Answer Workspace Report Discuss in Forum 1. B. C. and the onlystart() method that can start a thread of execution is the start() in the Threadclass. new Runnable(MyRunnable). and it is illegal to pass a class or interface name to any constructor. View Answer Workspace Report Discuss in Forum 15. What will be the output of the program? class MyThread extends Thread { . you can't pass a class or interface name to any constructor. public class MyRunnable implements Runnable { public void run() { // some code here } } which of these will create and start this thread? A.

out. } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System. } }. System. So the MyThread constructor runs and prints "MyThread".MyThread() { System. t. } } A. MyThread foo foo bar Answer & Explanation Answer: Option B Explanation: Option B is correct because in the first line of main we're constructing an instance of an anonymous inner class extending from MyThread. t. which causes the overridden run() method (the run()method defined in the anonymous inner class) to be invoked.out.start().start().println(" foo").out. D. "). What will be the output of the program? class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread(). } public void run(String s) { System.println(" baz").out. . } public void run() { System.out.print("one. The next statement in main invokes start() on the new thread instance. which prints "foo" View Answer Workspace Report Discuss in Forum 2.print(" MyThread").print(" bar"). C. foo MyThread bar B.

out. View Answer Workspace Report Discuss in Forum 3. B.print("Inside Thread "). Answer & Explanation Answer: Option B Explanation: When the start() method is attempted a second time on a single Thread object.t.out. Even if the thread has finished running.start(). ").out. What will be the output of the program? class MyThread extends Thread { MyThread() {} MyThread(Runnable r) {super(r). C. Thread two. } } class MyRunnable implements Runnable { public void run() { System.start(). new MyThread(new MyRunnable()). } public void run() { System. Compilation fails An exception occurs at runtime. D. } } A.print("two.out. System. } . the method will throw an IllegalThreadStateException (you will not need to know this exception name for the exam)." The output cannot be determined. it is still illegal to call start() again.start(). } public void run() { System. } } class Test { public static void main(String[] args) { new MyThread().print("Thread ").print(" Inside Runnable"). It prints "Thread one.

int addX() {x++. Both times. s1 run2 = new s1(). then the run method of the Thread class will invoke the run method of the Runnable object. C. Prints "Inside Thread Inside Thread" Prints "Inside Thread Inside Runnable" Does not compile Throws exception at runtime Answer & Explanation Answer: Option A Explanation: If a Runnable object is passed to the Thread constructor. the run() method in MyThread is invoked instead. y = 0.out.} A. } public static void main(String args[]) { s1 run1 = new s1().start(). What will be the output of the program? class s1 implements Runnable { int x = 0. t2. View Answer Workspace Report Discuss in Forum 4. return y.start(). i < 10. the run method in the Thread class is overridden by the run method in MyThread class. t1. return x. D.println(addX() + " " + addY()). Compile time Error: There is no start() method . B. Thread t1 = new Thread(run1). Thread t2 = new Thread(run2). } } A. i++) System. Therefore the run() method in MyRunnable is never invoked. however.} int addY() {y++. In this case.} public void run() { for(int i = 0.

println("x = " + x + "y } } } A. If you modify the code of the run() method to print the thread name it will help to clarify the output: public void run() { for(int i = 0... /* Line 9 } public synchronized void run( ) /* Line 11 { for (... System..) /* Line 13 */ { x++.out. public static void main(String [] args) { Q126 that = new Q126().getName() + ": " + addX() + " " + addY() ).g: 1 1 2 2 1 1 3 3.println( Thread. . (new Thread(that)). C. i++) System. Will print in this order: 1 1 2 2 3 3 4 4 5 5. y++. private int y.) Will print in this order: 1 2 3 4 5 6.start( ).. What will be the output of the program? public class Q126 implements Runnable { private int x.start( ). D... } View Answer Workspace Report Discuss in Forum 5. An error at line 11 causes compilation to fail */ */ */ = " + y).currentThread(). Answer & Explanation Answer: Option C Explanation: Both threads are operating on different sets of instance variables. i < 10. 1 2 3 4 5 6.. Will print but not exactly in an order (e.B.out. /* Line 8 (new Thread(that)).

The program prints pairs of values for x and y that might not always be the same on the same line (for example. } } .out. i++) { System. i < 3.start(). System. Test120 t2 = new Test120(). y=2") C.println("C"). y=1". Also note that because of the infinite loop at line 13. View Answer Workspace Report Discuss in Forum 6.out. System. } } } class Test120 extends Thread { public void run() { for(int i = 0. t1.println("A"). t2. Errors at lines 8 and 9 cause compilation to fail. Also keep in mind that the two threads share the same reference to theQ126 object.out. "x=1. Answer & Explanation Answer: Option D Explanation: The synchronized code is the key to answering this question. "x=1. i++) { System. i < 3.out. only one thread ever gets to execute.B. D.start(). What will be the output of the program? class s1 extends Thread { public void run() { for(int i = 0. In addition.println("D"). each value appears once (for example. "x=2. y=1" followed by "x=2. } } public static void main(String args[]) { s1 t1 = new s1(). y=1") The program prints pairs of values for x and y that are always the same on the same line (for example. Because x and y are both incremented inside the synchronized method they are always incremented together.println("B").

start().. D. i < 1000.out. Answer & Explanation Answer: Option C Explanation: We cannot predict the order in which threads are going to run. } System. i++) synchronized(this) { x = 12. What will be the output of the program? class s implements Runnable { int x. B. Thread t1 = new Thread(run). Compile time Error There is no start() method Will print in this order AB CD AB.ABCD. } } A... DeadLock Compilation Error B.print(x + " " + y + " "). y. t1.. It print 12 12 12 12 Cannot determine output. t2. } public static void main(String args[]) { s run = new s(). C.start(). D. View Answer Workspace Report Discuss in Forum 7.. Thread t2 = new Thread(run).. y = 12. Will print but not be able to predict the Order Will print in this order ABCD.A. C. public void run() { for(int i = 0. Answer & Explanation Answer: Option B .

Thread a1 = new A(demo). i < 10. C. a1. Thread a2 = new A(demo).println(count++). } } A. } public static void main(String[] args) { ThreadDemo demo = new ThreadDemo(). a2. public A(ThreadDemo td) { demo = td.Explanation: The program will execute without any problems and print 12 12 12 12. but the order cannot be determined The code will not compile.start(). Answer & Explanation Answer: Option B Explanation: . D. } public void run() { demo.doSomething(). i++) System. } } class A extends Thread { ThreadDemo demo. B. View Answer Workspace Report Discuss in Forum 8.out. It will print the numbers 0 to 19 sequentially It will print the numbers 1 to 20 sequentially It will print the numbers 1 to 20.start(). public synchronized void doSomething() { for (int i = 0. What will be the output of the program? public class ThreadDemo { private int count = 1.

You have two different threads that share one reference to a common object. The updating and output takes place inside synchronized code. One thread will run to completion printing the numbers 1-10. The second thread will then run to completion printing the numbers 11-20. View Answer Workspace Report Discuss in Forum 9.

What will be the output of the program?

public class WaitTest { public static void main(String [] args) { System.out.print("1 "); synchronized(args) { System.out.print("2 "); try { args.wait(); /* Line 11 */ } catch(InterruptedException e){ } } System.out.print("3 "); } } It fails to compile because the IllegalMonitorStateException of wait()is not dealt with in line 11. 123 13 12

A.

B. C. D.

Answer & Explanation

Answer: Option D Explanation: 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. The program is essentially frozen at line 11. A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have

to be dealt with explicitly. B and C are incorrect; 3 will never be printed, since this program will never terminate because it will wait forever. View Answer Workspace Report Discuss in Forum 10. What will be the output of the program?

public class SyncTest { public static void main (String [] args) { Thread t = new Thread() { Foo f = new Foo(); public void run() { f.increase(20); } }; t.start(); } } class Foo { private int data = 23; public void increase(int amt) { int x = data; data = x + amt; } } and assuming that data must be protected from corruption, what—if anything—can you add to the preceding code to ensure the integrity of data? A. B. C. D. Synchronize the run method. Wrap a synchronize(this) around the call to f.increase(). The existing code will cause a runtime exception. Synchronize the increase() method

Answer & Explanation

Answer: Option D Explanation: Option D is correct because synchronizing the code that actually does the increase will protect the

code from being accessed by more than one thread at a time. Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method. Option B is incorrect for virtually the same reason as A—synchronizing the code that calls the increase() method does not prevent other code from calling theincrease() method. View Answer Workspace Report Discuss in Forum 11. What will be the output of the program?

class Happy extends Thread { final StringBuffer sb1 = new StringBuffer(); final StringBuffer sb2 = new StringBuffer(); public static void main(String args[]) { final Happy h = new Happy(); new Thread() { public void run() { synchronized(this) { h.sb1.append("A"); h.sb2.append("B"); System.out.println(h.sb1); System.out.println(h.sb2); } } }.start(); new Thread() { public void run() { synchronized(this) { h.sb1.append("D"); h.sb2.append("C"); System.out.println(h.sb2); System.out.println(h.sb1); } } }.start(); } } A. B. ABBCAD ABCBCAD

D. i++) { System. Each String in the array lines will output. Answer & Explanation Answer: Option D Explanation: Can you guarantee the order in which threads are going to run? No you can't. This code will not compile. with no pause in between because this method is not executed in a Thread. B. Thread.currentThread().println(lines[i]).sleep(1000). View Answer Workspace Report Discuss in Forum 12. Each String in the array lines will output. Answer & Explanation Answer: Option D Explanation: .out. So how do you know what the output will be? The output cannot be determined. Each String in the array lines will output.length. CDADACB Output determined by the underlying platform. D. C. class Test { public static void main(String [] args) { printAll(args).currentThread() returns a reference to the currently executing Thread object. and there is no guarantee there will be a pause because currentThread() may not retrieve this thread. i < lines. What is the result of this code? A.C. } } } the static method Thread. with a 1-second pause. } public static void printAll(String[] lines) { for(int i = 0.

but it would still be incorrect if the InterruptedException was dealt with because all Java code. B is incorrect. C.3. B. The sleep() method is static.2. but it would be correct if the InterruptedException was dealt with.." . This code will not compile due to line 6. /* Line 5 */ t. D. 1. 1.2. /* Line 6 */ } public void run() { for(int i=1. i < 3.out.run().."). it still always affects the currently executing thread..2.. C is incorrect. This code will not compile due to line 5. } } } A.. or the methodprintAll() must declare it throws the InterruptedException. ++i) { System. so even if it is called on an instance. A is incorrect. The sleep() method must be enclosed in a try/catch block.. so the run() method executes as a normal method should and it prints "1.. What will be the output of the program? class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread().print(i + ". View Answer Workspace Report Discuss in Forum 13. runs in threads..D. including the main() method. Answer & Explanation Answer: Option C Explanation: Line 6 calls the run() method.

main() will finish after one thread. D. static final StringBuffer sb2 = new StringBuffer(). even though this will not start a true thread of execution.println (sb1 + " " + sb2). The code after line 6 will not execute until the run() method is complete. sb2. } } }.append("D"). } } A.start(). C. B is incorrect because it is legal to call the run() method. What will be the output of the program? class Test116 { static final StringBuffer sb1 = new StringBuffer(). View Answer Workspace Report Discuss in Forum 14. /* Line 28 */ System.append("B").out.append("A").start().A is incorrect because line 5 is the proper way to create an object. main() will finish in the middle of one thread. Cannot be determined. D is incorrect because the for loop only does two iterations. Answer & Explanation . } } }. new Thread() { public void run() { synchronized(sb1) { sb1.append("C"). public static void main(String args[]) { new Thread() { public void run() { synchronized(sb1) { sb1. main() will finish before starting threads. B. sb2.

yield(). B. } public static void main(String []argv) { (new ThreadTest()). Let us discuss. System.out. C.out. View Answer Workspace Report Discuss in Forum . D.Answer: Option D Explanation: Can you guarantee the order in which threads are going to run? No you can't.println("Leaving run").sleep(5000).println("In run"). View Answer Workspace Report Discuss in Forum 15. The code fails to compile in the main() method The code fails to compile in the run() method Only the text "In run" will be displayed The text "In run" followed by "Leaving run" will be displayed Answer & Explanation Answer: Option D Explanation: No answer description available for this question. What will be the output of the program? public class ThreadTest extends Thread { public void run() { System.start(). } } A. So how do you know what the output will be? The output cannot be determined. } catch(InterruptedException e) { } and you have some chance of predicting the outcome. add this code after line 28: try { Thread.

start(). This is guaranteed by the synchronised code. } public synchronized void run() { for(int i = 0. y++. C.. D. i++) { x++.currentThread(). but the output will be produced by first one thread then the other. View Answer Workspace Report Discuss in Forum .out..getName() + " x = " + x + ".println(Thread.out.. What will be the output of the program? public class Test107 implements Runnable { private int x. Will print in this order x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 7 y = B. 8.. private int y. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5. System.. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5. public static void main(String args[]) { Test107 that = new Test107(). /* Line 17 */ } } } A. (new Thread(that)). Modify line 17 to print the thread names: System. (new Thread(that)). Compilation error. Answer & Explanation Answer: Option C Explanation: Both threads are operating on the same instance variables. y = " + y). y = " + y).start(). i < 10. Because the code is synchronized the first thread will complete before the second thread begins.println("x = " + x + ".16.. but the output will be produced by both threads running simultaneously.

out. D. if (x >= 10) { notify().start().doStuff().println("x is " + x++). } catch(InterruptedException ex) { } } else { System. Answer & Explanation .doStuff(). public void doStuff() { if (x < 10) { // nothing to do try { wait(). t. C. g. } } class Foo { int x = 5. of class Foo.start(). It prints "x is 5 x is 6".17. The code will not compile because of some other error in class Test. What will be the output of the program? public class Test { public static void main (String [] args) { final Foo f = new Foo(). The code will not compile because of an error on notify(). B. Thread t = new Thread(new Runnable() { public void run() { f. An exception occurs at runtime. } }). } } } } A. Thread g = new Thread() { public void run() { f. } }.

. Option B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2. 0. B are incorrect because the code compiles without errors. View Answer Workspace Report Discuss in Forum 18.2.out.start()...1. /* Line 7 */ } public void run() { for(int i = 0.. B. in line 7.").print(i + ". Answer & Explanation Answer: Option D Explanation: The thread MyThread will start and loop three times (from 0 to 2). } } } A.. C. Thread x = new Thread(t)..2. therefore. i < 3. the code would run without exception. What will be the output of the program? class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread().3. 1.Answer: Option C Explanation: C is correct because the thread does not own the lock of the object it invokeswait() on.. Thread can take an object of type Thread as an argument in the constructor.1.3. D is incorrect because the exception is thrown before there is any output.2. Option A is incorrect because the Thread class implements the Runnable interface.. 0. Compilation fails... D. x.. . ++i) { System. If the method were synchronized. A.

View Answer Workspace Report Discuss in Forum 1.Thread and implement the run() method.Runnable and implement the run() method. 2 and 3 3 and 4 Answer & Explanation Answer: Option C . Extend java. 5. When a thread sleeps. Which statement is true? A. Extend java.Class that represents the class type. Implement java.lang.lang. 4. 3. it releases its locks. C. C. D is incorrect because a sleeping thread still maintains its locks. Implement java. Answer & Explanation Answer: Option B Explanation: B is correct because multiple threads are allowed to enter nonsynchronized code. even within a class that has some synchronized methods. A is incorrect because static methods can be synchronized. A static method cannot be synchronized. Which two can be used to create a new Thread? 1.lang.Thread and override the run() method.lang.lang. C is incorrect because only methods—not variables—can be marked synchronized. Variables can be protected from concurrent access problems by marking them with the synchronized keyword. A. View Answer Workspace Report Discuss in Forum 2. 1 and 2 1 and 4 B. D. Implement java. they synchronize on the lock on the instance of class java. B. multiple threads can still access the nonsynchronized code. 2.Thread and implement the start() method. If a class has synchronized code. D.lang.Runnable and override the start() method.

and another thread executes the notify method on the same object. C.You cannot implement java. Answer & Explanation Answer: Option B Explanation: Option B is correct . If two threads are blocked in the wait method of one object. Gives the error: (No interface expected here) (3) is wrong .Thread (This is a Class). then the first thread immediately resumes execution.The notify method only wakes the thread. It does not guarantee that the . gives the error: Interface expected). If a thread is blocked in the wait method of an object. A.Extending the Thread class and overriding its run method is a valid procedure. and another thread executes the notify method on the same object. then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call. extend (sub-class) the Thread class and implement the Runnable interface. it is still possible that the first thread might never resume execution. and Implement interfaces. (1) is correct .You must implement interfaces. (Implements Thread. and runnable is an interface and you must also include the run method.Explanation: There are two ways of creating a thread. (2) is wrong .Thread (This is a class). (Implements Thread. (5) is wrong . then the first thread definitely resumes execution as a direct and sole consequence of the notify call.lang.lang. D.Runnable is an interface which implements not Extends. B. and another thread executes the modify on that same object. Implements expects an interface.You cannot implement java. gives the error: Interface expected) View Answer Workspace Report Discuss in Forum 3. (4) is correct . You Extend classes. Which statement is true? If only one thread is blocked in the wait method of an object. and another thread executes the notify method on the same object. For both of these ways you must implement (override and not overload) the public void run() method. If a thread is blocked in the wait method of an object.

3. (4) is correct because the wait() method is overloaded to accept a wait duration in milliseconds. A thread must own the lock on the object its invoking wait()/notify()/notifyAll() on. (6) is correct because wait()/notify()/notifyAll() must all be called from within a synchronized. (1) is incorrect because wait()/notify() will not prevent deadlock. Synchronization can prevent two objects from being accessed by the same thread.This is incorrect because as said in Answer B notify only wakes the thread but further to this once it is awake it goes back into the stack and awaits execution therefore it is not a "direct and sole consequence of the notify call" Option D is incorrect .The notify method wakes one waiting thread up. 6. Both wait() and notify() must be called from a synchronized context. If the thread has not been notified by the time the wait duration has elapsed. context. then the thread will move back to runnable even without having been notified. 3 and 5 1 and 3 Answer & Explanation Answer: Option C Explanation: Statements (4) and (6) are correct.thread will run. C. Option A is incorrect . but it might not necessarily resume execution right away. the newly awakened thread . 1 and 2 4 and 6 B. View Answer Workspace Report Discuss in Forum 4. To resume executing. If there are more than one sleeping threads then the choice as to which thread to wake is made by the machine rather than you therefore you cannot guarantee that the notify'ed thread will be the first waiting thread. Deadlock will not occur if wait()/notify() is used 2. (2) is incorrect because a sleeping thread will return to runnable when it wakes up. The notify() method is overloaded to accept a duration. The wait() method is overloaded to accept a duration. Which two statements are true? 1. A thread will resume execution as soon as its sleep duration expires. 5. D. 4.just because another thread activates the modify method in A this does not mean that the thread will automatically resume execution Option C is incorrect . A.

Thread myThread = new Thread(target). so the compiler would complain when creating a Thread with an instance of it. B.must still be moved from runnable to running by the scheduler. so that the preceding code compiles correctly? A. The notifyAll() method must be called from a synchronized context. View Answer Workspace Report Discuss in Forum Which statement is true? A. Option B is incorrect because even though the class would compile and it has a valid public void run() method. public class MyRunnable extends Runnable{public void run(){}} public class MyRunnable extends Object{public void run(){}} public class MyRunnable implements Runnable{public void run(){}} public class MyRunnable implements Runnable{void run(){}} Answer & Explanation Answer: Option C Explanation: The class correctly implements the Runnable interface with a legal public void run() method. B. The following block of code creates a Thread using a Runnable target: Runnable target = new MyRunnable(). Option A is incorrect because interfaces are not extended. Option D is incorrect because the run() method must be public. C. it does not implement the Runnable interface. D. . Which of the following classes can be used to create the target. (5) is incorrect because notify() is not overloaded to accept a duration. To call wait(). View Answer Workspace Report Discuss in Forum 5. an object must own the lock on the thread. they are implemented. (3) is incorrect because synchronization prevents two or more threads from accessing the same object.

println("start completed"). The notify() method is defined in class java. B b = new B(). /* Line 7 */ . /* Line 6 */ System. a. void start() { A a = new A(). The thread can only release its locks by exiting the synchronized code. b = null.out.Thread.lang. View Answer Workspace Report Discuss in Forum 1. D. Option D is wrong because notify() will not cause a thread to release its locks. /* Line 5 */ a = null. The notify() method causes a thread to immediately release its locks. not the other way around.C.Object. Answer & Explanation Answer: Option A Explanation: Option A is correct because the notifyAll() method (along with wait() andnotify()) must always be called from within a synchronized context. the thread must own the lock on the object that wait() is being invoked on.lang.s(b). Option C is wrong because notify() is defined in java. Option B is incorrect because to call wait().

methodA(). eligible for garbage collection? A. D. class HappyGarbage01 { public static void main(String args[]) { HappyGarbage01 h = new HappyGarbage01(). created in line 3. return obj2[0]. obj2[0] = obj1.} When is the B object. B. After line 9 After line 10 After line 11 Garbage collector never invoked in methodA() Answer & Explanation . } } Where will be the most chance of the garbage collector being invoked? A. after line 5 after line 6 after line 7 There is no way to be absolutely certain. /* Line 6 */ } Object methodA() { Object obj1 = new Object(). C. B. View Answer Workspace Report Discuss in Forum 2. Let us discuss. obj1 = null. Object [] obj2 = new Object[1]. h. D. C. Answer & Explanation Answer: Option D Explanation: No answer description available for this question.

Garbage collection takes place after the method has returned its reference to the object. The method returns to line 6. newBar = new Bar(). The Objectobj1 still exists on the heap and can be accessed by an active thread through the reference stored in obj2[0]. eligible for garbage collection? A. Option B is wrong.Answer: Option D Explanation: Option D is correct. so garbage collection takes place after line 6. when main() completes Answer & Explanation . D. there is no reference to store the return value. B. class Bar { } class Test { Bar doBar() { Bar b = new Bar(). the other reference is maintained in obj2[0].println("finishing"). Option A is wrong. /* Line 12 */ System. created on line 6.doBar(). /* Line 11 */ Bar newBar = t. /* Line 15 */ } } At what point is the Bar object. C. Option C is wrong. when doBar() completes after line 15. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0]. /* Line 7 */ } public static void main (String args[]) { Test t = new Test(). /* Line 14 */ System. Because the reference to obj1 is stored in obj2[0]. after line 12 after line 14 after line 7. Because it is only one of the references to the object obj1. View Answer Workspace Report Discuss in Forum 3.out.println("newBar"). /* Line 6 */ return b.out.

} } When is the Demo object eligible for garbage collection? A. is eligible for garbage collection after line 14. D. void start() { d = new Demo(). Answer & Explanation Answer: Option D Explanation: Option D is correct. Because the reference in the doBar() method is returned on line 7 and is stored in newBar on line 12. Option A is wrong. B.Answer: Option B Explanation: Option B is correct. Not applicable because the object is eligible for garbage collection after line 14. Option C is wrong. this.takeDemo(d). View Answer Workspace Report Discuss in Forum 4. C. This actually protects the object from garbage collection. By a process of elimination. Therefore the Bar object. This preserver the object created on line 6. demo = new Demo(). All references to the Bar object created on line 6 are destroyed when a new reference to a new Bar object is assigned to the variable newBar on line 14. /* Line 7 */ } /* Line 8 */ void takeDemo(Demo demo) { demo = null. Option D is wrong. class Test { private Demo d. . After line 7 After line 8 After the start() method completes When the instance running this code is made eligible for garbage collection. created on line 6.

x2 = x4. public Object m() { Object o = new Float(3. Object [] oa = new Object[l]. /* Line 5 */ o = null. oa[0] = o. X x2 = m1(x). A copy of the variable d is set to null and not the actual variabled. C. when the start() method finishes the variable d still holds a reference. the only object without a reference is the one generated as a result of line 6. return mx. } static X m1(X mx) { mx = new X(). D.html View Answer Workspace Report Discuss in Forum 6. /* Line 6 */ oa[0] = null. Option C is wrong. /* Line 8 */ .com/javaworld/javaqa/2000-05/03-qa-0526-pass.14F). Ref: http://www. 0 2 B. Option B is wrong. /* Line 6 */ X x4 = new X().javaworld. how many objects are eligible for garbage collection? A. View Answer Workspace Report Discuss in Forum 5.Option A is wrong." so the reference variable x is not affected by the m1() method. /* Line 8 */ doComplexStuff(). The variable d exists outside the start() method (it is a class member). So. public class X { public static void main(String [] args) { X x = new X(). Remember that "Java is pass by value. } } After line 8 runs. 1 3 Answer & Explanation Answer: Option B Explanation: By the time line 8 has run. The variable d is a member of the Test class and is never directly set to null. /* Line 7 */ return o.

} } after line 11 runs. D. /* Line 6 */ X2 x3 = new X2().} When is the Float object. C. This simply copies the object reference into the array.x = x3. x2 = new X2(). just after line 5 just after line 7 B. The thread of execution will then not have access to the object. x3. Option C is correct. /* Line 11 */ doComplexStuff(). C. 0 2 B. but no live thread can reach either of . how many objects are eligible for garbage collection? A. just after line 6 just after line 8 Answer & Explanation Answer: Option C Explanation: Option A is wrong. public static void main(String [] args) { X2 x2 = new X2(). x3 = x2. oa[0] still maintains the reference to the Float object. eligible for garbage collection? A. The reference o is set to null. but. class X2 { public X2 x. created in line 3. Option B is wrong. D. By the time line 11 has run.x = x2. the objects instantiated in lines 6 and 7 are referring to each other. View Answer Workspace Report Discuss in Forum 7. 1 3 Answer & Explanation Answer: Option C Explanation: This is an example of the islands of isolated objects. /* Line 7 */ x2.

StringBuffer : Removes the characters in a substring of this StringBuffer.Method in class java. int) . Answer & Explanation Answer: Option D Explanation: Option D is correct. What allows the programmer to destroy an object x? A.finalize() Runtime.text. from this questions point of view.lang. They are: 1. it may be unloaded. x. When an object is no longer referenced. 2. But it is interesting. int) . int) . C. If an object declares a finalizer.AccessibleEditableText : Deletes the text between two indices 4. I found 19 finalize() methods. The most interesting. was the finalize() method in class java.io.Method in class :javax.delete() x. D. getRuntime() .Returns the runtime object associated with the current Java application.JTextComponent.accessibility.swing. 3.File : Deletes the file or directory denoted by this abstract pathname. B. This method does not destroy the object to which it belongs.AccessibleJTextComponent. delete(int. Option B is wrong. delete(int. the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released.gc() Only the garbage collection system can destroy an object. delete() . I found 4 delete() methods in all of the Java class structure.Objectwhich is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. it may be reclaimed by the garbage collector. two of which are: 1. Option C is wrong. The Runtime class has many methods. Deletes the text between two indices None of these destroy the object to which they belong. View Answer Workspace Report Discuss in Forum 8. Option A is wrong.Method in class java. .lang.Method in interfacejavax. When a class is no longer needed.getRuntime().them. delete(int.

Which statement is true? A. B.2. Objects instantiated within anonymous inner classes are placed in the garbage B. Objects that can be reached from a live thread will never be garbage collected. gc() . Even though Java applications can run out of memory there another answer supplied that is more right. Objects from a class with the finalize() method overridden will never be garbage collected. D. . the virtual machine has made its best effort to recycle all discarded objects. Which statement is true? A. View Answer Workspace Report Discuss in Forum 1. See the note above on Islands of Isolation (An object is eligible for garbage collection when no live thread can access it . Answer & Explanation Answer: Option D Explanation: Option D is correct. Objects with at least one reference will never be garbage collected. Option C is wrong. it doesn't destroy the object. Option B is wrong. Objects that are referred to by other objects will never be garbage collected. All objects that are eligible for garbage collection will be garbage collected by the garbage collector. C.Runs the garbage collector.even though there might be references to it). Option A is wrong. When control returns from the method call. Interesting as this is. Programs will not run out of memory. "Never again be used" does not mean that there are no more references to the object. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. D. View Answer Workspace Report Discuss in Forum 2. Objects that will never again be used are eligible for garbage collection. C.

Option D is wrong. If an object can be accessed from a live thread. but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory.gc().gc() asks the garbage collector to run. C. If this were the case then the garbage collector would actively hang onto objects until a program finishes . B. Option B is incorrect because islands of isolated objects can exist. Runtime.this goes against the purpose of the garbage collector. View Answer Workspace Report Discuss in Forum 3. Objects are not collected if they are accessible from live threads. Answer & Explanation Answer: Option B Explanation: Option B is correct. . Answer & Explanation Answer: Option D Explanation: All objects are placed in the garbage collectible heap. Option C is incorrect because finalize() has no such mystical powers. Which statement is true? A. An OutOfMemory error is only thrown if a single block of memory cannot be found that is large enough for a particular requirement. it can't be garbage collected. Option C is wrong.collectible heap. D. Memory is reclaimed by calling Runtime. The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM. Option A is incorrect because the garbage collector makes no guarantees. Objects that have finalize() methods always have their finalize()methods called before the program ends. Option A is wrong.

Calling Runtime. Answer & Explanation Answer: Option C Explanation: This is a great way to think about when objects can be garbage collected. If an object can be accessed from a live thread. D. The garbage collector uses a mark and sweep algorithm. C.gc() will cause eligible objects to be garbage collected. B. Option A and B assume guarantees that the garbage collector never makes. it can't be garbage collected. then object 2 can't be garbage collected. If object 1 refers to object 2. Option D is wrong because of the now famous islands of isolation scenario. View Answer Workspace Report Discuss in Forum .View Answer Workspace Report Discuss in Forum 4. Which statement is true? A.