Anda di halaman 1dari 212

http://www.indiabix.

com/java-programming/questions-and-answers/

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.1, 2, 3, 4 C. 2, 4, 5, 6 Answer & Explanation Answer: Option B Explanation: (1), (3), (4), (5) are the correct statements.

B. 1, 3, 4, 5 D.3, 4, 5, 6

(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. 2. Which one of these lists contains only Java programming language keywords? A.class, if, void, long, Int, continue B. goto, instanceof, native, finally, default, throws C. try, virtual, throw, final, volatile, transient D.strictfp, constant, super, implements, do E. 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.

3. Which will legally declare, construct, and initialize an array? A.int [] myList = {"1", "2", "3"}; B. int [] myList = (5, 8, 2); C. int myList [] [] = {4,9,7,0}; D.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. 4. Which is a reserved word in the Java programming language? A.method B. native C. subclasses D.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'. 5. Which is a valid keyword in java? A.interface B. string C. Float D.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. 6. Which three are legal array declarations? 1. 2. 3. 4. 5. int [] myScores []; char [] myChars; int [6] myScores; Dog myDogs []; Dog myDogs [7]; B. 2, 4, 5 D.All are correct.

A.1, 2, 4 C. 2, 3, 4 Answer & Explanation Answer: Option A Explanation:

(1), (2), and (4) are legal array declarations. With an array declaration, you can place the brackets to the right or left of the identifier. Option A looks strange, but it's perfectly legal to split the brackets in a multidimensional array, and place them on both sides of the identifier. Although coding this way would only annoy your fellow programmers, for the exam, you need to know it's legal. (3) and (5) are wrong because you can't declare an array with a size. 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, based on the type of array and the size). View Answer Workspace Report Discuss in Forum 7. public interface Foo
{ int k = 4; /* Line 3 */ }

Which three piece of codes are equivalent to line 3? 1. 2. 3. 4. 5. 6. final int k = 4; public int k = 4; static int k = 4; abstract int k = 4; volatile int k = 4; protected int k = 4; B. 2, 3 and 4 D.4, 5 and 6

A.1, 2 and 3 C. 3, 4 and 5 Answer & Explanation

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

A.1, 2, 4 B. 1, 3, 6 C. 3, 5 D.5 only

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

11. Which one is a valid declaration of a boolean? A.boolean b1 = 0; B. boolean b2 = 'false'; C. boolean b3 = false; D.boolean b4 = Boolean.false(); E. boolean b5 = no; Answer & Explanation Answer: Option C Explanation: A boolean can only be assigned the literal true or false. View Answer Workspace Report Discuss in Forum 12. Which three are valid declarations of a float? 1. 2. 3. 4. 5. 6. float f1 = -343; float f2 = 3.14; float f3 = 0x12345; float f4 = 42e7; float f5 = 2001.0D; float f6 = 2.81F; B. 2, 3, 5 D.2, 4, 6

A.1, 2, 4 C. 1, 3, 6 Answer & Explanation Answer: Option C Explanation:

(1) and (3) are integer literals (32 bits), and integers can be legally assigned to floats (also 32 bits). (6) is correct because (F) is appended to the literal, declaring it as a float rather than a double (the default for floating point literals). (2), (4),and (5) are all doubles. View Answer Workspace Report Discuss in Forum 13. Which is a valid declarations of a String? A.String s1 = null; B. String s2 = 'null'; C. String s3 = (String) 'abc'; D.String s4 = (String) '\ufeed'; Answer & Explanation

Answer: Option A Explanation: Option A sets the String reference to null. Option B is wrong because null cannot be in single quotes. Option C is wrong because there are multiple characters between the single quotes ('abc'). Option D is wrong because you can't cast a char (primitive) to a String (object). View Answer Workspace Report Discuss in Forum 14. What is the numerical range of a char? A.-128 to 127 C. 0 to 32767 Answer & Explanation Answer: Option D Explanation: A char is really a 16-bit integer behind the scenes, so it supports 216 (from 0 to 65535) values. 15 What will be the output of the program?
public class CommandArgsThree { public static void main(String [] args) { String [][] argCopy = new String[2][2]; int x; argCopy[0] = args; x = argCopy[0].length; for (int y = 0; y < x; y++) { System.out.print(" " + argCopy[0][y]); } } }

B. -(215) to (215) - 1 D.0 to 65535

and the command-line invocation is > java CommandArgsThree 1 2 3 A.0 0 C. 0 0 0 Answer & Explanation

B. 1 2 D.1 2 3

Answer: Option D Explanation: In argCopy[0] = args;, the reference variable argCopy[0] , which was referring to an array with two elements, is reassigned to an array (args) with three elements. View Answer Workspace Report Discuss in Forum 16. What will be the output of the program?
public class CommandArgs { public static void main(String [] args) { String s1 = args[1]; String s2 = args[2]; String s3 = args[3]; String s4 = args[4]; System.out.print(" args[2] = " + s2); } }

and the command-line invocation is > java CommandArgs 1 2 3 4 A.args[2] = 2 B. args[2] = 3 C. args[2] = null D.An exception is thrown at runtime. Answer & Explanation Answer: Option D Explanation: An exception is thrown because in the code String s4 = args[4];, the array index (the fifth element) is out of bounds. The exception thrown is the cleverly named ArrayIndexOutOfBoundsException. View Answer Workspace Report Discuss in Forum 17. public class F0091
{ public void main( String[] args ) { System.out.println( "Hello" + args[0] ); } }

What will be the output of the program, if this code is executed with the command

line: > java F0091 world A.Hello B. Hello Foo91 C. Hello world D.The code does not run. Answer & Explanation Answer: Option D Explanation: Option D is correct. A runtime error will occur owning to the main method of the code fragment not being declared static: Exception in thread "main" java.lang.NoSuchMethodError: main The Java Language Specification clearly states: "The main method must be declared public, static, and void. It must accept a single argument that is an array of strings." View Answer Workspace Report Discuss in Forum 18. What will be the output of the program?
public class TestDogs { public static void main(String [] args) { Dog [][] theDogs = new Dog[3][]; System.out.println(theDogs[2][0].toString()); } } class Dog { }

A.null B. theDogs C. Compilation fails D.An exception is thrown at runtime Answer & Explanation Answer: Option D Explanation: The second dimension of the array referenced by theDogs has not been initialized. Attempting to access an uninitialized object element (System.out.println(theDogs[2][0].toString());) raises a NullPointerException. View Answer Workspace Report Discuss in Forum

19. What will be the output of the program ?


public class Test { public static void main(String [] args) { signed int x = 10; for (int y=0; y<5; y++, x--) System.out.print(x + ", "); } }

A.10, 9, 8, 7, 6, B. 9, 8, 7, 6, 5, C. Compilation fails. D.An exception is thrown at runtime. Answer & Explanation Answer: Option C Explanation: The word "signed" is not a valid modifier keyword in the Java language. All number primitives in Java are signed. Hence the Compilation will fails. 20. What will be the output of the program?
public class CommandArgsTwo { public static void main(String [] argh) { int x; x = argh.length; for (int y = 1; y <= x; y++) { System.out.print(" " + argh[y]); } } }

and the command-line invocation is > java CommandArgsTwo 1 2 3 A.0 1 2 B. 1 2 3 C. 0 0 0 D.An exception is thrown at runtime Answer & Explanation Answer: Option D Explanation: An exception is thrown because at some point in (System.out.print(" " + argh[y]);), the value of x will be equal to y, resulting in an attempt to access an index out of

bounds for the array. Remember that you can access only as far as length - 1, so loop logical tests should use x < someArray.length as opposed to x < = someArray.length. View Answer Workspace Report Discuss in Forum 21. In the given program, how many lines of output will be produced?
public class Test { public static void main(String [] args) { int [] [] [] x = new int [3] [] []; int i, j; x[0] = new int[4][]; x[1] = new int[2][]; x[2] = new int[5][]; for (i = 0; i < x.length; i++) { for (j = 0; j < x[i].length; j++) { x[i][j] = new int [i + j + 1]; System.out.println("size = " + x[i][j].length); } } } }

A.7 C. 11 E. Compilation fails Answer & Explanation Answer: Option C Explanation: The loops use the array sizes (length).

B. 9 D.13

It produces 11 lines of output as given below.


D:\Java>javac Test.java D:\Java>java Test size = 1 size = 2 size = 3 size = 4 size = 2 size = 3 size = 3 size = 4 size = 5 size = 6 size = 7

Therefore, 11 is the answer. View Answer Workspace Report Discuss in Forum 22. What will be the output of the program?
public class X { public static void main(String [] args) { String names [] = new String[5]; for (int x=0; x < args.length; x++) names[x] = args[x]; System.out.println(names[2]); } }

and the command line invocation is > java X a b A.names B. null C. Compilation fails D.An exception is thrown at runtime Answer & Explanation Answer: Option B Explanation: The names array is initialized with five null elements. Then elements 0 and 1 are assigned the String values "a" and "b" respectively (the command-line arguments passed to main). Elements of names array 2, 3, and 4 remain unassigned, so they have a value of null. 23. You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective? A.public B. private C. protected D.transient Answer & Explanation Answer: Option C Explanation: Access modifiers dictate which classes, not which instances, may access features. Methods and variables are collectively known as members. Method and variable members are given access control in exactly the same way.

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. public means that all other classes regardless of the package that they belong to, can access the member (assuming the class itself is visible) final makes it impossible to extend a class, when applied to a method it prevents a method from being overridden in a subclass, 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. transient indicates that a variable is not part of the persistent state of an object. volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. 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 - protected. A is also a contender but C is more restrictive, 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. View Answer Workspace Report Discuss in Forum 24. public class Outer
{ public void someOuterMethod() { //Line 5 } public class Inner { } public static void main(String[] argv) { Outer ot = new Outer(); //Line 10 } }

Which of the following code fragments inserted, will allow to compile? A.new Inner(); //At line 5 B. new Inner(); //At line 10 C. new ot.Inner(); //At line 10 D.new Outer.Inner(); //At line 10 Answer & Explanation

Answer: Option A Explanation: Option A compiles without problem. Option B gives error - non-static variable cannot be referenced from a static context. Option C package ot does not exist. Option D gives error - non-static variable cannot be referenced from a static context. View Answer Workspace Report Discuss in Forum 25. interface Base
{ boolean m1 (); byte m2(short s); }

which two code fragments will compile? 1. interface Base2 implements Base {} 2. abstract class Class2 extends Base { public boolean m1(){ return true; }} 3. abstract class Class2 implements Base {} 4. abstract class Class2 implements Base { public boolean m1(){ return (7 > 4); }} 5. abstract class Class2 implements Base { protected boolean m1(){ return (5 > 7) }} A.1 and 2 C. 3 and 4 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. (4) is correct because the method is correctly implemented ((7 > 4) is a boolean). (1) is incorrect because interfaces don't implement anything. (2) is incorrect because classes don't extend interfaces. (5) is incorrect because interface methods are implicitly public, so the methods being implemented must be public. View Answer Workspace Report Discuss in Forum 26. Which three form part of correct array declarations? B. 2 and 3 D.1 and 5

1. 2. 3. 4. 5. 6.

public int a [ ] static int [ ] a public [ ] int a private int a [3] private int [3] a [ ] public final int [ ] a B. 2, 4, 5 D.2, 5, 6

A.1, 3, 4 C. 1, 2, 6 Answer & Explanation Answer: Option C Explanation:

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

28. 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.public B. abstract C. protected D.synchronized E. default access Answer & Explanation Answer: Option E Explanation: default access is the "package oriented" access modifier. Option A and C are wrong because public and protected are less restrictive. Option B and D are wrong because abstract and synchronized are not access modifiers. View Answer Workspace Report Discuss in Forum 29. Which of the following is/are legal method declarations? 1. 2. 3. 4. protected abstract void m1(); static final void m1(){} synchronized public final void m1() {} private native void m1();

A.1 and 3 B. 2 and 4 C. 1 only D.All of them are legal declarations. Answer & Explanation Answer: Option D Explanation: All the given statements are legal declarations. View Answer Workspace Report Discuss in Forum 30. Which cause a compiler error? A.int[ ] scores = {3, 5, 7}; B. int [ ][ ] scores = {2,7,6}, {9,3,45}; C. String cats[ ] = {"Fluffy", "Spot", "Zeus"}; D.boolean results[ ] = new boolean [] {true, false, true}; E. Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)}; Answer & Explanation Answer: Option B

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

A.1 and 2 C. 3, 4, and 5 Answer & Explanation Answer: Option B Explanation:

(2), (3), and (5). These are all valid interface method signatures. (1), is incorrect because an interface method must be public; if it is not explicitly declared public it will be made public implicitly. (4) is incorrect because interface methods cannot be static. View Answer Workspace Report Discuss in Forum 32. You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective? A.public B. private C. protected D.default access Answer & Explanation Answer: Option D Explanation: The only two real contenders are C and D. Protected access Option C makes a member accessible only to classes in the same package or subclass of the class. While default access Option D makes a member accessible only to classes in the

same package.

33. What is the widest valid returnType for methodA in line 3?


public class ReturnIt { returnType methodA(byte x, double y) /* Line 3 */ { return (long)x / y * 2; } }

A.int C. long Answer & Explanation Answer: Option D Explanation:

B. byte D.double

However A, B and C are all wrong. Each of these would result in a narrowing conversion. Whereas we want a widening conversion, therefore the only correct answer is D. Don't be put off by the long cast, this applies only to the variable x and not the rest of the expression. It is the variable y (of type double) that forces the widening conversion to double. Java's widening conversions are: - From a byte to a short, an int, a long, a float, or a double. - From a short, an int, a long, a float, or a double. - From a char to an int, a long, a float, or a double. - From an int to a long, a float, or a double. - From a long to a float, or a double. - From a float to a double. View Answer Workspace Report Discuss in Forum 34. class A
{ protected int method1(int a, int b) { return 0; } }

Which is valid in a class that extends class A? A.public int method1(int a, int b) {return 0; } B. private int method1(int a, int b) { return 0; } C. public short method1(int a, int b) { return 0; } D.static protected int method1(int a, int b) { return 0; } Answer & Explanation Answer: Option A Explanation: Option A is correct - because the class that extends A is just simply overriding method1. Option B is wrong - because it can't override as there are less access privileges in the subclass method1. Option C is wrong - because to override it, the return type needs to be an integer. The different return type means that the method is not overriding but the same argument list means that the method is not overloading. Conflict - compile time error. Option D is wrong - because you can't override a method and make it a class method i.e. using static. View Answer Workspace Report Discuss in Forum 35. Which one creates an instance of an array? A.int[ ] ia = new int[15]; B. float fa = new float[20]; C. char[ ] ca = "Some String"; D.int ia[ ] [ ] = { 4, 5, 6 }, { 1,2,3 }; Answer & Explanation Answer: Option A Explanation: Option A is correct. It uses correct array declaration and correct array construction. Option B is incorrect. It generates a compiler error: incompatible types because the array variable declaration is not correct. The array construction expects a reference type, but it is supplied with a primitive type in the declaration. Option C is incorrect. It generates a compiler error: incompatible types because a string literal is not assignable to a character type variable. Option D is wrong, it generates a compiler error <identifier> expected. The compiler thinks that you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create a 3 x 3

two-dimensional array. View Answer Workspace Report Discuss in Forum 36. Which two of the following are legal declarations for nonnested classes and interfaces? 1. 2. 3. 4. 5. 6. final abstract class Test {} public static interface Test {} final public class Test {} protected abstract class Test {} protected interface Test {} abstract public class Test {} B. 2 and 5 D.4 and 6

A.1 and 4 C. 3 and 6 Answer & Explanation Answer: Option C Explanation: (3), (6). Both are legal class declarations.

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

1. 2. 3. 4. 5.

float[ ] f = new float(3); float f2[ ] = new float[ ]; float[ ]f1 = new float[3]; float f3[ ] = new float[3]; float f5[ ] = {1.0f, 2.0f, 2.0f}; B. 3, 5 D.1, 2

A.2, 4 C. 4, 5 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 [ ] . The following is the correct syntax: float[ ] f = new float[3]; (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 f2[ ] = new float[3]; (3), (4), and (5) compile without error. View Answer Workspace Report Discuss in Forum 39. Given a method in a protected class, what access modifier do you use to restrict access to that method to only the other members of the same class? A.final B. static C. private D.protected E. volatile Answer & Explanation Answer: Option C Explanation: The private access modifier limits access to members of the same class. Option A, B, D, and E are wrong because protected are the wrong access modifiers, and final, static, and volatile are modifiers but not access modifiers. View Answer Workspace Report Discuss in Forum 40. Which is a valid declaration within an interface? A.public static short stop = 23; B. protected short stop = 23; C. transient short stop = 23; D.final void madness(short stop); Answer & Explanation

Answer: Option A Explanation: (A) is valid interface declarations. (B) and (C) are incorrect because interface variables cannot be either protected or transient. (D) is incorrect because interface methods cannot be final or static. 41. What will be the output of the program?
class A { final public int GetResult(int a, int b) { return 0; } } class B extends A { public int GetResult(int a, int b) {return 1; } } public class Test { public static void main(String args[]) { B b = new B(); System.out.println("x = " + b.GetResult(0, 1)); } }

A.x = 0 B. x = 1 C. Compilation fails. D.An exception is thrown at runtime. Answer & Explanation Answer: Option C Explanation: The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden. View Answer Workspace Report Discuss in Forum 42. What will be the output of the program?
public class Test { public static void main(String args[]) { class Foo { public int i = 3; } Object o = (Object)new Foo(); Foo foo = (Foo)o;

System.out.println("i = " + foo.i); } }

A.i = 3 B. Compilation fails. C. i = 5 D.A ClassCastException will occur. Answer & Explanation Answer: Option A Explanation: No answer description available for this question. Let us discuss. View Answer Workspace Report Discuss in Forum 43. What will be the output of the program?
public class A { void A() /* Line 3 */ { System.out.println("Class A"); } public static void main(String[] args) { new A(); } }

A.Class A B. Compilation fails. C. An exception is thrown at line 3. D.The code executes with no output. Answer & Explanation Answer: Option D Explanation: Option D is correct. The specification at line 3 is for a method and not a constructor and this method is never called therefore there is no output. The constructor that is called is the default constructor. View Answer Workspace Report Discuss in Forum 44. What will be the output of the program?
class Super { public int i = 0; public Super(String text) /* Line 4 */ {

i = 1; } } class Sub extends Super { public Sub(String text) { i = 2; } public static void main(String args[]) { Sub sub = new Sub("Hello"); System.out.println(sub.i); } }

A.0 C. 2 Answer & Explanation Answer: Option D Explanation:

B. 1 D.Compilation fails.

A default no-args constructor is not created because there is a constructor supplied that has an argument, line 4. Therefore the sub-class constructor must explicitly make a call to the super class constructor:
public Sub(String text) { super(text); // this must be the first line constructor i = 2; }

View Answer Workspace Report Discuss in Forum 45. What will be the output of the program?
public class Test { public int aMethod() { static int i = 0; i++; return i; } public static void main(String args[]) { Test test = new Test(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } }

A.0 C. 2 Answer & Explanation

B. 1 D.Compilation fails.

Answer: Option D Explanation: Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local). 46. What will be the output of the program?
interface Count { short counter = 0; void countUp(); } public class TestCount implements Count { public static void main(String [] args) { TestCount t = new TestCount(); t.countUp(); } public void countUp() { for (int x = 6; x>counter; x--, ++counter) /* Line 14 */ { System.out.print(" " + counter); } } }

A.0 1 2 C. 0 1 2 3 E. Compilation fails Answer & Explanation Answer: Option E Explanation:

B. 1 2 3 D.1 2 3 4

The code will not compile because the variable counter is an interface variable that is by default final static. The compiler will complain at line 14 when the code attempts to increment counter. View Answer Workspace Report Discuss in Forum 47. What will be the output of the program?
class Base { Base() { System.out.print("Base"); } } public class Alpha extends Base

{ public static void main(String[] args) { new Alpha(); /* Line 12 */ new Base(); /* Line 13 */ } }

A.Base B. BaseBase C. Compilation fails D.The code runs with no output Answer & Explanation Answer: Option B Explanation: Option B is correct. It would be correct if the code had compiled, and the subclass Alpha had been saved in its own file. In this case Java supplies an implicit call from the sub-class constructor to the no-args constructor of the super-class therefore line 12 causes Base to be output. Line 13 also causes Base to be output. Option A is wrong. It would be correct if either the main class or the subclass had not been instantiated. Option C is wrong. The code compiles. Option D is wrong. There is output. View Answer Workspace Report Discuss in Forum 48. What will be the output of the program?
import java.util.*; public class NewTreeSet2 extends NewTreeSet { public static void main(String [] args) { NewTreeSet2 t = new NewTreeSet2(); t.count(); } } protected class NewTreeSet { void count() { for (int x = 0; x < 7; x++,x++ ) { System.out.print(" " + x); } } }

A.0 2 4 B. 0 2 4 6 C. Compilation fails at line 2

D.Compilation fails at line 10 Answer & Explanation Answer: Option D Explanation: Nonnested classes cannot be marked protected (or final for that matter), so the compiler will fail at protected class NewTreeSet. View Answer Workspace Report Discuss in Forum 49. What will be the output of the program?
public class ArrayTest { public static void main(String[ ] args) { float f1[ ], f2[ ]; f1 = new float[10]; f2 = f1; System.out.println("f2[0] = " + f2[0]); } }

A.It prints f2[0] = 0.0 B. It prints f2[0] = NaN C. An error at f2 = f1; causes compile to fail. D.It prints the garbage value. Answer & Explanation Answer: Option A Explanation: Option A is correct. When you create an array (f1 = new float[10];) the elements are initialises to the default values for the primitive data type (float in this case - 0.0), so f1 will contain 10 elements each with a value of 0.0. f2 has been declared but has not been initialised, it has the ability to reference or point to an array but as yet does not point to any array. f2 = f1; copies the reference (pointer/memory address) of f1 into f2 so now f2 points at the array pointed to by f1. This means that the values returned by f2 are the values returned by f1. Changes to f1 are also changes to f2 because both f1 and f2 point to the same array. View Answer Workspace Report Discuss in Forum 50. What will be the output of the program?
class Super { public Integer getLength() { return new Integer(4);

} } public class Sub extends Super { public Long getLength() { return new Long(5); } public static void main(String[] args) { Super sooper = new Super(); Sub sub = new Sub(); System.out.println( sooper.getLength().toString() + "," + sub.getLength().toString() ); } }

A.4, 4 C. 5, 4 Answer & Explanation Answer: Option D Explanation:

B. 4, 5 D.Compilation fails.

Option D is correct, compilation fails - The return type of getLength( ) in the super class is an object of reference type Integer and the return type in the sub class is an object of reference type Long. In other words, it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed. 51. interface DoMath
{ double getArea(int rad); } interface MathPlus { double getVol(int b, int h); } /* Missing Statements ? */

which two code fragments inserted at end of the program, will allow to compile? 1. 2. 3. 4. 5. class AllMath extends DoMath { double getArea(int r); } interface AllMath implements MathPlus { double getVol(int x, int y); } interface AllMath extends DoMath { float getAvg(int h, int l); } class AllMath implements MathPlus { double getArea(int rad); } abstract class AllMath implements DoMath, MathPlus { public double getArea(int rad) { return rad * rad * 3.14; } } B. 2 only D.1 and 4

A.1 only C. 3 and 5 Answer & Explanation

Answer: Option C Explanation: (3) are (5) are correct because interfaces and abstract classes do not need to fully implement the interfaces they extend or implement (respectively). (1) is incorrect because a class cannot extend an interface. (2) is incorrect because an interface cannot implement anything. (4) is incorrect because the method being implemented is from the wrong interface. View Answer Workspace Report Discuss in Forum 52. Which two statements are true for any concrete class implementing the java.lang.Runnable interface? 1. You can extend the Runnable interface as long as you override the public run() method. 2. The class must contain a method called run() from which all code for that thread will be initiated. 3. The class must contain an empty public void method named run(). 4. The class must contain a public void method named runnable(). 5. The class definition must include the words implements Threads and contain a method called run(). 6. The mandatory method must be public, with a return type of void, must be called run(), and cannot take any arguments. A.1 and 3 C. 1 and 5 Answer & Explanation Answer: Option D Explanation: (2) and (6). When a thread's run() method completes, the thread will die. The run() method must be declared public void and not take any arguments. (1) is incorrect because classes can never extend interfaces. (3) is incorrect because the run() method is typically not empty; if it were, the thread would do nothing. (4) is incorrect because the mandatory method is run(). (5) is incorrect because the class implements Runnable. View Answer Workspace Report Discuss in Forum 53. /* Missing statements ? */
public class NewTreeSet extends java.util.TreeSet { public static void main(String [] args) {

B. 2 and 4 D.2 and 6

java.util.TreeSet t = new java.util.TreeSet(); t.clear(); } public void clear() { TreeMap m = new TreeMap(); m.clear(); } }

which two statements, added independently at beginning of the program, allow the code to compile? 1. 2. 3. 4. 5. No statement is required import java.util.*; import.java.util.Tree*; import java.util.TreeSet; import java.util.TreeMap; B. 2 and 5 D.3 and 5

A.1 only C. 3 and 4 Answer & Explanation Answer: Option B Explanation:

(2) and (5). TreeMap is the only class that must be imported. TreeSet does not need an import statement because it is described with a fully qualified name. (1) is incorrect because TreeMap must be imported. (3) is incorrect syntax for an import statement. (4) is incorrect because it will not import TreeMap, which is required. View Answer Workspace Report Discuss in Forum 54. Which three statements are true? 1. 2. 3. 4. The default constructor initialises method variables. The default constructor has the same access as its class. The default constructor invokes the no-arg constructor of the superclass. If a class lacks a no-arg constructor, the compiler always creates a default constructor. 5. The compiler creates a default constructor only when there are no other constructors for the class. B. 2, 3 and 5 D.1, 2 and 3

A.1, 2 and 4 C. 3, 4 and 5 Answer & Explanation Answer: Option B

Explanation: (2) sounds correct as in the example below


class CoffeeCup { private int innerCoffee; public CoffeeCup() { } public void add(int amount) { innerCoffee += amount; } //... }

The compiler gives default constructors the same access level as their class. In the example above, class CoffeeCup is public, so the default constructor is public. If CoffeeCup had been given package access, the default constructor would be given package access as well. (3) is correct. The Java compiler generates at least one instance initialisation method for every class it compiles. In the Java class file, the instance initialisation method is named "<init>." For each constructor in the source code of a class, the Java compiler generates one <init>() method. If the class declares no constructors explicitly, the compiler generates a default no-arg constructor that just invokes the superclass's no-arg constructor. As with any other constructor, the compiler creates an <init>() method in the class file that corresponds to this default constructor. (5) is correct. The compiler creates a default constructor if you do not declare any constructors in your class. View Answer Workspace Report Discuss in Forum 55.
package testpkg.p1; public class ParentUtil { public int x = 420; protected int doStuff() { return x; } } package testpkg.p2; import testpkg.p1.ParentUtil; public class ChildUtil extends ParentUtil { public static void main(String [] args) { new ChildUtil().callStuff(); } void callStuff() { System.out.print("this " + this.doStuff() ); /* Line 18 */ ParentUtil p = new ParentUtil(); System.out.print(" parent " + p.doStuff() ); /* Line 20 */ } }

which statement is true?

A.The code compiles and runs, with output this 420 parent 420. B. If line 18 is removed, the code will compile and run. C. If line 20 is removed, the code will compile and run. D.An exception is thrown at runtime. Answer & Explanation Answer: Option C Explanation: The ParentUtil instance p cannot be used to access the doStuff() method. Because doStuff() has protected access, and the ChildUtil class is not in the same package as the ParentUtil class, doStuff() can be accessed only by instances of the ChildUtil class (a subclass of ParentUtil). Option A, B, D, and E are incorrect because of the access rules described previously. 56. What will be the output of the program?
class PassA { public static void main(String [] args) { PassA p = new PassA(); p.start(); } void start() { long [] a1 = {3,4,5}; long [] a2 = fix(a1); System.out.print(a1[0] + a1[1] + a1[2] + " "); System.out.println(a2[0] + a2[1] + a2[2]); } long [] fix(long [] a3) { a3[1] = 7; return a3; } }

A.12 15 C. 3 4 5 3 7 5 Answer & Explanation Answer: Option B Explanation: Output: 15 15

B. 15 15 D.3 7 5 3 7 5

The reference variables a1 and a3 refer to the same long array object. When the [1] element is updated in the fix() method, it is updating the array referred to by a1. The

reference variable a2 refers to the same array object. So Output: 3+7+5+" "3+7+5 Output: 15 15 Because Numeric values will be added View Answer Workspace Report Discuss in Forum 57. What will be the output of the program?
class Test { public static void main(String [] args) { Test p = new Test(); p.start(); } void start() { boolean b1 = false; boolean b2 = fix(b1); System.out.println(b1 + " " + b2); } boolean fix(boolean b1) { b1 = true; return b1; } }

A.true true C. true false Answer & Explanation Answer: Option B Explanation:

B. false true D.false false

The boolean b1 in the fix() method is a different boolean than the b1 in the start() method. The b1 in the start() method is not updated by the fix() method. View Answer Workspace Report Discuss in Forum 58. What will be the output of the program?
class PassS { public static void main(String [] args) { PassS p = new PassS(); p.start(); } void start() {

String s1 = "slip"; String s2 = fix(s1); System.out.println(s1 + " " + s2); } String fix(String s1) { s1 = s1 + "stream"; System.out.print(s1 + " "); return "stream"; } }

A.slip stream B. slipstream stream C. stream slip stream D.slipstream slip stream Answer & Explanation Answer: Option D Explanation: When the fix() method is first entered, start()'s s1 and fix()'s s1 reference variables both refer to the same String object (with a value of "slip"). 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"). When the program returns to start(), another String object is created, referred to by s2 and with a value of "stream". View Answer Workspace Report Discuss in Forum 59. What will be the output of the program?
class BitShift { public static void main(String [] args) { int x = 0x80000000; System.out.print(x + " and "); x = x >>> 31; System.out.println(x); } }

A.-2147483648 and 1 B. 0x80000000 and 0x00000001 C. -2147483648 and -1 D.1 and -2147483648 Answer & Explanation Answer: Option A Explanation: Option A is correct. The >>> operator moves all bits to the right, zero filling the

left bits. The bit transformation looks like this: Before: 1000 0000 0000 0000 0000 0000 0000 0000 After: 0000 0000 0000 0000 0000 0000 0000 0001 Option C is incorrect because the >>> operator zero fills the left bits, which in this case changes the sign of x, as shown. Option B is incorrect because the output method print() always displays integers in base 10. Option D is incorrect because this is the reverse order of the two output numbers. View Answer Workspace Report Discuss in Forum 60. What will be the output of the program?
class Equals { public static void main(String [] args) { int x = 100; double y = 100.1; boolean b = (x = y); /* Line 7 */ System.out.println(b); } }

A.true B. false C. Compilation fails D.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. The == operator compares values to produce a boolean, whereas the = operator assigns a value to variables. Option A, B, and D are incorrect because the code does not get as far as compiling. If we corrected this code, the output would be false. 61. What will be the output of the program?
class Test { public static void main(String [] args) { int x=20; String sup = (x < 15) ? "small" : (x < 22)? "tiny" :

"huge"; System.out.println(sup); } }

A.small C. huge Answer & Explanation Answer: Option B Explanation:

B. tiny D.Compilation fails

This is an example of a nested ternary operator. The second evaluation (x < 22) is true, so the "tiny" value is assigned to sup. View Answer Workspace Report Discuss in Forum 62. What will be the output of the program?
class Test { public static void main(String [] args) { int x= 0; int y= 0; for (int z = 0; z < 5; z++) { if (( ++x > 2 ) && (++y > 2)) { x++; } } System.out.println(x + " " + y); } }

A.5 2 C. 6 3 Answer & Explanation Answer: Option C Explanation:

B. 5 3 D.6 4

In the first two iterations x is incremented once and y is not because of the short circuit && operator. In the third and forth iterations x and y are each incremented, and in the fifth iteration x is doubly incremented and y is incremented. View Answer Workspace Report Discuss in Forum 63. What will be the output of the program?
class Test { public static void main(String [] args)

{ int x= 0; int y= 0; for (int z = 0; z < 5; z++) { if (( ++x > 2 ) || (++y > 2)) { x++; } } System.out.println(x + " " + y); } }

A.5 3 C. 8 3 Answer & Explanation Answer: Option B Explanation:

B. 8 2 D.8 5

The first two iterations of the for loop both x and y are incremented. On the third iteration x is incremented, and for the first time becomes greater than 2. The short circuit or operator || keeps y from ever being incremented again and x is incremented twice on each of the last three iterations. View Answer Workspace Report Discuss in Forum 64. What will be the output of the program?
class Bitwise { public static void main(String [] args) { int x = 11 & 9; int y = x ^ 3; System.out.println( y | 12 ); } }

A.0 C. 8 Answer & Explanation Answer: Option D Explanation:

B. 7 D.14

The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9. The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The | operator produces a 1 bit when at least one bit is 1; the result of this operation is 14. View Answer Workspace Report Discuss in Forum

65. What will be the output of the program?


class SSBool { public static void main(String [] args) { boolean b1 = true; boolean b2 = false; boolean b3 = true; if ( b1 & b2 | b2 & b3 | b2 ) /* Line 8 */ System.out.print("ok "); if ( b1 & b2 | b2 & b3 | b2 | b1 ) /*Line 10*/ System.out.println("dokey"); } }

A.ok B. dokey C. ok dokey D.No output is produced E. Compilation error Answer & Explanation Answer: Option B Explanation: The & operator has a higher precedence than the | operator so that on line 8 b1 and 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". 66. What will be the output of the program?
class SC2 { public static void main(String [] args) { SC2 s = new SC2(); s.start(); } void start() { int a = 3; int b = 4; System.out.print(" " + 7 System.out.print(a + b); System.out.print(" " + a System.out.print(foo() + System.out.println(a + b } String foo() { return "foo"; } }

+ 2 + " "); + b + " "); a + b + " "); + foo());

A.9 7 7 foo 7 7foo

B. 72 34 34 foo34 34foo C. 9 7 7 foo34 34foo D.72 7 34 foo34 7foo Answer & Explanation Answer: Option D Explanation: Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands. View Answer Workspace Report Discuss in Forum 67. What will be the output of the program?
class Test { static int s; public static void main(String [] args) { Test p = new Test(); p.start(); System.out.println(s); } void start() { int x = 7; twice(x); System.out.print(x + " "); } void twice(int x) { x = x*2; s = x; } }

A.7 7 C. 14 0 Answer & Explanation Answer: Option B Explanation:

B. 7 14 D.14 14

The int x in the twice() method is not the same int x as in the start() method. Start()'s x is not affected by the twice() method. The instance variable s is updated by twice()'s x, which is 14. View Answer Workspace Report Discuss in Forum

68. What will be the output of the program?


class Two { byte x; } class PassO { public static void main(String [] args) { PassO p = new PassO(); p.start(); } void start() { Two t = new Two(); System.out.print(t.x + " "); Two t2 = fix(t); System.out.println(t.x + " " + t2.x); } Two fix(Two tt) { tt.x = 42; return tt; } }

A.null null 42 C. 0 42 42 Answer & Explanation Answer: Option C Explanation:

B. 0 0 42 D.0 0 0

In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0. View Answer Workspace Report Discuss in Forum 69. What will be the output of the program?
class BoolArray { boolean [] b = new boolean[3]; int count = 0; void set(boolean [] x, int i) { x[i] = true; ++count; }

public static void main(String [] args) { BoolArray ba = new BoolArray(); ba.set(ba.b, 0); ba.set(ba.b, 2); ba.test(); } void test() { if ( b[0] && b[1] | b[2] ) count++; if ( b[1] && b[(++count - 2)] ) count += 7; System.out.println("count = " + count); } }

A.count = 0 C. count = 3 Answer & Explanation Answer: Option C Explanation:

B. count = 2 D.count = 4

The reference variables b and x both refer to the same boolean array. count is incremented for each call to the set() method, and once again when the first if test is true. Because of the && short circuit operator, count is not incremented during the second if test. View Answer Workspace Report Discuss in Forum 70. What will be the output of the program?
public class Test { public static void leftshift(int i, int j) { i <<= j; } public static void main(String args[]) { int i = 4, j = 2; leftshift(i, j); System.out.printIn(i); } }

A.2 C. 8 Answer & Explanation Answer: Option B Explanation:

B. 4 D.16

Java only ever passes arguments to a method by value (i.e. a copy of the variable) and never by reference. Therefore the value of the variable i remains unchanged in the main method. If you are clever you will spot that 16 is 4 multiplied by 2 twice, (4 * 2 * 2) = 16. If you had 16 left shifted by three bits then 16 * 2 * 2 * 2 = 128. If you had 128 right shifted by 2 bits then 128 / 2 / 2 = 32. Keeping these points in mind, you don't have to go converting to binary to do the left and right bit shifts. 71.
import java.awt.*; class Ticker extends Component { public static void main (String [] args) { Ticker t = new Ticker(); /* Missing Statements ? */ } }

which two of the following statements, inserted independently, could legally be inserted into missing section of this code? 1. 2. 3. 4. boolean test = (Component instanceof t); boolean test = (t instanceof Ticker); boolean test = t.instanceof(Ticker); boolean test = (t instanceof Component); B. 2 and 3 D.2 and 4

A.1 and 4 C. 1 and 3 Answer & Explanation Answer: Option D Explanation:

(2) is correct because class type Ticker is part of the class hierarchy of t; therefore it is a legal use of the instanceof operator. (4) is also correct because Component is part of the hierarchy of t, because Ticker extends Component. (1) is incorrect because the syntax is wrong. A variable (or null) always appears before the instanceof operator, and a type appears after it. (3) is incorrect because the statement is used as a method (t.instanceof(Ticker);), which is illegal. View Answer Workspace Report Discuss in Forum 72. Which of the following are legal lines of code? 1. 2. 3. 4. int w = (int)888.8; byte x = (byte)1000L; long y = (byte)100; byte z = (byte)100L;

A.1 and 2 B. 2 and 3 C. 3 and 4 D.All statements are correct. Answer & Explanation Answer: Option D Explanation: Statements (1), (2), (3), and (4) are correct. (1) is correct because when a floatingpoint number (a double in this case) is cast to an int, it simply loses the digits after the decimal. (2) and (4) are correct because a long can be cast into a byte. If the long is over 127, it loses its most significant (leftmost) bits. (3) actually works, even though a cast is not necessary, because a long can store a byte. View Answer Workspace Report Discuss in Forum 73. Which two statements are equivalent? 1. 2. 3. 4. 16*4 16>>2 16/2^2 16>>>2 B. 2 and 4 D.1 and 3

A.1 and 2 C. 3 and 4 Answer & Explanation Answer: Option B Explanation: (2) is correct. 16 >> 2 = 4 (4) is correct. 16 >>> 2 = 4 (1) is wrong. 16 * 4 = 64 (3) is wrong. 16/2 ^ 2 = 10

View Answer Workspace Report Discuss in Forum 74. Which two statements are equivalent? 1. 3/2

2. 3<2 3. 3*4 4. 3<<2 A.1 and 2 C. 3 and 4 Answer & Explanation Answer: Option C Explanation: (1) is wrong. 3/2 = 1 (integer arithmetic). (2) is wrong. 3 < 2 = false. (3) is correct. 3 * 4 = 12. (4) is correct. 3 <<2= 12. In binary 3 is 11, now shift the bits two places to the left and we get 1100 which is 12 in binary (3*2*2). View Answer Workspace Report Discuss in Forum 75. import java.awt.Button;
class CompareReference { public static void main(String [] args) { float f = 42.0f; float [] f1 = new float[2]; float [] f2 = new float[2]; float [] f3 = f1; long x = 42; f1[0] = 42.0f; } }

B. 2 and 3 D.1 and 4

which three statements are true? 1. 2. 3. 4. 5. f1 == f2 f1 == f3 f2 == f1[1] x == f1[0] f == f1[0] B. 2, 4 and 5 D.1, 4 and 5

A.1, 2 and 3 C. 3, 4 and 5 Answer & Explanation Answer: Option B Explanation:

(2) is correct because the reference variables f1 and f3 refer to the same array object. (4) is correct because it is legal to compare integer and floating-point types. (5) is correct because it is legal to compare a variable with an array element. (3) is incorrect because f2 is an array object and f1[1] is an array element. 76. Which two are equal? 1. 2. 3. 4. 5. 32/4 (8 >> 2) << 4 2^5 128 >>> 2 2 >> 5 B. 2 and 4 D.2 and 3

A.1 and 2 C. 1 and 3 Answer & Explanation Answer: Option B Explanation:

(2) and (4) are correct. (2) and (4) both evaluate to 32. (2) is shifting bits right then left using the signed bit shifters >> and <<. (4) is shifting bits using the unsigned operator >>>, but since the beginning number is positive the sign is maintained. (1) evaluates to 8, (3) looks like 2 to the 5th power, but ^ is the Exclusive OR operator so (3) evaluates to 7. (5) evaluates to 0 (2 >> 5 is not 2 to the 5th). 77. public void foo( boolean a, boolean b)
{ if( a ) { System.out.println("A"); /* Line 5 */ } else if(a && b) /* Line 7 */ { System.out.println( "A && B"); } else /* Line 11 */ { if ( !b ) { System.out.println( "notB") ; } else { System.out.println( "ELSE" ) ; } } }

A.If a is true and b is true then the output is "A && B"

B. If a is true and b is false then the output is "notB" C. If a is false and b is true then the output is "ELSE" D.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 78. 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 B. 2 and 4 D.4 and 6

A.1 and 3 C. 3 and 5 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 79. 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.Compilation fails. B. "odd" will always be output. C. "even" will always be output. D."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 80. 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.There is a syntax error on line 1. B. There are syntax errors on lines 1 and 6. C. There are syntax errors on lines 1, 6, and 8. D.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. 81. 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.j = -1 C. j = 1 Answer & Explanation Answer: Option D Explanation:

B. j = 0 D.Compilation fails.

The case statement takes only a single argument. The case statement on line 4 is given two arguments so the compiler complains. View Answer Workspace Report Discuss in Forum 82. What will be the output of the program?
int i = 1, j = 10; do { if(i > j) { break; } j--; } while (++i < 5); System.out.println("i = " + i + " and j = " + j);

A.i = 6 and j = 5 C. i = 6 and j = 4 Answer & Explanation Answer: Option D Explanation:

B. i = 5 and j = 5 D.i = 5 and j = 6

This loop is a do-while loop, which always executes the code block within the block at least once, due to the testing condition being at the end of the loop, rather than at

the beginning. This particular loop is exited prematurely if i becomes greater than j. The order is, test i against j, if bigger, it breaks from the loop, decrements j by one, and then tests the loop condition, where a pre-incremented by one i is tested for being lower than 5. The test is at the end of the loop, so i can reach the value of 5 before it fails. So it goes, start: 1, 10 2, 9 3, 8 4, 7 5, 6 loop condition fails. View Answer Workspace Report Discuss in Forum 83. What will be the output of the program?
public class Switch2 { final static short x = 2; public static int y = 0; public static void main(String [] args) { for (int z=0; z < 3; z++) { switch (z) { case x: System.out.print("0 "); case x-1: System.out.print("1 "); case x-2: System.out.print("2 "); } } } }

A.0 1 2 C. 2 1 0 1 0 0 Answer & Explanation Answer: Option D Explanation:

B. 0 1 2 1 2 2 D.2 1 2 0 1 2

The case expressions are all legal because x is marked final, which means the expressions can be evaluated at compile time. In the first iteration of the for loop case x-2 matches, so 2 is printed. In the second iteration, x-1 is matched so 1 and 2 are printed (remember, once a match is found all remaining statements are executed until a break statement is encountered). In the third iteration, x is matched. So 0 1 and 2 are printed.

View Answer Workspace Report Discuss in Forum 84. What will be the output of the program?
public class SwitchTest { public static void main(String[] args) { System.out.println("value =" + switchIt(4)); } public static int switchIt(int x) { int j = 1; switch (x) { case l: j++; case 2: j++; case 3: j++; case 4: j++; case 5: j++; default: j++; } return j + x; } }

A.value = 2 C. value = 6 Answer & Explanation Answer: Option D Explanation:

B. value = 4 D.value = 8

Because there are no break statements, once the desired result is found, the program continues though each of the remaining options. View Answer Workspace Report Discuss in Forum 85. What will be the output of the program?
public class If2 { static boolean b1, b2; public static void main(String [] args) { int x = 0; if ( !b1 ) /* Line 7 */ { if ( !b2 ) /* Line 9 */ { b1 = true; x++; if ( 5 > 6 ) { x++; } if ( !b1 )

x = else if x = else if x =

x ( x ( x

+ 10; b2 = true ) /* Line 19 */ + 100; b1 | b2 ) /* Line 21 */ + 1000;

} } System.out.println(x); } }

A.0 C. 101 Answer & Explanation Answer: Option C Explanation:

B. 1 D.111

As instance variables, b1 and b2 are initialized to false. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. 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). Since line 19 was successful, subsequent else-if's (line 21) will be skipped. 86. What will be the output of the program?
public class Switch2 { final static short x = 2; public static int y = 0; public static void main(String [] args) { for (int z=0; z < 3; z++) { switch (z) { case y: System.out.print("0 "); /* Line 11 */ case x-1: System.out.print("1 "); /* Line 12 */ case x: System.out.print("2 "); /* Line 13 */ } } } }

A.0 1 2 B. 0 1 2 1 2 2 C. Compilation fails at line 11. D.Compilation fails at line 12. Answer & Explanation Answer: Option C Explanation: Case expressions must be constant expressions. Since x is marked final, lines 12 and 13 are legal; however y is not a final so the compiler will fail at line 11.

View Answer Workspace Report Discuss in Forum 87. What will be the output of the program?
public class If1 { static boolean b; public static void main(String [] args) { short hand = 42; if ( hand < 50 & !b ) /* Line 7 */ hand++; if ( hand > 50 ); /* Line 9 */ else if ( hand > 40 ) { hand += 7; hand++; } else --hand; System.out.println(hand); } }

A.41 C. 50 Answer & Explanation Answer: Option D Explanation:

B. 42 D.51

In Java, boolean instance variables are initialized to false, so the if test on line 7 is true and hand is incremented. Line 9 is legal syntax, a do nothing statement. The else-if is true so hand has 7 added to it and is then incremented. View Answer Workspace Report Discuss in Forum 88. What will be the output of the program?
public class Test { public static void main(String [] args) { int I = 1; do while ( I < 1 ) System.out.print("I is " + I); while ( I > 1 ) ; } }

A.I is 1 B. I is 1 I is 1 C. No output is produced. D.Compilation error Answer & Explanation

Answer: Option C Explanation: There are two different looping constructs in this problem. The first is a do-while loop and the second is a while loop, nested inside the do-while. The body of the dowhile is only a single statement-brackets are not needed. You are assured that the while expression will be evaluated at least once, followed by an evaluation of the do-while expression. Both expressions are false and no output is produced. View Answer Workspace Report Discuss in Forum 89. What will be the output of the program?
int x = l, y = 6; while (y--) { x++; } System.out.println("x = " + x +" y = " + y);

A.x = 6 y = 0 C. x = 6 y = -1 Answer & Explanation Answer: Option D Explanation:

B. x = 7 y = 0 D.Compilation fails.

Compilation fails because the while loop demands a boolean argument for it's looping condition, but in the code, it's given an int argument. while(true) { //insert code here } View Answer Workspace Report Discuss in Forum 90. What will be the output of the program?
int I = 0; outer: while (true) { I++; inner: for (int j = 0; j < 10; j++) { I += j; if (j == 3) continue inner; break outer; } continue outer; } System.out.println(I);

A.1 C. 3 Answer & Explanation Answer: Option A Explanation:

B. 2 D.4

The program flows as follows: I will be incremented after the while loop is entered, then I will be incremented (by zero) when the for loop is entered. The if statement evaluates to false, and the continue statement is never reached. The break statement tells the JVM to break out of the outer loop, at which point I is printed and the fragment is done. 91. What will be the output of the program?
for (int i = 0; i < 4; i += 2) { System.out.print(i + " "); } System.out.println(i); /* Line 5 */

A.0 2 4 C. 0 1 2 3 4 Answer & Explanation Answer: Option D Explanation:

B. 0 2 4 5 D.Compilation fails.

Compilation fails on the line 5 - System.out.println(i); as the variable i has only been declared within the for loop. It is not a recognised variable outside the code block of loop. View Answer Workspace Report Discuss in Forum 92. What will be the output of the program?
int x = 3; int y = 1; if (x = y) /* Line 3 */ { System.out.println("x =" + x); }

A.x = 1 B. x = 3 C. Compilation fails. D.The code runs with no output. Answer & Explanation Answer: Option C

Explanation: Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails. View Answer Workspace Report Discuss in Forum 93. What will be the output of the program?
Float f = new Float("12"); switch (f) { case 12: System.out.println("Twelve"); case 0: System.out.println("Zero"); default: System.out.println("Default"); }

A.Zero C. Default Answer & Explanation Answer: Option D Explanation:

B. Twelve D.Compilation fails

The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails. View Answer Workspace Report Discuss in Forum 94. What will be the output of the program?
int i = O; while(1) { if(i == 4) { break; } ++i; } System.out.println("i = " + i);

A.i = 0 C. i = 4 Answer & Explanation Answer: Option D Explanation:

B. i = 3 D.Compilation fails.

Compilation fails because the argument of the while loop, the condition, must be of primitive type boolean. In Java, 1 does not represent the true state of a boolean,

rather it is seen as an integer. View Answer Workspace Report Discuss in Forum 95. What will be the output of the program?
public class Delta { static boolean foo(char c) { System.out.print(c); return true; } public static void main( String[] argv ) { int i = 0; for (foo('A'); foo('B') && (i < 2); foo('C')) { i++; foo('D'); } } }

A.ABDCBDCB B. ABCDABCD C. Compilation fails. D.An exception is thrown at runtime. 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. The loop will only initialise that once. '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. 'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop. Here ends the first loop. Again 'B' is printed as part of the loop test. 'D' is printed as it is in the loop. 'C' is printed as it 'increments' at the end of each loop. Again 'B' is printed as part of the loop test. At this point the test fails because the other part of the test (i < 2) is no longer true. i has been increased in value by 1 for each loop with the line: i++; This results in a printout of ABDCBDCB

96. What will be the output of the program?


for(int i = 0; i < 3; i++) { switch(i) { case 0: break; case 1: System.out.print("one "); case 2: System.out.print("two "); case 3: System.out.print("three "); } } System.out.println("done");

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

A.0

B. 2

C. 4 Answer & Explanation Answer: Option D Explanation:

D.6

Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. The result is j = 6. View Answer Workspace Report Discuss in Forum 98. What will be the output of the program?
boolean bool = true; if(bool = false) /* Line 2 */ { System.out.println("a"); } else if(bool) /* Line 6 */ { System.out.println("b"); } else if(!bool) /* Line 10 */ { System.out.println("c"); /* Line 12 */ } else { System.out.println("d"); }

A.a C. c Answer & Explanation Answer: Option C Explanation:

B. b D.d

Look closely at line 2, is this an equality check (==) or an assignment (=). The condition at line 2 evaluates to false and also assigns false to bool. bool is now false so the condition at line 6 is not true. The condition at line 10 checks to see if bool is not true ( if !(bool == true) ), it isn't so line 12 is executed. View Answer Workspace Report Discuss in Forum 99. What will be the output of the program?
public class Switch2 { final static short x = 2; public static int y = 0; public static void main(String [] args) {

for (int z=0; z < 4; z++) { switch (z) { case x: System.out.print("0 "); default: System.out.print("def "); case x-1: System.out.print("1 "); break; case x-2: System.out.print("2 "); } } } }

A.0 def 1 C. 2 1 0 def def Answer & Explanation Answer: Option D Explanation:

B. 2 1 0 def 1 D.2 1 0 def 1 def 1

When z == 0 , case x-2 is matched. When z == 1, case x-1 is matched and then the break occurs. When z == 2, case x, then default, then x-1 are all matched. When z == 3, default, then x-1 are matched. The rules for default are that it will fall through from above like any other case (for instance when z == 2), and that it will match when no other cases match (for instance when z==3). View Answer Workspace Report Discuss in Forum 100. What will be the output of the program?
int i = 0, j = 5; tp: for (;;) { i++; for (;;) { if(i > --j) { break tp; } } System.out.println("i =" + i + ", j = " + j);

A.i = 1, j = 0 C. i = 3, j = 4 Answer & Explanation Answer: Option D Explanation:

B. i = 1, j = 4 D.Compilation fails.

If you examine the code carefully you will notice a missing curly bracket at the end of the code, this would cause the code to fail.

101. What will be the output of the program?


int I = 0; label: if (I < 2) { System.out.print("I is " + I); I++; continue label; }

A.I is 0 B. I is 0 I is 1 C. Compilation fails. D.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. If this syntax were legal, the combination of the continue and the if statements would create a kludgey kind of loop, but the compiler will force you to write cleaner code than this. 102. What will be the output of the program?
public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } }

A.Finally B. Compilation fails. C. The code runs with no output. D.An exception is thrown at runtime. Answer & Explanation Answer: Option A Explanation: If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

1. 2. 3. 4.

An exception arising in the finally block itself. The death of the thread. The use of System.exit() Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown. View Answer Workspace Report Discuss in Forum 103. What will be the output of the program?
try { int x = 0; int y = 5 / x; } catch (Exception e) { System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished");

A.finished C. Compilation fails. Answer & Explanation Answer: Option C Explanation:

B. Exception D.Arithmetic Exception

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class. If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses). View Answer Workspace Report Discuss in Forum 104. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A");

} catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error(); /* Line 22 */ } }

A.ABCD B. Compilation fails. C. C is printed before exiting with an error message. D.BC is printed before exiting with an error message. 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. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error). View Answer Workspace Report Discuss in Forum 105. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) /* Line 10 */ { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E");

} public static void badMethod() { throw new RuntimeException(); } }

A.BD C. BDE Answer & Explanation Answer: Option C Explanation:

B. BCD D.BCDE

A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught. View Answer Workspace Report Discuss in Forum 106. What will be the output of the program?
public class RTExcept { public static void throwit () { System.out.print("throwit "); throw new RuntimeException(); } public static void main(String [] args) { try { System.out.print("hello "); throwit(); } catch (Exception re ) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("after "); } }

A.hello throwit caught B. Compilation fails C. hello throwit RuntimeException caught after D.hello throwit caught finally after Answer & Explanation Answer: Option D Explanation:

The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal. A, B and C are incorrect based on the program logic described above. Remember that properly handled exceptions do not cause the program to stop executing. 107. 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.out.print("finally "); /* Line 11 */ } } public static void main(String args[]) { try { aMethod(); } catch (Exception e) /* Line 20 */ { System.out.print("exception "); } System.out.print("finished"); /* Line 24 */ } }

A.finally B. exception finished C. finally exception finished D.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 throw statement (line 7). (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). (3) The finally block completes normally, and then the try statement completes

abruptly because of the throw statement (line 7). (4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20). This prints "exception". (5) Lastly program execution continues, because the exception has been caught, and "finished" is output (line 24). View Answer Workspace Report Discuss in Forum 108. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() {} }

A.AC C. ACD Answer & Explanation Answer: Option C Explanation:

B. BC D.ABCD

There is no exception thrown, so all the code with the exception of the catch statement block is run. View Answer Workspace Report Discuss in Forum 109. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); /* Line 7 */

System.out.print("A"); } catch (Exception ex) /* Line 10 */ { System.out.print("B"); /* Line 12 */ } finally /* Line 14 */ { System.out.print("C"); /* Line 16 */ } System.out.print("D"); /* Line 18 */ } public static void badMethod() { throw new RuntimeException(); } }

A.AB C. ABC Answer & Explanation Answer: Option D Explanation:

B. BC D.BCD

(1) A RuntimeException is thrown, this is a subclass of exception. (2) The exception causes the try to complete abruptly (line 7) therefore line 8 is never executed. (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). (5) The exception was caught, so the program continues with line 18 and outputs "D". View Answer Workspace Report Discuss in Forum 110. What will be the output of the program?
public class MyProgram { public static void main(String args[]) { try { System.out.print("Hello world "); } finally { System.out.println("Finally executing "); } } }

A.Nothing. The program will not compile because no exceptions are specified.

B. Nothing. The program will not compile because no catch clauses are specified. C. Hello world. D.Hello world Finally executing Answer & Explanation Answer: Option D Explanation: Finally clauses are always executed. The program will first execute the try block, printing Hello world, and will then execute the finally block, printing Finally executing. Option A, B, and C are incorrect based on the program logic described above. Remember that either a catch or a finally statement must follow a try. Since the finally is present, the catch is not required. View Answer Workspace Report Discuss in Forum 111. 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(); /* Line 9 */ } catch (Exc0 e0) /* Line 11 */ { System.out.println("Ex0 caught"); } catch (Exception e) { System.out.println("exception caught"); } } }

A.Ex0 caught B. exception caught C. Compilation fails because of an error at line 2. D.Compilation fails because of an error at line 9. Answer & Explanation Answer: Option A Explanation: An exception Exc1 is thrown and is caught by the catch statement on line 11. The code is executed in this block. There is no finally block of code to execute.

112. import java.io.*;


public class MyProgram { public static void main(String args[]) { FileOutputStream out = null; try { out = new FileOutputStream("test.txt"); out.write(122); } catch(IOException io) { System.out.println("IO Error."); } finally { out.close(); } } }

and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true? A.This program will compile successfully. B. This program fails to compile due to an error at line 4. C. This program fails to compile due to an error at line 6. D.This program fails to compile due to an error at line 13. Answer & Explanation Answer: Option D Explanation: Any method (in this case, the main() method) that throws a checked exception (in this case, out.close() ) must be called within a try clause, or the method must declare that it throws the exception. Either main() must declare that it throws an exception, or the call to out.close() in the finally block must fall inside a (in this case nested) try-catch block. View Answer Workspace Report Discuss in Forum 113. public class MyProgram
{ public static void throwit() { throw new RuntimeException(); } public static void main(String args[]) { try { System.out.println("Hello world "); throwit(); System.out.println("Done with try block "); } finally

{ System.out.println("Finally executing "); } } }

which answer most closely indicates the behavior of the program? A.The program will not compile. The program will print Hello world, then will print that a RuntimeException has B. occurred, then will print Done with try block, and then will print Finally executing. The program will print Hello world, then will print that a RuntimeException has C. occurred, and then will print Finally executing. The program will print Hello world, then will print Finally executing, then will D. print that a RuntimeException has occurred. Answer & Explanation Answer: Option D Explanation: Once the program throws a RuntimeException (in the throwit() method) that is not caught, the finally block will be executed and the program will be terminated. If a method does not handle an exception, the finally block is executed before the exception is propagated. View Answer Workspace Report Discuss in Forum 114. public class ExceptionTest
{ class TestException extends Exception {} public void runTest() throws TestException {} public void test() /* Point X */ { runTest(); } }

At Point X on line 5, which code is necessary to make the code compile? A.No code is necessary. B. throws Exception C. catch ( Exception e ) D.throws RuntimeException Answer & Explanation Answer: Option B Explanation: Option B is correct. This works because it DOES throw an exception if an error occurs. Option A is wrong. 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. Option C is wrong. The catch statement belongs in a method body not a method specification. Option D is wrong. TestException is a subclass of Exception therefore the test method, in this example, must throw TestException or some other class further up the Exception tree. Throwing RuntimeException is just not on as this belongs in the java.lang.RuntimeException branch (it is not a superclass of TestException). The compiler complains with the same error as in A above. View Answer Workspace Report Discuss in Forum 115. System.out.print("Start ");
try { System.out.print("Hello world"); throw new FileNotFoundException(); } System.out.print(" Catch Here "); /* Line 7 */ catch(EOFException e) { System.out.print("End of file exception"); } catch(FileNotFoundException e) { System.out.print("File not found"); }

and given that EOFException and FileNotFoundException are both subclasses of IOException, and further assuming this block of code is placed into a class, which statement is most true concerning this code? A.The code will not compile. B. Code output: Start Hello world File Not Found. C. Code output: Start Hello world End of file exception. D.Code output: Start Hello world Catch Here File not found. Answer & Explanation Answer: Option A Explanation: Line 7 will cause a compiler error. The only legal statements after try blocks are either catch or finally statements. Option B, C, and D are incorrect based on the program logic described above. If line 7 was removed, the code would compile and the correct answer would be Option B. View Answer Workspace Report Discuss in Forum 116. Which statement is true? A.catch(X x) can catch subclasses of X where X is a subclass of Exception. B. The Error class is a RuntimeException.

C. Any statement that can throw an Error must be enclosed in a try block. D.Any statement that can throw an Exception must be enclosed in a try block. Answer & Explanation Answer: Option A Explanation: Option A is correct. If the class specified in the catch clause does have subclasses, any exception object that subclasses the specified class will be caught as well. Option B is wrong. The error class is a subclass of Throwable and not Runtime Exception. Option C is wrong. You do not catch this class of error. Option D is wrong. An exception can be thrown to the next method higher up the call stack. 117. Which four can be thrown using the throw statement? 1. 2. 3. 4. 5. 6. Error Event Object Throwable Exception RuntimeException B. 2, 3, 4 and 5 D.2, 4, 5 and 6

A.1, 2, 3 and 4 C. 1, 4, 5 and 6 Answer & Explanation Answer: Option C Explanation:

The (1), (4), (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. The Throwable class is the superclass of all errors and exceptions in the Java language. 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.

View Answer Workspace Report Discuss in Forum 118. Which statement is true? A.A try statement must have at least one corresponding catch block. B. Multiple catch statements can catch the same class of exception more than once. An Error that might be thrown in a method must be declared as thrown by that C. method, or be handled within that method. Except in case of VM shutdown, if a try block starts to execute, a corresponding D. finally block will always start to execute. Answer & Explanation Answer: Option D Explanation: A is wrong. A try statement can exist without catch, but it must have a finally statement. B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch block completes normally, then the try statement completes normally. C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked exceptions (java.lang.Exception) have to be caught. However, speaking of Exceptions, Exceptions do not have to be handled in the same method as the throw statement. They can be passed to another method. If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: 1. 2. 3. 4. An exception arising in the finally block itself. The death of the thread. The use of System.exit() Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown. 119. 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.TreeMap B. HashMap C. LinkedHashMap D.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 new LinkedHashMap. 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 120. Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object? A.java.lang.String B. java.lang.Double C. java.lang.StringBuffer D.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 121. 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.java.util.HashSet B. java.util.LinkedHashSet C. java.util.List D.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 ArrayList functionality and has synchronized methods; it is slower than ArrayList. View Answer Workspace Report Discuss in Forum 122. 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.java.util.Map B. java.util.Set C. java.util.List D.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 key-value 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 123. Which interface does java.util.Hashtable implement? A.Java.util.Map B. Java.util.List C. Java.util.HashTable D.Java.util.Collection Answer & Explanation

Answer: Option A Explanation: Hash table based implementation of the Map interface. 124 Which interface provides the capability to store objects using a key-value pair? B. Java.util.Set . A.Java.util.Map C. Java.util.List D.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 125. Which collection class allows you to associate its elements with key values, and allows you to retrieve objects in FIFO (first-in, first-out) sequence? A.java.util.ArrayList B. java.util.LinkedHashMap C. java.util.HashMap D.java.util.TreeMap Answer & Explanation Answer: Option B Explanation: LinkedHashMap is the collection class used for caching purposes. FIFO is another way to indicate caching behavior. To retrieve LinkedHashMap elements in cached order, use the values() method and iterate over the resultant collection. View Answer Workspace Report Discuss in Forum 126. Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization? A.java.util.SortedMap B. java.util.TreeMap C. java.util.TreeSet D.java.util.Hashtable Answer & Explanation Answer: Option D Explanation: Hashtable is the only class listed that provides synchronized methods. If you need synchronization great; otherwise, use HashMap, it's faster.

View Answer Workspace Report Discuss in Forum 127. Which is valid declaration of a float? A.float f = 1F; C. float f = "1"; Answer & Explanation Answer: Option A Explanation: Option A is valid declaration of float. 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. 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.e there might be a loss of precision. View Answer Workspace Report Discuss in Forum 128. /* Missing Statement ? */
public class foo { public static void main(String[]args)throws Exception { java.io.PrintWriter out = new java.io.PrintWriter(); new java.io.OutputStreamWriter(System.out,true); out.println("Hello"); } }

B. float f = 1.0; D.float f = 1.0d;

What line of code should replace the missing statement to make this program compile? A.No statement required. B. import java.io.*; C. include java.io.*; D.import java.io.PrintWriter; 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. 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. 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.io" then the class name in the long run leading to a lot more typing.

129 What is the numerical range of char? A.0 to 32767 C. -256 to 255 Answer & Explanation Answer: Option B Explanation:

B. 0 to 65535 D.-32768 to 32767

The char type is integral but unsigned. The range of a variable of type char is from 0 to 216-1 or 0 to 65535. Java characters are Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant nine bits of a char are 0, then the encoding is the same as seven-bit ASCII. View Answer Workspace Report Discuss in Forum 130. Which of the following are Java reserved words? 1. 2. 3. 4. run import default implement B. 2 and 3 D.2 and 4

A.1 and 2 C. 3 and 4 Answer & Explanation Answer: Option B Explanation: (2) - This is a Java keyword (3) - This is a Java keyword

(1) - Is incorrect because although it is a method of Thread/Runnable it is not a keyword (4) - This is not a Java keyword the keyword is implements 131. What will be the output of the program?
public class Test { public static void main (String[] args) { String foo = args[1]; String bar = args[2]; String baz = args[3];

System.out.println("baz = " + baz); /* Line 8 */ } }

And the command line invocation: > java Test red green blue A.baz = C. baz = blue Answer & Explanation Answer: Option D Explanation: When running the program you entered 3 arguments "red", "green" and "blue". When dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes "red", args[1] becomes "green" and args[2] becomes "blue". 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. View Answer Workspace Report Discuss in Forum 132 What will be the output of the program?
public class Test { public static void main (String args[]) { String str = NULL; System.out.println(str); } }

B. baz = null D.Runtime Exception

A.NULL B. Compile Error C. Code runs but no output D.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". View Answer Workspace Report Discuss in Forum

133 What will be the output of the program?


package foo; import java.util.Vector; /* Line 2 */ private class MyVector extends Vector { int i = 1; /* Line 5 */ public MyVector() { i = 2; } } public class MyNewVector extends MyVector { public MyNewVector () { i = 4; /* Line 15 */ } public static void main (String args []) { MyVector v = new MyNewVector(); /* Line 19 */ } }

A.Compilation will succeed. B. Compilation will fail at line 3. C. Compilation will fail at line 5. D.Compilation will fail at line 15. Answer & Explanation Answer: Option B Explanation: Option B is correct. The compiler complains with the error "modifier private not allowed here". The class is created private and is being used by another class on line 19. View Answer Workspace Report Discuss in Forum 134. What will be the output of the program?
public class Test { private static int[] x; public static void main(String[] args) { System.out.println(x[0]); } }

A.0 B. null C. Compile Error D.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. the new statement is missing, for example: private static int[]x = new int[5]; private static int[x] declares a static i.e. class level array. the "new" keyword is the word that actually creates said array. int[5] in association with the new sets the size of the array. 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. View Answer Workspace Report Discuss in Forum 135. What will be the output of the program?
import java.util.*; class I { public static void main (String[] args) { Object i = new ArrayList().iterator(); System.out.print((i instanceof List)+","); System.out.print((i instanceof Iterator)+","); System.out.print(i instanceof ListIterator); } }

A.Prints: false, false, false B. Prints: false, false, true C. Prints: false, true, false D.Prints: false, true, true Answer & Explanation Answer: Option C Explanation: The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn't return a List or a ListIterator object. A ListIterator can be obtained by invoking the listIterator method. 136. What will be the output of the program?
public class Test

{ private static float[] f = new float[2]; public static void main (String[] args) { System.out.println("f[0] = " + f[0]); } }

A.f[0] = 0 C. Compile Error Answer & Explanation Answer: Option B Explanation:

B. f[0] = 0.0 D.Runtime Exception

The choices are between Option A and B, what this question is really testing is your knowledge of default values of an initialized array. This is an array type float i.e. 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 137. What will be the output of the program?
import java.util.*; class H { public static void main (String[] args) { Object x = new Vector().elements(); System.out.print((x instanceof Enumeration)+","); System.out.print((x instanceof Iterator)+","); System.out.print(x instanceof ListIterator); } }

A.Prints: false,false,false B. Prints: false,false,true C. Prints: false,true,false D.Prints: true,false,false Answer & Explanation Answer: Option D Explanation: The Vector.elements method returns an Enumeration over the elements of the vector. Vector implements the List interface and extends AbstractList so it is also possible to get an Iterator over a Vector by invoking the iterator or listIterator method. View Answer Workspace Report Discuss in Forum

138. What will be the output of the program?


TreeSet map = new TreeSet(); map.add("one"); map.add("two"); map.add("three"); map.add("four"); map.add("one"); Iterator it = map.iterator(); while (it.hasNext() ) { System.out.print( it.next() + " " ); }

A.one two three four B. four three two one C. four one three two D.one two three four one Answer & Explanation Answer: Option C Explanation: TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which typically means alphabetical. View Answer Workspace Report Discuss in Forum 139. What will be the output of the program?
public static void main(String[] args) { Object obj = new Object() { public int hashCode() { return 42; } }; System.out.println(obj.hashCode()); }

A.42 B. Runtime Exception C. Compile Error at line 2 D.Compile Error at line 5 Answer & Explanation Answer: Option A Explanation: This code is an example of an anonymous inner class. They can be declared to extend another class or implement a single interface. Since they have no name you

can not use the "new" keyword on them. In this case the annoynous class is extending the Object class. Within the {} you place the methods you want for that class. After this class has been declared its methods can be used by that object in the usual way e.g. objectname.annoymousClassMethod() 140. class Test1
{ public int value; public int hashCode() { return 42; } } class Test2 { public int value; public int hashcode() { return (int)(value^5); } }

which statement is true? A.class Test1 will not compile. The Test1 hashCode() method is more efficient than the Test2 hashCode() B. method. The Test1 hashCode() method is less efficient than the Test2 hashCode() C. method. D.class Test2 will not compile. Answer & Explanation Answer: Option C Explanation: The so-called "hashing algorithm" implemented by class Test1 will always return the same value, 42, which is legal but which will place all of the hash table entries into a single bucket, the most inefficient setup possible. Option A and D are incorrect because these classes are legal. Option B is incorrect based on the logic described above. View Answer Workspace Report Discuss in Forum 141. Which statement is true for the class java.util.HashSet? A.The elements in the collection are ordered. B. The collection is guaranteed to be immutable. C. The elements in the collection are guaranteed to be unique. D.The elements in the collection are accessed using a unique key. Answer & Explanation Answer: Option C Explanation: Option C is correct. HashSet implements the Set interface and the Set interface

specifies collection that contains no duplicate elements. Option A is wrong. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. Option B is wrong. The set can be modified. Option D is wrong. This is a Set and not a Map. View Answer Workspace Report Discuss in Forum 142. Which of the following statements about the hashcode() method are incorrect? 1. The value returned by hashcode() is used in some collection classes to help locate objects. 2. The hashcode() method is required to return a positive int value. 3. The hashcode() method in the String class is the one inherited from Object. 4. Two new empty String objects will produce identical hashcodes. A.1 and 2 C. 3 and 4 Answer & Explanation Answer: Option B Explanation: (2) is an incorrect statement because there is no such requirement. (3) is an incorrect statement and therefore a correct answer because the hashcode for a string is computed from the characters in the string. View Answer Workspace Report Discuss in Forum 143. What two statements are true about properly overridden hashCode() and equals() methods? 1. hashCode() doesn't have to be overridden if equals() is. 2. equals() doesn't have to be overridden if hashCode() is. 3. hashCode() can always return the same value, regardless of the object that invoked it. 4. equals() can be true even if it's comparing different objects. A.1 and 2 C. 3 and 4 Answer & Explanation Answer: Option C B. 2 and 3 D.1 and 3 B. 2 and 3 D.1 and 4

Explanation: (3) and (4) are correct. (1) and (2) are incorrect because by contract hashCode() and equals() can't be overridden unless both are overridden. View Answer Workspace Report Discuss in Forum 144. Which two statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? 1. If the equals() method returns true, the hashCode() comparison == must return true. 2. If the equals() method returns false, the hashCode() comparison != must return true. 3. If the hashCode() comparison == returns true, the equals() method must return true. 4. If the hashCode() comparison == returns true, the equals() method might return true. A.1 and 4 C. 3 and 4 Answer & Explanation Answer: Option A Explanation: (1) is a restatement of the equals() and hashCode() contract. (4) is true because if the hashCode() comparison returns ==, the two objects might or might not be equal. (2) and (3) are incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. 145. x = 0;
if (x1.hashCode() != x2.hashCode() ) if (x3.equals(x4) ) x = x + 10; if (!x5.equals(x6) ) x = x + 100; if (x7.hashCode() == x8.hashCode() ) System.out.println("x = " + x); x = x + 1;

B. 2 and 3 D.1 and 3

x = x + 1000;

and assuming that the equals() and hashCode() methods are property implemented, if the output is "x = 1111", which of the following statements will always be true? A.x2.equals(x1) B. x3.hashCode() == x4.hashCode() C. x5.hashCode() != x6.hashCode() D.x8.equals(x7) Answer & Explanation

Answer: Option B Explanation: By contract, if two objects are equivalent according to the equals() method, then the hashCode() method must evaluate them to be ==. Option A is incorrect because if the hashCode() values are not equal, the two objects must not be equal. Option C is incorrect because if equals() is not true there is no guarantee of any result from hashCode(). Option D is incorrect because hashCode() will often return == even if the two objects do not evaluate to equals() being true. View Answer Workspace Report Discuss in Forum 146. Which of the following are true statements? 1. The Iterator interface declares only three methods: hasNext, next and remove. 2. The ListIterator interface extends both the List and Iterator interfaces. 3. The ListIterator interface provides forward and backward iteration capabilities. 4. The ListIterator interface provides the ability to modify the List during iteration. 5. The ListIterator interface provides the ability to determine its position in the List. A.2, 3, 4 and 5 C. 3, 4 and 5 Answer & Explanation Answer: Option B Explanation: The ListIterator interface extends the Iterator interface and declares additional methods to provide forward and backward iteration capabilities, List modification capabilities, and the ability to determine the position of the iterator in the List. View Answer Workspace Report Discuss in Forum 147. Which statement is true for the class java.util.ArrayList? A.The elements in the collection are ordered. B. The collection is guaranteed to be immutable. C. The elements in the collection are guaranteed to be unique. D.The elements in the collection are accessed using a unique key. B. 1, 3, 4 and 5 D.1, 2 and 3

Answer & Explanation Answer: Option A Explanation: Yes, always the elements in the collection are ordered. 148. Which is true about an anonymous inner class? A.It can extend exactly one class and implement exactly one interface. B. It can extend exactly one class and can implement multiple interfaces. C. It can extend exactly one class or implement exactly one interface. It can implement multiple interfaces regardless of whether it also extends a D. class. Answer & Explanation Answer: Option C Explanation: Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, 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). Option A, B, D, and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C. View Answer Workspace Report Discuss in Forum 149. class Boo
{ Boo(String s) { } Boo() { } } class Bar extends Boo { Bar() { } Bar(String s) {super(s);} void zoo() { // insert code here } }

which one create an anonymous inner class from within class Bar? A.Boo f = new Boo(24) { }; B. Boo f = new Bar() { }; C. Bar f = new Boo(String s) { }; D.Boo f = new Boo.Bar(String s) { }; 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. 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, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works. Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class. Option C is incorrect because it violates the rules of polymorphismyou cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has. Option D uses incorrect syntax. View Answer Workspace Report Discuss in Forum 150 Which is true about a method-local inner class? A.It must be marked final. B. It can be marked abstract. C. It can be marked public. D.It can be marked static. Answer & Explanation Answer: Option B Explanation: Option B is correct because a method-local inner class can be abstract, 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). 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), or static. View Answer Workspace Report Discuss in Forum 151. Which statement is true about a static nested class? You must have a reference to an instance of the enclosing class in order to A. instantiate it. B. It does not have access to nonstatic members of the enclosing class. C. It's variables and methods must be static. D.It must extend the enclosing class. Answer & Explanation

Answer: Option B Explanation: Option B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class). Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class. Option C is incorrect because static nested classes can declare and define nonstatic members. Option D is wrong because it just is. There's no rule that says an inner or nested class has to extend anything. View Answer Workspace Report Discuss in Forum 152. Which constructs an anonymous inner class instance? A.Runnable r = new Runnable() { }; B. Runnable r = new Runnable(public void run() { }); C. Runnable r = new Runnable { public void run(){}}; D.System.out.println(new Runnable() {public void run() { }}); Answer & Explanation Answer: Option D Explanation: D is correct. It defines an anonymous inner class instance, 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, so it must override the run() method of Runnable. A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation. B and C use incorrect syntax. 153. class Foo
{ class Bar{ } } class Test { public static void main (String [] args) { Foo f = new Foo(); /* Line 10: Missing statement ? */ }

which statement, inserted at line 10, creates an instance of Bar? A.Foo.Bar b = new Foo.Bar(); B. Foo.Bar b = f.new Bar(); C. Bar b = new f.Bar(); D.Bar b = f.new Bar(); 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, then using a reference to the enclosing class to invoke new on the inner class. Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new. C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong. D is incorrect because it doesn't use the enclosing class name in the reference variable declaration. View Answer Workspace Report Discuss in Forum 154. public class MyOuter
{ public static class MyInner { public static void foo() { } } }

which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class? A.MyOuter.MyInner m = new MyOuter.MyInner(); B. MyOuter.MyInner mi = new MyInner(); MyOuter m = new MyOuter(); C. MyOuter.MyInner mi = m.new MyOuter.MyInner(); D.MyInner mi = new MyOuter.MyInner(); Answer & Explanation Answer: Option A Explanation: MyInner is a static nested class, so it must be instantiated using the fully-scoped name of MyOuter.MyInner.

Option B is incorrect because it doesn't use the enclosing name in the new. Option C is incorrect because it uses incorrect syntax. When you instantiate a nested class by invoking new on an instance of the enclosing class, you do not use the enclosing name. 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. Option D is incorrect because it doesn't use the enclosing class name in the variable declaration. 155. What will be the output of the program?
public class Foo { Foo() { System.out.print("foo"); } class Bar { Bar() { System.out.print("bar"); } public void go() { System.out.print("hi"); } } /* class Bar ends */ public static void main (String [] args) { Foo f = new Foo(); f.makeBar(); } void makeBar() { (new Bar() {}).go(); } }/* class Foo ends */

A.Compilation fails. B. An error occurs at runtime. C. It prints "foobarhi" D.It prints "barhi" Answer & Explanation Answer: Option C Explanation: Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints "foo". Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints "bar", and finally the go() method is invoked on the new Bar instance, which means the go() method

prints "hi". View Answer Workspace Report Discuss in Forum 156. What will be the output of the program?
public class HorseTest { public static void main (String [] args) { class Horse { public String name; /* Line 7 */ public Horse(String s) { name = s; } } /* class Horse ends */ Object obj = new Horse("Zippo"); /* Line 13 */ Horse h = (Horse) obj; /* Line 14 */ System.out.println(h.name); } } /* class HorseTest ends */

A.An exception occurs at runtime at line 10. B. It prints "Zippo". C. Compilation fails because of an error on line 7. D.Compilation fails because of an error on line 13. Answer & Explanation Answer: Option B Explanation: The code in the HorseTest class is perfectly legal. Line 13 creates an instance of the method-local inner class Horse, using a reference variable declared as type Object. Line 14 casts the Horse object to a Horse reference variable, which allows line 15 to compile. If line 14 were removed, the HorseTest code would not compile, because class Object does not have a name variable. View Answer Workspace Report Discuss in Forum 157. 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; } } /* Line 11 */

System.out.println(o.equals("Fred")); } }

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

A.57 22 B. 45 38

C. 45 57 D.An exception occurs at runtime. 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. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosing AbstractTest class to tie to the new Bar inner class instance. AbstractTest can't be instantiated because it's abstract, so we created an anonymous subclass (nonabstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance. 159. What is the name of the method used to start a thread execution? A.init(); B. start(); C. run(); D.resume(); Answer & Explanation Answer: Option B Explanation: Option B is Correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Option A is wrong. There is no init() method in the Thread class. Option C is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. Option D is wrong. The resume() method is deprecated. It resumes a suspended thread. View Answer Workspace Report Discuss in Forum 160. Which two are valid constructors for Thread? 1. 2. 3. 4. Thread(Runnable r, String name) Thread() Thread(int priority) Thread(Runnable r, ThreadGroup g)

5. Thread(Runnable r, int priority) A.1 and 3 C. 1 and 2 Answer & Explanation Answer: Option C Explanation: (1) and (2) are both valid constructors for Thread. (3), (4), and (5) are not legal Thread constructors, although (4) is close. If you reverse the arguments in (4), you'd have a valid constructor. View Answer Workspace Report Discuss in Forum 161. Which three are methods of the Object class? 1. 2. 3. 4. 5. 6. 7. 8. notify(); notifyAll(); isInterrupted(); synchronized(); interrupt(); wait(long msecs); sleep(long msecs); yield(); B. 2, 4, 5 D.2, 3, 4 B. 2 and 4 D.2 and 5

A.1, 2, 4 C. 1, 2, 6 Answer & Explanation Answer: Option C Explanation:

(1), (2), and (6) are correct. They are all related to the list of threads waiting on the specified object. (3), (5), (7), and (8) are incorrect answers. The methods isInterrupted() and interrupt() are instance methods of Thread. The methods sleep() and yield() are static methods of Thread. D is incorrect because synchronized is a keyword and the synchronized() construct is part of the Java language. View Answer Workspace Report Discuss in Forum

162. 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.Thread t = new Thread(X); B. Thread t = new Thread(X); t.start(); C. X run = new X(); Thread t = new Thread(run); t.start(); D.Thread t = new Thread(); x.run(); Answer & Explanation Answer: Option C Explanation: Option C is suitable to start a thread. View Answer Workspace Report Discuss in Forum 163. Which cannot directly cause a thread to stop executing? A.Calling the SetPriority() method on a Thread object. B. Calling the wait() method on an object. C. Calling notify() method on an object. D.Calling read() method on an InputStream object. Answer & Explanation Answer: Option C Explanation: Option C is correct. notify() - wakes up a single thread that is waiting on this object's monitor. 164. Which two of the following methods are defined in class Thread? 1. 2. 3. 4. 5. start() wait() notify() run() terminate() B. 2 and 3 D.2 and 4

A.1 and 4 C. 3 and 4 Answer & Explanation Answer: Option A

Explanation: (1) and (4). Only start() and run() are defined by the Thread class. (2) and (3) are incorrect because they are methods of the Object class. (5) is incorrect because there's no such method in any thread-related class. View Answer Workspace Report Discuss in Forum 165. Which three guarantee that a thread will leave the running state? 1. 2. 3. 4. 5. 6. 7. yield() wait() notify() notifyAll() sleep(1000) aLiveThread.join() Thread.killThread() B. 2, 5 and 6 D.4, 5 and 7

A.1, 2 and 4 C. 3, 4 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. (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). (6) is correct because, assuming that the thread you're calling join() on is alive, the thread calling join() will immediately block until the thread you're calling join() on is no longer alive. (1) is wrong, but tempting. The yield() method is not guaranteed to cause a thread to leave the running state, although if there are runnable threads of the same priority as the currently running thread, then the current thread will probably leave the running state. (3) and (4) are incorrect because they don't cause the thread invoking them to leave the running state. (7) is wrong because there's no such method. View Answer Workspace Report Discuss in Forum

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

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

A.After thread A is notified, or after two seconds. B. After the lock on B is released, or after two seconds. C. Two seconds after thread A is notified. D.Two seconds after lock B is released. Answer & Explanation Answer: Option A Explanation: Option A. Either of the two events (notification or wait time expiration) will make the thread become a candidate for running again. Option B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. Option C is incorrect because the thread will become a candidate immediately after notification, not two seconds afterwards. Option D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released. View Answer Workspace Report Discuss in Forum 171. Which of the following will not directly cause a thread to stop? A.notify() B. wait() C. InputStream access D.sleep() Answer & Explanation Answer: Option A Explanation: Option A is correct. notify() - wakes up a single thread that is waiting on this object's monitor. Option B is wrong. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. Option C is wrong. Methods of the InputStream class block until input data is available, the end of the stream is detected, or an exception is thrown. Blocking means that a thread may stop until certain conditions are met. Option D is wrong. sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. The thread does not lose ownership of any monitors. View Answer Workspace Report Discuss in Forum

172. Which class or interface defines the wait(), notify(),and notifyAll() methods? A.Object B. Thread C. Runnable D.Class Answer & Explanation Answer: Option A Explanation: The Object class defines these thread-specific methods. Option B, C, and D are incorrect because they do not define these methods. And yes, the Java API does define a class called Class, though you do not need to know it for the exam. View Answer Workspace Report Discuss in Forum 173. public class MyRunnable implements Runnable
{ public void run() { // some code here } }

which of these will create and start this thread? A.new Runnable(MyRunnable).start(); B. new Thread(MyRunnable).run(); C. new Thread(new MyRunnable()).start(); D.new MyRunnable().start(); Answer & Explanation Answer: Option C Explanation: Because the class implements Runnable, an instance of it has to be passed to the Thread constructor, and then the instance of the Thread has to be started. A is incorrect. There is no constructor like this for Runnable because Runnable is an interface, and it is illegal to pass a class or interface name to any constructor. B is incorrect for the same reason; you can't pass a class or interface name to any constructor. D is incorrect because MyRunnable doesn't have a start() method, and the only start() method that can start a thread of execution is the start() in the Thread class. 174. What will be the output of the program?
class MyThread extends Thread { MyThread()

{ System.out.print(" MyThread"); } public void run() { System.out.print(" bar"); } public void run(String s) { System.out.println(" baz"); } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System.out.println(" foo"); } }; t.start(); } }

A.foo C. MyThread bar Answer & Explanation Answer: Option B Explanation:

B. MyThread foo D.foo bar

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

System.out.print("Thread "); } }

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

A.Prints "Inside Thread Inside Thread" B. Prints "Inside Thread Inside Runnable" C. Does not compile D.Throws exception at runtime Answer & Explanation Answer: Option A

Explanation: If a Runnable object is passed to the Thread constructor, then the run method of the Thread class will invoke the run method of the Runnable object. In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked. Both times, the run() method in MyThread is invoked instead. View Answer Workspace Report Discuss in Forum 177. What will be the output of the program?
class s1 implements Runnable { int x = 0, y = 0; int addX() {x++; return x;} int addY() {y++; return y;} public void run() { for(int i = 0; i < 10; i++) System.out.println(addX() + " " + addY()); } public static void main(String args[]) { s1 run1 = new s1(); s1 run2 = new s1(); Thread t1 = new Thread(run1); Thread t2 = new Thread(run2); t1.start(); t2.start(); } }

A.Compile time Error: There is no start() method B. Will print in this order: 1 1 2 2 3 3 4 4 5 5... C. Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3...) D.Will print in this order: 1 2 3 4 5 6... 1 2 3 4 5 6... Answer & Explanation Answer: Option C Explanation: Both threads are operating on different sets of instance variables. 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; i < 10; i++) System.out.println( Thread.currentThread().getName() + ": " + addX() + " " + addY() );

} View Answer Workspace Report Discuss in Forum 178. What will be the output of the program?
public class Q126 implements Runnable { private int x; private int y; public static void main(String [] args) { Q126 that = new Q126(); (new Thread(that)).start( ); /* Line 8 (new Thread(that)).start( ); /* Line 9 } public synchronized void run( ) /* Line 11 { for (;;) /* Line 13 */ { x++; y++; System.out.println("x = " + x + "y } } }

*/ */ */

= " + y);

A.An error at line 11 causes compilation to fail B. Errors at lines 8 and 9 cause compilation to fail. The program prints pairs of values for x and y that might not always be the same C. on the same line (for example, "x=2, y=1") The program prints pairs of values for x and y that are always the same on the D.same line (for example, "x=1, y=1". In addition, each value appears once (for example, "x=1, y=1" followed by "x=2, y=2") Answer & Explanation Answer: Option D Explanation: The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object. Also note that because of the infinite loop at line 13, only one thread ever gets to execute. 179. What will be the output of the program?
class s1 extends Thread { public void run() { for(int i = 0; i < 3; i++)

{ System.out.println("A"); System.out.println("B"); } } } class Test120 extends Thread { public void run() { for(int i = 0; i < 3; i++) { System.out.println("C"); System.out.println("D"); } } public static void main(String args[]) { s1 t1 = new s1(); Test120 t2 = new Test120(); t1.start(); t2.start(); } }

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

t1.start(); t2.start(); } }

A.DeadLock C. Compilation Error Answer & Explanation Answer: Option B Explanation:

B. It print 12 12 12 12 D.Cannot determine output.

The program will execute without any problems and print 12 12 12 12. View Answer Workspace Report Discuss in Forum 181. What will be the output of the program?
public class ThreadDemo { private int count = 1; public synchronized void doSomething() { for (int i = 0; i < 10; i++) System.out.println(count++); } public static void main(String[] args) { ThreadDemo demo = new ThreadDemo(); Thread a1 = new A(demo); Thread a2 = new A(demo); a1.start(); a2.start(); } } class A extends Thread { ThreadDemo demo; public A(ThreadDemo td) { demo = td; } public void run() { demo.doSomething(); } }

A.It will print the numbers 0 to 19 sequentially B. It will print the numbers 1 to 20 sequentially C. It will print the numbers 1 to 20, but the order cannot be determined D.The code will not compile. Answer & Explanation Answer: Option B

Explanation: 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 182. 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. B. 1 2 3 C. 1 3 D.1 2 Answer & Explanation A. 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

183. 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, whatif anythingcan you add to the preceding code to ensure the integrity of data? A.Synchronize the run method. B. Wrap a synchronize(this) around the call to f.increase(). C. The existing code will cause a runtime exception. D.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 Asynchronizing the code that calls the increase() method does not prevent other code from calling the increase() method. 184. 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.ABBCAD B. ABCBCAD C. CDADACB D.Output determined by the underlying platform. Answer & Explanation Answer: Option D Explanation: Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined. View Answer Workspace Report Discuss in Forum 185. class Test
{ public static void main(String [] args) { printAll(args); } public static void printAll(String[] lines)

{ for(int i = 0; i < lines.length; i++) { System.out.println(lines[i]); Thread.currentThread().sleep(1000); } } }

the static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code? A.Each String in the array lines will output, with a 1-second pause. Each String in the array lines will output, with no pause in between because this B. method is not executed in a Thread. Each String in the array lines will output, and there is no guarantee there will be C. a pause because currentThread() may not retrieve this thread. D.This code will not compile. Answer & Explanation Answer: Option D Explanation: D. The sleep() method must be enclosed in a try/catch block, or the method printAll() must declare it throws the InterruptedException. A is incorrect, but it would be correct if the InterruptedException was dealt with. B is incorrect, but it would still be incorrect if the InterruptedException was dealt with because all Java code, including the main() method, runs in threads. C is incorrect. The sleep() method is static, so even if it is called on an instance, it still always affects the currently executing thread. View Answer Workspace Report Discuss in Forum 186. What will be the output of the program?
class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread(); /* Line 5 */ t.run(); /* Line 6 */ } public void run() { for(int i=1; i < 3; ++i) { System.out.print(i + ".."); } } }

A.This code will not compile due to line 5.

B. This code will not compile due to line 6. C. 1..2.. D.1..2..3.. Answer & Explanation Answer: Option C Explanation: Line 6 calls the run() method, so the run() method executes as a normal method should and it prints "1..2.." A is incorrect because line 5 is the proper way to create an object. B is incorrect because it is legal to call the run() method, even though this will not start a true thread of execution. The code after line 6 will not execute until the run() method is complete. D is incorrect because the for loop only does two iterations. View Answer Workspace Report Discuss in Forum 187. What will be the output of the program?
class Test116 { static final StringBuffer sb1 = new StringBuffer(); static final StringBuffer sb2 = new StringBuffer(); public static void main(String args[]) { new Thread() { public void run() { synchronized(sb1) { sb1.append("A"); sb2.append("B"); } } }.start(); new Thread() { public void run() { synchronized(sb1) { sb1.append("C"); sb2.append("D"); } } }.start(); /* Line 28 */ System.out.println (sb1 + " " + sb2); }

A.main() will finish before starting threads. B. main() will finish in the middle of one thread. C. main() will finish after one thread. D.Cannot be determined. Answer & Explanation Answer: Option D Explanation: Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined. add this code after line 28: try { Thread.sleep(5000); } catch(InterruptedException e) { } and you have some chance of predicting the outcome. View Answer Workspace Report Discuss in Forum 188. What will be the output of the program?
public class ThreadTest extends Thread { public void run() { System.out.println("In run"); yield(); System.out.println("Leaving run"); } public static void main(String []argv) { (new ThreadTest()).start(); } }

A.The code fails to compile in the main() method B. The code fails to compile in the run() method C. Only the text "In run" will be displayed D.The text "In run" followed by "Leaving run" will be displayed Answer & Explanation Answer: Option D Explanation: No answer description available for this question. Let us discuss. 189. What will be the output of the program?
public class Test107 implements Runnable {

private int x; private int y; public static void main(String args[]) { Test107 that = new Test107(); (new Thread(that)).start(); (new Thread(that)).start(); } public synchronized void run() { for(int i = 0; i < 10; i++) { x++; y++; System.out.println("x = " + x + ", y = " + y); /* Line 17 */ } } }

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

Thread g = new Thread() { public void run() { f.doStuff(); } }; t.start(); g.start(); } } class Foo { int x = 5; public void doStuff() { if (x < 10) { // nothing to do try { wait(); } catch(InterruptedException ex) { } } else { System.out.println("x is " + x++); if (x >= 10) { notify(); } } } }

A.The code will not compile because of an error on notify(); of class Foo. B. The code will not compile because of some other error in class Test. C. An exception occurs at runtime. D.It prints "x is 5 x is 6". Answer & Explanation Answer: Option C Explanation: C is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception. A, B are incorrect because the code compiles without errors. D is incorrect because the exception is thrown before there is any output. View Answer Workspace Report Discuss in Forum 191. What will be the output of the program?
class MyThread extends Thread {

public static void main(String [] args) { MyThread t = new MyThread(); Thread x = new Thread(t); x.start(); /* Line 7 */ } public void run() { for(int i = 0; i < 3; ++i) { System.out.print(i + ".."); } } }

A.Compilation fails. C. 0..1..2..3.. Answer & Explanation Answer: Option D Explanation:

B. 1..2..3.. D.0..1..2..

The thread MyThread will start and loop three times (from 0 to 2). Option A is incorrect because the Thread class implements the Runnable interface; therefore, in line 7, Thread can take an object of type Thread as an argument in the constructor. 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. 192. Which statement is true? A.A static method cannot be synchronized. If a class has synchronized code, multiple threads can still access the B. nonsynchronized code. Variables can be protected from concurrent access problems by marking them C. with the synchronized keyword. D.When a thread sleeps, it releases its locks. 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; they synchronize on the lock on the instance of class java.lang.Class that represents the class type. C is incorrect because only methodsnot variablescan be marked synchronized.

D is incorrect because a sleeping thread still maintains its locks. View Answer Workspace Report Discuss in Forum 193. Which two can be used to create a new Thread? 1. 2. 3. 4. 5. Extend java.lang.Thread and override the run() method. Extend java.lang.Runnable and override the start() method. Implement java.lang.Thread and implement the run() method. Implement java.lang.Runnable and implement the run() method. Implement java.lang.Thread and implement the start() method. B. 2 and 3 D.3 and 4

A.1 and 2 C. 1 and 4 Answer & Explanation Answer: Option C Explanation:

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

If a thread is blocked in the wait method of an object, and another thread C. executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed D. the wait call first definitely resumes execution as a direct and sole consequence of the notify call. Answer & Explanation Answer: Option B Explanation: Option B is correct - The notify method only wakes the thread. It does not guarantee that the thread will run. Option A is incorrect - 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 - 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. 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. View Answer Workspace Report Discuss in Forum 195. Which two statements are true? 1. Deadlock will not occur if wait()/notify() is used 2. A thread will resume execution as soon as its sleep duration expires. 3. Synchronization can prevent two objects from being accessed by the same thread. 4. The wait() method is overloaded to accept a duration. 5. The notify() method is overloaded to accept a duration. 6. Both wait() and notify() must be called from a synchronized context. A.1 and 2 C. 4 and 6 Answer & Explanation Answer: Option C Explanation: Statements (4) and (6) are correct. (4) is correct because the wait() method is B. 3 and 5 D.1 and 3

overloaded to accept a wait duration in milliseconds. If the thread has not been notified by the time the wait duration has elapsed, then the thread will move back to runnable even without having been notified. (6) is correct because wait()/notify()/notifyAll() must all be called from within a synchronized, context. A thread must own the lock on the object its invoking wait()/notify()/notifyAll() on. (1) is incorrect because wait()/notify() will not prevent deadlock. (2) is incorrect because a sleeping thread will return to runnable when it wakes up, but it might not necessarily resume execution right away. To resume executing, the newly awakened thread must still be moved from runnable to running by the scheduler. (3) is incorrect because synchronization prevents two or more threads from accessing the same object. (5) is incorrect because notify() is not overloaded to accept a duration. View Answer Workspace Report Discuss in Forum 196. The following block of code creates a Thread using a Runnable target:
Runnable target = new MyRunnable(); Thread myThread = new Thread(target);

Which of the following classes can be used to create the target, so that the preceding code compiles correctly? A.public class MyRunnable extends Runnable{public void run(){}} B. public class MyRunnable extends Object{public void run(){}} C. public class MyRunnable implements Runnable{public void run(){}} D.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. Option A is incorrect because interfaces are not extended; they are implemented. Option B is incorrect because even though the class would compile and it has a valid public void run() method, it does not implement the Runnable interface, so the compiler would complain when creating a Thread with an instance of it. Option D is incorrect because the run() method must be public.

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

When is the B object, created in line 3, eligible for garbage collection? A.after line 5 B. after line 6 C. after line 7 D.There is no way to be absolutely certain. Answer & Explanation Answer: Option D Explanation: No answer description available for this question. Let us discuss. View Answer Workspace Report Discuss in Forum 199. class HappyGarbage01
{ public static void main(String args[]) { HappyGarbage01 h = new HappyGarbage01(); h.methodA(); /* Line 6 */ } Object methodA()

{ Object obj1 = new Object(); Object [] obj2 = new Object[1]; obj2[0] = obj1; obj1 = null; return obj2[0]; } }

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

At what point is the Bar object, created on line 6, eligible for garbage collection? A.after line 12 B. after line 14

C. after line 7, when doBar() completes D.after line 15, when main() completes Answer & Explanation Answer: Option B Explanation: Option B is correct. 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. Therefore the Bar object, created on line 6, is eligible for garbage collection after line 14. Option A is wrong. This actually protects the object from garbage collection. Option C is wrong. Because the reference in the doBar() method is returned on line 7 and is stored in newBar on line 12. This preserver the object created on line 6. Option D is wrong. Not applicable because the object is eligible for garbage collection after line 14. View Answer Workspace Report Discuss in Forum 201. class Test
{ private Demo d; void start() { d = new Demo(); this.takeDemo(d); /* Line 7 */ } /* Line 8 */ void takeDemo(Demo demo) { demo = null; demo = new Demo(); } }

When is the Demo object eligible for garbage collection? A.After line 7 B. After line 8 C. After the start() method completes D.When the instance running this code is made eligible for garbage collection. Answer & Explanation Answer: Option D Explanation: Option D is correct. By a process of elimination. Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

Option B is wrong. A copy of the variable d is set to null and not the actual variable d. Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference. View Answer Workspace Report Discuss in Forum 202. public class X
{ public static void main(String [] args) { X x = new X(); X x2 = m1(x); /* Line 6 */ X x4 = new X(); x2 = x4; /* Line 8 */ doComplexStuff(); } static X m1(X mx) { mx = new X(); return mx; } }

After line 8 runs. how many objects are eligible for garbage collection? A.0 B. 1 C. 2 D.3 Answer & Explanation Answer: Option B Explanation: By the time line 8 has run, the only object without a reference is the one generated as a result of line 6. Remember that "Java is pass by value," so the reference variable x is not affected by the m1() method. Ref: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html 203. public Object m()
{ Object o = new Float(3.14F); Object [] oa = new Object[l]; oa[0] = o; /* Line 5 */ o = null; /* Line 6 */ oa[0] = null; /* Line 7 */ return o; /* Line 8 */ }

When is the Float object, created in line 3, eligible for garbage collection? A.just after line 5 B. just after line 6 C. just after line 7 D.just after line 8 Answer & Explanation

Answer: Option C Explanation: Option A is wrong. This simply copies the object reference into the array. Option B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object. Option C is correct. The thread of execution will then not have access to the object. View Answer Workspace Report Discuss in Forum 204. class X2
{ public X2 x; public static void main(String [] args) { X2 x2 = new X2(); /* Line 6 */ X2 x3 = new X2(); /* Line 7 */ x2.x = x3; x3.x = x2; x2 = new X2(); x3 = x2; /* Line 11 */ doComplexStuff(); } }

after line 11 runs, how many objects are eligible for garbage collection? A.0 B. 1 C. 2 D.3 Answer & Explanation Answer: Option C Explanation: This is an example of the islands of isolated objects. By the time line 11 has run, the objects instantiated in lines 6 and 7 are referring to each other, but no live thread can reach either of them. View Answer Workspace Report Discuss in Forum 205 What allows the programmer to destroy an object x? A.x.delete() B. x.finalize() C. Runtime.getRuntime().gc() D.Only the garbage collection system can destroy an object. Answer & Explanation Answer: Option D

Explanation: Option D is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, 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. When a class is no longer needed, it may be unloaded. Option A is wrong. I found 4 delete() methods in all of the Java class structure. They are: 1. delete() - Method in class java.io.File : Deletes the file or directory denoted by this abstract pathname. 2. delete(int, int) - Method in class java.lang.StringBuffer : Removes the characters in a substring of this StringBuffer. 3. delete(int, int) - Method in interface javax.accessibility.AccessibleEditableText : Deletes the text between two indices 4. delete(int, int) - Method in class : javax.swing.text.JTextComponent.AccessibleJTextComponent; Deletes the text between two indices None of these destroy the object to which they belong. Option B is wrong. I found 19 finalize() methods. The most interesting, from this questions point of view, was the finalize() method in class java.lang.Object which is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs. Option C is wrong. But it is interesting. The Runtime class has many methods, two of which are: 1. getRuntime() - Returns the runtime object associated with the current Java application. 2. gc() - Runs the garbage collector. 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. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn't destroy the object.

206. Which statement is true? A.Programs will not run out of memory. B. Objects that will never again be used are eligible for garbage collection. C. Objects that are referred to by other objects will never be garbage collected. D.Objects that can be reached from a live thread will never be garbage collected. Answer & Explanation

Answer: Option D Explanation: Option D is correct. Option C is wrong. See the note above on Islands of Isolation (An object is eligible for garbage collection when no live thread can access it - even though there might be references to it). Option B is wrong. "Never again be used" does not mean that there are no more references to the object. Option A is wrong. Even though Java applications can run out of memory there another answer supplied that is more right. View Answer Workspace Report Discuss in Forum 207. Which statement is true? All objects that are eligible for garbage collection will be garbage collected by A. the garbage collector. B. Objects with at least one reference will never be garbage collected. Objects from a class with the finalize() method overridden will never be garbage C. collected. Objects instantiated within anonymous inner classes are placed in the garbage D. collectible heap. Answer & Explanation Answer: Option D Explanation: All objects are placed in the garbage collectible heap. Option A is incorrect because the garbage collector makes no guarantees. Option B is incorrect because islands of isolated objects can exist. Option C is incorrect because finalize() has no such mystical powers. View Answer Workspace Report Discuss in Forum 208. Which statement is true? A.Memory is reclaimed by calling Runtime.gc(). B. Objects are not collected if they are accessible from live threads. An OutOfMemory error is only thrown if a single block of memory cannot be C. found that is large enough for a particular requirement. Objects that have finalize() methods always have their finalize() methods called D. before the program ends.

Answer & Explanation Answer: Option B Explanation: Option B is correct. If an object can be accessed from a live thread, it can't be garbage collected. Option A is wrong. Runtime.gc() asks the garbage collector to run, but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory. Option C is wrong. The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM. Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes - this goes against the purpose of the garbage collector. View Answer Workspace Report Discuss in Forum 209. Which statement is true? A.Calling Runtime.gc() will cause eligible objects to be garbage collected. B. The garbage collector uses a mark and sweep algorithm. C. If an object can be accessed from a live thread, it can't be garbage collected. D.If object 1 refers to object 2, then object 2 can't be garbage collected. Answer & Explanation Answer: Option C Explanation: This is a great way to think about when objects can be garbage collected. Option A and B assume guarantees that the garbage collector never makes. Option D is wrong because of the now famous islands of isolation scenario. 210. What will be the output of the program?
public class Test { public static void main(String[] args) { int x = 0; assert (x > 0) ? "assertion failed" : "assertion passed" ; System.out.println("finished"); } }

A.finished B. Compiliation fails.

C. An AssertionError is thrown and finished is output. D.An AssertionError is thrown with the message "assertion failed." Answer & Explanation Answer: Option B Explanation: Compilation Fails. You can't use the Assert statement in a similar way to the ternary operator. Don't confuse. View Answer Workspace Report Discuss in Forum 211. public class Test
{ public void foo() { assert false; /* Line 5 */ assert false; /* Line 6 */ } public void bar() { while(true) { assert false; /* Line 12 */ } assert false; /* Line 14 */ } }

What causes compilation to fail? A.Line 5 B. Line 6 C. Line 12 D.Line 14 Answer & Explanation Answer: Option D Explanation: Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also be unreachable. The answer must be something other than assert. Examine the following: A while statement can complete normally if and only if at least one of the following is true: - The while statement is reachable and the condition expression is not a constant

expression with value true. -There is a reachable break statement that exits the while statement. The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code:
public class Test80 { public void foo() { assert false; assert false; } public void bar() { while(true) { assert false; break; } assert false; } }

View Answer Workspace Report Discuss in Forum 212. What will be the output of the program?
public class Test { public static int y; public static void foo(int x) { System.out.print("foo "); y = x; } public static int bar(int z) { System.out.print("bar "); return y = z; } public static void main(String [] args ) { int t = 0; assert t > 0 : bar(7); assert t > 1 : foo(8); /* Line 18 */ System.out.println("done "); } }

A.bar B. bar done C. foo done D.Compilation fails Answer & Explanation Answer: Option D

Explanation: The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile. View Answer Workspace Report Discuss in Forum 213. What will be the output of the program (when you run with the -ea option) ?
public class Test { public static void main(String[] args) { int x = 0; assert (x > 0) : "assertion failed"; /* Line 6 */ System.out.println("finished"); } }

A.finished B. Compilation fails. C. An AssertionError is thrown. D.An AssertionError is thrown and finished is output. Answer & Explanation Answer: Option C Explanation: An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option) Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6. View Answer Workspace Report Discuss in Forum 214. public class Test2
{ public static int x; public static int foo(int y) { return y * 2; } public static void main(String [] args) { int z = 5; assert z > 0; /* Line 11 */ assert z > 2: foo(z); /* Line 12 */ if ( z < 7 ) assert z > 4; /* Line 14 */ switch (z) {

case 4: System.out.println("4 "); case 5: System.out.println("5 "); default: assert z < 10; } if ( z < 10 ) assert z > 4: z++; /* Line 22 */ System.out.println(z); } }

which line is an example of an inappropriate use of assertions? A.Line 11 B. Line 12 C. Line 14 D.Line 22 Answer & Explanation Answer: Option D Explanation: Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false. Option A is fine; a second expression in an assert statement is not required. Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement. Option C is fine because it is proper to call an assert statement conditionally. 215. Which of the following statements is true? If assertions are compiled into a source file, and if no flags are included at A. runtime, assertions will execute by default. B. As of Java version 1.4, assertion statements are compiled by default. With the proper use of runtime arguments, it is possible to instruct the VM to C. disable assertions for a certain class, and to enable assertions for a certain package, at the same time. When evaluating command-line arguments, the VM gives -ea flags precedence D. over -da flags. Answer & Explanation Answer: Option C Explanation: Option C is true because multiple VM flags can be used on a single invocation of a Java program. Option A is incorrect because at runtime assertions are ignored by default. Option B is incorrect because as of Java 1.4 you must add the argument -source

1.4 to the command line if you want the compiler to compile assertion statements. Option D is incorrect because the VM evaluates all assertion flags left to right. View Answer Workspace Report Discuss in Forum 216. Which statement is true? A.Assertions can be enabled or disabled on a class-by-class basis. B. Conditional compilation is used to allow tested classes to run at full speed. C. Assertions are appropriate for checking the validity of arguments in a method. The programmer can choose to execute a return statement or to throw an D. exception if an assertion fails. Answer & Explanation Answer: Option A Explanation: Option A is correct. The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class. Option B is wrong. Is there such a thing as conditional compilation in Java? Option C is wrong. For private methods - yes. But do not use assertions to check the parameters of a public method. An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError. Option D is wrong. Because you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover. View Answer Workspace Report Discuss in Forum 217. Which statement is true about assertions in the Java programming language? A.Assertion expressions should not contain side effects. B. Assertion expression values can be any primitive type. C. Assertions should be used for enforcing preconditions on public methods. An AssertionError thrown as a result of a failed assertion should always be D. handled by the enclosing method. Answer & Explanation Answer: Option A Explanation:

Option A is correct. Because assertions may be disabled, programs must not assume that the boolean expressions contained in assertions will be evaluated. Thus these expressions should be free of side effects. That is, evaluating such an expression should not affect any state that is visible after the evaluation is complete. Although it is not illegal for a boolean expression contained in an assertion to have a side effect, it is generally inappropriate, as it could cause program behaviour to vary depending on whether assertions are enabled or disabled. Assertion checking may be disabled for increased performance. Typically, assertion checking is enabled during program development and testing and disabled for deployment. Option B is wrong. Because you assert that something is "true". True is Boolean. So, an expression must evaluate to Boolean, not int or byte or anything else. Use the same rules for an assertion expression that you would use for a while condition. Option C is wrong. Usually, enforcing a precondition on a public method is done by condition-checking code that you write yourself, to give you specific exceptions. Option D is wrong. "You're never supposed to handle an assertion failure" Not all legal uses of assertions are considered appropriate. As with so much of Java, you can abuse the intended use for assertions, despite the best efforts of Sun's Java engineers to discourage you. For example, you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover. Legally, however, AssertionError is a subclass of Throwable, so it can be caught. But just don't do it! If you're going to try to recover from something, it should be an exception. To discourage you from trying to substitute an assertion for an exception, the AssertionError doesn't provide access to the object that generated it. All you get is the String message. View Answer Workspace Report Discuss in Forum 218. Which of the following statements is true? A.It is sometimes good practice to throw an AssertionError explicitly. Private getter() and setter() methods should not use assertions to verify B. arguments. If an AssertionError is thrown in a try-catch block, the finally block will be C. bypassed. It is proper to handle assertion statement failures using a catch D. (AssertionException ae) block. Answer & Explanation Answer: Option A Explanation: Option A is correct because it is sometimes advisable to thrown an assertion error

even if assertions have been disabled. Option B is incorrect because it is considered appropriate to check argument values in private methods using assertions. Option C is incorrect; finally is never bypassed. Option D is incorrect because AssertionErrors should never be handled. View Answer Workspace Report Discuss in Forum 219. Which of the following statements is true? In an assert statement, the expression after the colon ( : ) can be any Java A. expression. If a switch block has no default, adding an assert default is considered B. appropriate. In an assert statement, if the expression after the colon ( : ) does not have a C. value, the assert's error message will be empty. D.It is appropriate to handle assertion failures using a catch clause. Answer & Explanation Answer: Option B Explanation: Adding an assertion statement to a switch statement that previously had no default case is considered an excellent use of the assert mechanism. Option A is incorrect because only Java expressions that return a value can be used. For instance, a method that returns void is illegal. Option C is incorrect because the expression after the colon must have a value. Option D is incorrect because assertions throw errors and not exceptions, and assertion errors do cause program termination and should not be handled. 220. Which three statements are true? 1. Assertion checking is typically enabled when a program is deployed. 2. It is never appropriate to write code to handle failure of an assert statement. 3. Assertion checking is typically enabled during program development and testing. 4. Assertion checking can be selectively enabled or disabled on a per-package basis, but not on a per-class basis. 5. Assertion checking can be selectively enabled or disabled on both a perpackage basis and a per-class basis. A.1, 2 and 4 B. 2, 3 and 5 C. 3, 4 and 5

D.1, 2 and 5 Answer & Explanation Answer: Option B Explanation: (1) is wrong. It's just not true. (2) is correct. You're never supposed to handle an assertion failure. (3) is correct. Assertions let you test your assumptions during development, but the assertion codein effectevaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove. (4) is wrong. See the explanation for (5) below. (5) is correct. Assertion checking can be selectively enabled or disabled on a perpackage basis. Note that the package default assertion status determines the assertion status for classes initialized in the future that belong to the named package or any of its "subpackages". The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class. 221. public class Test2
{ public static int x; public static int foo(int y) { return y * 2; } public static void main(String [] args) { int z = 5; assert z > 0; /* Line 11 */ assert z > 2: foo(z); /* Line 12 */ if ( z < 7 ) assert z > 4; /* Line 14 */ switch (z) { case 4: System.out.println("4 "); case 5: System.out.println("5 "); default: assert z < 10; } if ( z < 10 ) assert z > 4: z++; /* Line 22 */ System.out.println(z); } }

which line is an example of an inappropriate use of assertions? A.Line 11 B. Line 12 C. Line 14 D.Line 22 Answer & Explanation Answer: Option D Explanation: Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false. Option A is fine; a second expression in an assert statement is not required. Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement. Option C is fine because it is proper to call an assert statement conditionally. View Answer Workspace Report Discuss in Forum 222. public class Test
{ public void foo() { assert false; /* Line 5 */ assert false; /* Line 6 */ } public void bar() { while(true) { assert false; /* Line 12 */ } assert false; /* Line 14 */ } }

What causes compilation to fail? A.Line 5 B. Line 6 C. Line 12 D.Line 14 Answer & Explanation Answer: Option D Explanation: Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of

the assert then surely line 6 would also be unreachable. The answer must be something other than assert. Examine the following: A while statement can complete normally if and only if at least one of the following is true: - The while statement is reachable and the condition expression is not a constant expression with value true. -There is a reachable break statement that exits the while statement. The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code:
public class Test80 { public void foo() { assert false; assert false; } public void bar() { while(true) { assert false; break; } assert false; } }

223 What is the value of "d" after this line of code has been executed? double d = Math.round ( 2.5 + Math.random() ); A.2 B. 3 C. 4 D.2.5 Answer & Explanation Answer: Option B Explanation: The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So Option B is the answer. View Answer Workspace Report Discuss in Forum

224. Which of the following would compile without error? A.int a = Math.abs(-5); B. int b = Math.abs(5.0); C. int c = Math.abs(5.5F); D.int d = Math.abs(5L); Answer & Explanation Answer: Option A Explanation: The return value of the Math.abs() method is always the same as the type of the parameter passed into that method. In the case of A, an integer is passed in and so the result is also an integer which is fine for assignment to "int a". The values used in B, C & D respectively are a double, a float and a long. The compiler will complain about a possible loss of precision if we try to assign the results to an "int". View Answer Workspace Report Discuss in Forum 225. Which of the following are valid calls to Math.max? 1. 2. 3. 4. Math.max(1,4) Math.max(2.3, 5) Math.max(1, 3, 5, 7) Math.max(-1.5, -2.8f)

A.1, 2 and 4 B. 2, 3 and 4 C. 1, 2 and 3 D.3 and 4 Answer & Explanation Answer: Option A Explanation: (1), (2), and (4) are correct. The max() method is overloaded to take two arguments of type int, long, float, or double. (3) is incorrect because the max() method only takes two arguments. View Answer Workspace Report Discuss in Forum

226. public class Myfile


{ public static void main (String[] args) { String biz = args[1]; String baz = args[2]; String rip = args[3]; System.out.println("Arg is " + rip); } }

Select how you would start the program to cause it to print: Arg is 2 A.java Myfile 222 B. java Myfile 1 2 2 3 4 C. java Myfile 1 3 2 2 D.java Myfile 0 1 2 3 Answer & Explanation Answer: Option C Explanation: Arguments start at array element 0 so the fourth arguement must be 2 to produce the correct output. 227. What will be the output of the program?
String x = new String("xyz"); String y = "abc"; x = x + y;

How many String objects have been created? A.2 B. 3 C. 4 D.5 Answer & Explanation Answer: Option C Explanation: Line 1 creates two, one referred to by x and the lost String "xyz". Line 2 creates one (for a total of three). Line 3 creates one more (for a total of four), the concatenated String referred to by x with a value of "xyzabc". View Answer Workspace Report Discuss in Forum 228. What will be the output of the program?
public class WrapTest { public static void main(String [] args) { int result = 0; short s = 42;

Long x = new Long("42"); Long y = new Long(42); Short z = new Short("42"); Short x2 = new Short(s); Integer y2 = new Integer("42"); Integer z2 = new Integer(42); if (x == y) /* Line 13 */ result = 1; if (x.equals(y) ) /* Line 15 */ result = result + 10; if (x.equals(z) ) /* Line 17 */ result = result + 100; if (x.equals(x2) ) /* Line 19 */ result = result + 1000; if (x.equals(z2) ) /* Line 21 */ result = result + 10000; System.out.println("result = " + result); } }

A.result = 1 B. result = 10 C. result = 11 D.result = 11010 Answer & Explanation Answer: Option B Explanation: Line 13 fails because == compares reference values, not object values. Line 15 succeeds because both String and primitive wrapper constructors resolve to the same value (except for the Character wrapper). Lines 17, 19, and 21 fail because the equals() method fails if the object classes being compared are different and not in the same tree hierarchy. View Answer Workspace Report Discuss in Forum 229. What will be the output of the program?
public class BoolTest { public static void main(String [] args) { int result = 0; Boolean Boolean Boolean Boolean b1 b2 b3 b4 = = = = new new new new Boolean("TRUE"); Boolean("true"); Boolean("tRuE"); Boolean("false");

if (b1 == b2) /* Line 10 */ result = 1; if (b1.equals(b2) ) /* Line 12 */ result = result + 10; if (b2 == b4) /* Line 14 */

result = result if (b2.equals(b4) ) result = result if (b2.equals(b3) ) result = result

+ 100; /* Line 16 */ + 1000; /* Line 18 */ + 10000;

System.out.println("result = " + result); } }

A.0 B. 1 C. 10 D.10010 Answer & Explanation Answer: Option D Explanation: Line 10 fails because b1 and b2 are two different objects. Lines 12 and 18 succeed because the Boolean String constructors are case insensitive. Lines 14 and 16 fail because true is not equal to false. View Answer Workspace Report Discuss in Forum 230. What will be the output of the program?
public class ObjComp { public static void main(String [] args ) { int result = 0; ObjComp oc = new ObjComp(); Object o = oc; if (o == oc) result = 1; if (o != oc) result = result + 10; if (o.equals(oc) ) result = result + 100; if (oc.equals(o) ) result = result + 1000; System.out.println("result = " + result); } }

A.1 B. 10 C. 101 D.1101 Answer & Explanation Answer: Option D

Explanation: Even though o and oc are reference variables of different types, they are both referring to the same object. This means that == will resolve to true and that the default equals() method will also resolve to true. View Answer Workspace Report Discuss in Forum 231. What will be the output of the program?
public class Example { public static void main(String [] args) { double values[] = {-2.3, -1.0, 0.25, 4}; int cnt = 0; for (int x=0; x < values.length; x++) { if (Math.round(values[x] + .5) == Math.ceil(values[x])) { ++cnt; } } System.out.println("same results " + cnt + " time(s)"); } }

A.same results 0 time(s) B. same results 2 time(s) C. same results 4 time(s) D.Compilation fails. Answer & Explanation Answer: Option B Explanation: Math.round() adds .5 to the argument then performs a floor(). Since the code adds an additional .5 before round() is called, it's as if we are adding 1 then doing a floor(). The values that start out as integer values will in effect be incremented by 1 on the round() side but not on the ceil() side, and the noninteger values will end up equal. 232. What will be the output of the program?
public class Test178 { public static void main(String[] args) { String s = "foo"; Object o = (Object)s; if (s.equals(o)) { System.out.print("AAA"); }

else { System.out.print("BBB"); } if (o.equals(s)) { System.out.print("CCC"); } else { System.out.print("DDD"); } } }

A.AAACCC B. AAADDD C. BBBCCC D.BBBDDD Answer & Explanation Answer: Option A Explanation: No answer description available for this question. Let us discuss. View Answer Workspace Report Discuss in Forum 233. What will be the output of the program?
String x = "xyz"; x.toUpperCase(); /* Line 2 */ String y = x.replace('Y', 'y'); y = y + "abc"; System.out.println(y);

A.abcXyZ B. abcxyz C. xyzabc D.XyZabc Answer & Explanation Answer: Option C Explanation: Line 2 creates a new String object with the value "XYZ", but this new object is immediately lost because there is no reference to it. Line 3 creates a new String object referenced by y. This new String object has the value "xyz" because there was no "Y" in the String object referred to by x. Line 4 creates a new String object, appends "abc" to the value "xyz", and refers y to the result. View Answer Workspace Report Discuss in Forum

234. What will be the output of the program?


int i = (int) Math.random();

A.i = 0 B. i = 1 C. value of i is undetermined D.Statement causes a compile error Answer & Explanation Answer: Option A Explanation: Math.random() returns a double value greater than or equal to 0 and less than 1. Its value is stored to an int but as this is a narrowing conversion, a cast is needed to tell the compiler that you are aware that there may be a loss of precision. The value after the decimal point is lost when you cast a double to int and you are left with 0. View Answer Workspace Report Discuss in Forum 235. What will be the output of the program?
class A { public A(int x){} } class B extends A { } public class test { public static void main (String args []) { A a = new B(); System.out.println("complete"); } }

A.It compiles and runs printing nothing B. Compiles but fails at runtime C. Compile Error D.Prints "complete" Answer & Explanation Answer: Option C Explanation: No constructor has been defined for class B therefore it will make a call to the default constructor but since class B extends class A it will also call the Super() default constructor. Since a constructor has been defined in class A java will no longer supply a default constructor for class A therefore when class B calls class A's default constructor it

will result in a compile error. View Answer Workspace Report Discuss in Forum 236. What will be the output of the program?
int i = 1, j = 10; do { if(i++ > --j) /* Line 4 */ { continue; } } while (i < 5); System.out.println("i = " + i + "and j = " + j); /* Line 9 */

A.i = 6 and j = 5 B. i = 5 and j = 5 C. i = 6 and j = 6 D.i = 5 and j = 6 Answer & Explanation Answer: Option D Explanation: This question is not testing your knowledge of the continue statement. It is testing your knowledge of the order of evaluation of operands. Basically the prefix and postfix unary operators have a higher order of evaluation than the relational operators. So on line 4 the variable i is incremented and the variable j is decremented before the greater than comparison is made. As the loop executes the comparison on line 4 will be: if(i > j) if(2 > 9) if(3 > 8) if(4 > 7) if(5 > 6) at this point i is not less than 5, therefore the loop terminates and line 9 outputs the values of i and j as 5 and 6 respectively. The continue statement never gets to execute because i never reaches a value that is greater than j. 237. What will be the output of the program?
public class ExamQuestion7 { static int j; static void methodA(int i) {

boolean b; do { b = i<10 | methodB(4); /* Line 9 */ b = i<10 || methodB(8); /* Line 10 */ }while (!b); } static boolean methodB(int i) { j += i; return true; } public static void main(String[] args) { methodA(0); System.out.println( "j = " + j ); } }

A.j = 0 B. j = 4 C. j = 8 D.The code will run with no output Answer & Explanation Answer: Option B Explanation: The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed. However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called. The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4. View Answer Workspace Report Discuss in Forum 238. What will be the output of the program?
try { Float f1 = new Float("3.0"); int x = f1.intValue(); byte b = f1.byteValue(); double d = f1.doubleValue(); System.out.println(x + b + d); } catch (NumberFormatException e) /* Line 9 */ { System.out.println("bad number"); /* Line 11 */ }

A.9.0

B. bad number C. Compilation fails on line 9. D.Compilation fails on line 11. Answer & Explanation Answer: Option A Explanation: The xxxValue() methods convert any numeric wrapper object's value to any primitive type. When narrowing is necessary, significant bits are dropped and the results are difficult to calculate. View Answer Workspace Report Discuss in Forum 239. What will be the output of the program?
class Q207 { public static void main(String[] args) { int i1 = 5; int i2 = 6; String s1 = "7"; System.out.println(i1 + i2 + s1); /* Line 8 */ } }

A.18 B. 117 C. 567 D.Compiler error Answer & Explanation Answer: Option B Explanation: This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are: If either operand is a String, the + operator concatenates the operands. If both operands are numeric, the + operator adds the operands. The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as:
System.out.println( new StringBuffer() .append(new Integer(i1 + i2).toString())

.append(s1) .toString() );

View Answer Workspace Report Discuss in Forum 240. What will be the output of the program?
public class SqrtExample { public static void main(String [] args) { double value = -9.0; System.out.println( Math.sqrt(value)); } }

A.3.0 B. -3.0 C. NaN D.Compilation fails. Answer & Explanation Answer: Option C Explanation: The sqrt() method returns NaN (not a number) when it's argument is less than zero. View Answer Workspace Report Discuss in Forum 241. What will be the output of the program?
String s = "ABC"; s.toLowerCase(); s += "def"; System.out.println(s);

A.ABC B. abc C. ABCdef D.Compile Error Answer & Explanation Answer: Option C Explanation: String objects are immutable. The object s above is set to "ABC". Now ask yourself if this object is changed and if so where - remember strings are immutable. Line 2 returns a string object but does not change the originag string object s, so after line 2 s is still "ABC". So what's happening on line 3? Java will treat line 3 like the following:

s = new StringBuffer().append(s).append("def").toString(); This effectively creates a new String object and stores its reference in the variable s, the old String object containing "ABC" is no longer referenced by a live thread and becomes available for garbage collection. 242. What will be the output of the program?
public class NFE { public static void main(String [] args) { String s = "42"; try { s = s.concat(".5"); /* Line 8 */ double d = Double.parseDouble(s); s = Double.toString(d); int x = (int) Math.ceil(Double.valueOf(s).doubleValue()); System.out.println(x); } catch (NumberFormatException e) { System.out.println("bad number"); } } }

A.42 B. 42.5 C. 43 D.bad number Answer & Explanation Answer: Option C Explanation: All of this code is legal, and line 8 creates a new String with a value of "42.5". Lines 9 and 10 convert the String to a double and then back again. Line 11 is fun Math.ceil()'s argument expression is evaluated first. We invoke the valueOf() method that returns an anonymous Double object (with a value of 42.5). Then the doubleValue() method is called (invoked on the newly created Double object), and returns a double primitive (there and back again), with a value of (you guessed it) 42.5. The ceil() method converts this to 43.0, which is cast to an int and assigned to x. View Answer Workspace Report Discuss in Forum

243. What will be the output of the program? System.out.println(Math.sqrt(-4D)); A.-2 B. NaN C. Compile Error D.Runtime Exception Answer & Explanation Answer: Option B Explanation: It is not possible in regular mathematics to get a value for the square-root of a negative number therefore a NaN will be returned because the code is valid. View Answer Workspace Report Discuss in Forum 244. What will be the output of the program?
interface Foo141 { int k = 0; /* Line 3 */ } public class Test141 implements Foo141 { public static void main(String args[]) { int i; Test141 test141 = new Test141(); i = test141.k; /* Line 11 */ i = Test141.k; i = Foo141.k; } }

A.Compilation fails. B. Compiles and runs ok. C. Compiles but throws an Exception at runtime. D.Compiles but throws a RuntimeException at runtime. Answer & Explanation Answer: Option B Explanation: The variable k on line 3 is an interface constant, it is implicitly public, static, and final. Static variables can be referenced in two ways: Via a reference to any instance of the class (line 11) Via the class name (line 12). View Answer Workspace Report Discuss in Forum

245. What will be the output of the program?


String a = "newspaper"; a = a.substring(5,7); char b = a.charAt(1); a = a + b; System.out.println(a);

A.apa B. app C. apea D.apep Answer & Explanation Answer: Option B Explanation: Both substring() and charAt() methods are indexed with a zero-base, and substring() returns a String of length arg2 - arg1. View Answer Workspace Report Discuss in Forum 246. What will be the output of the program?
public class StringRef { public static void main(String [] args) { String s1 = "abc"; String s2 = "def"; String s3 = s2; /* Line 7 */ s2 = "ghi"; System.out.println(s1 + s2 + s3); } }

A.abcdefghi B. abcdefdef C. abcghidef D.abcghighi Answer & Explanation Answer: Option C Explanation: After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".

247. What will be the output of the program?


public class Test138 { public static void stringReplace (String text) { text = text.replace ('j' , 'c'); /* Line 5 */ } public static void bufferReplace (StringBuffer text) { text = text.append ("c"); /* Line 9 */ } public static void main (String args[]) { String textString = new String ("java"); StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */ stringReplace(textString); bufferReplace(textBuffer); System.out.println (textString + textBuffer); } }

A.java B. javac C. javajavac D.Compile error Answer & Explanation Answer: Option C Explanation: A string is immutable, it cannot be changed, that's the reason for the StringBuffer class. The stringReplace method does not change the string declared on line 14, so this remains set to "java". Method parameters are always passed by value - a copy is passed into the method if the copy changes, the original remains intact, line 5 changes the reference i.e. text points to a new String object, however this is lost when the method completes. The textBuffer is a StringBuffer so it can be changed. This change is carried out on line 9, so "java" becomes "javac", the text reference on line 9 remains unchanged. This gives us the output of "javajavac" View Answer Workspace Report Discuss in Forum 248. What will be the output of the program?
class Tree { } class Pine extends Tree { } class Oak extends Tree { } public class Forest1 { public static void main (String [] args) {

Tree tree = new Pine(); if( tree instanceof Pine ) System.out.println ("Pine"); else if( tree instanceof Tree ) System.out.println ("Tree"); else if( tree instanceof Oak ) System.out.println ( "Oak" ); else System.out.println ("Oops "); } }

A.Pine B. Tree C. Forest D.Oops Answer & Explanation Answer: Option A Explanation: The program prints "Pine". View Answer Workspace Report Discuss in Forum 249. What will be the output of the program?
String d = "bookkeeper"; d.substring(1,7); d = "w" + d; d.append("woo"); /* Line 4 */ System.out.println(d);

A.wookkeewoo B. wbookkeeper C. wbookkeewoo D.Compilation fails. Answer & Explanation Answer: Option D Explanation: In line 4 the code calls a StringBuffer method, append() on a String object. View Answer Workspace Report Discuss in Forum 250. What will be the output of the program?
String a = "ABCD"; String b = a.toLowerCase(); b.replace('a','d'); b.replace('b','c'); System.out.println(b);

A.abcd B. ABCD C. dccd D.dcba Answer & Explanation Answer: Option A Explanation: String objects are immutable, they cannot be changed, in this case we are talking about the replace method which returns a new String object resulting from replacing all occurrences of oldChar in this string with newChar. b.replace(char oldChar, char newChar); But since this is only a temporary String it must either be put to use straight away i.e. System.out.println(b.replace('a','d')); Or a new variable must be assigned its value i.e. String c = b.replace('a','d'); View Answer Workspace Report Discuss in Forum 251. What will be the output of the program?
public class ExamQuestion6 { static int x; boolean catch() { x++; return true; } public static void main(String[] args) { x=0; if ((catch() | catch()) || catch()) x++; System.out.println(x); } }

A.1 B. 2 C. 3 D.Compilation Fails Answer & Explanation Answer: Option D

Explanation: Initially this looks like a question about the logical and logical shortcut operators "|" and "||" but on closer inspection it should be noticed that the name of the boolean method in this code is "catch". "catch" is a reserved keyword in the Java language and cannot be used as a method name. Hence Compilation will fail. 252. What will be the output of the program?
public class Test { public static void main(String[] args) { final StringBuffer a = new StringBuffer(); final StringBuffer b = new StringBuffer(); new Thread() { public void run() { System.out.print(a.append("A")); synchronized(b) { System.out.print(b.append("B")); } } }.start(); new Thread() { public void run() { System.out.print(b.append("C")); synchronized(a) { System.out.print(a.append("D")); } } }.start(); } }

A.ACCBAD B. ABBCAD C. CDDACB D.Indeterminate output Answer & Explanation Answer: Option D Explanation: It gives different output while executing the same compiled code at different times.
C:\>javac Test.java C:\>java Test ABBCAD C:\>java Test

ACADCB C:\>java ACBCBAD C:\>java ABBCAD C:\>java ACBCBAD C:\>java ACBCBAD C:\>java ABBCAD

Test Test Test Test Test

View Answer Workspace Report Discuss in Forum 253. What will be the output of the program?
String s = "hello"; Object o = s; if( o.equals(s) ) { System.out.println("A"); } else { System.out.println("B"); } if( s.equals(o) ) { System.out.println("C"); } else { System.out.println("D"); }

1. 2. 3. 4.

A B C D

A.1 and 3 B. 2 and 4 C. 3 and 4 D.1 and 2 Answer & Explanation Answer: Option A Explanation: No answer description available for this question. Let us discuss. View Answer Workspace Report Discuss in Forum

254. What will be the output of the program (in jdk1.6 or above)?
public class BoolTest { public static void main(String [] args) { Boolean b1 = new Boolean("false"); boolean b2; b2 = b1.booleanValue(); if (!b2) { b2 = true; System.out.print("x "); } if (b1 & b2) /* Line 13 */ { System.out.print("y "); } System.out.println("z"); } }

A.z B. x z C. y z D.Compilation fails. Answer & Explanation Answer: Option B Explanation: No answer description available for this question. Let us discuss. 255. Which statement is true given the following? Double d = Math.random(); A.0.0 < d <= 1.0 B. 0.0 <= d < 1.0 C. Compilation fail D.Cannot say. Answer & Explanation Answer: Option B Explanation: The Math.random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 View Answer Workspace Report Discuss in Forum

256. Which two statements are true about wrapper or String classes? 1. If x and y refer to instances of different wrapper classes, then the fragment x.equals(y) will cause a compiler failure. 2. If x and y refer to instances of different wrapper classes, then x == y can sometimes be true. 3. If x and y are String references and if x.equals(y) is true, then x == y is true. 4. If x, y, and z refer to instances of wrapper classes and x.equals(y) is true, and y.equals(z) is true, then z.equals(x) will always be true. 5. If x and y are String references and x == y is true, then y.equals(x) will be true. A.1 and 2 B. 2 and 3 C. 3 and 4 D.4 and 5 Answer & Explanation Answer: Option D Explanation: Statement (4) describes an example of the equals() method behaving transitively. By the way, x, y,and z will all be the same type of wrapper. Statement (5) is true because x and y are referring to the same String object. Statement (1) is incorrectthe fragment will compile. Statement (2) is incorrect because x == y means that the two reference variables are referring to the same object. Statement (3) will only be true if x and y refer to the same String. It is possible for x and y to refer to two different String objects with the same value. View Answer Workspace Report Discuss in Forum 257. Which of the following will produce an answer that is closest in value to a double, d, while not being greater than d? A.(int)Math.min(d); B. (int)Math.max(d); C. (int)Math.abs(d); D.(int)Math.floor(d); Answer & Explanation Answer: Option D Explanation: The casting to an int is a smokescreen. Use a process of elimination to answer this question: Option D is the correct answer, it is syntathecially correct and will consistently

return a value less than d. Option A and B are wrong because both the min() and max() methods require 2 arguments whereas here they are passed only one parameter. Option C is wrong because it could return a value greater than d (if d was negative). View Answer Workspace Report Discuss in Forum 258. What two statements are true about the result obtained from calling Math.random()? 1. 2. 3. 4. 5. The result is less than 0.0. The result is greater than or equal to 0.0.. The result is less than 1.0. The result is greater than 1.0. The result is greater than or equal to 1.0.

A.1 and 2 B. 2 and 3 C. 3 and 4 D.4 and 5 Answer & Explanation Answer: Option B Explanation: (1) and (2) are correct. The result range for random() is 0.0 to < 1.0; 1.0 is not in range.

http://www.javaprepare.com/quests/test.html

Mock exam 1 for SCJP 6


The sample test is modeled on the Sun Certification for JavaTM 6 Programmer exam. The test has 50 questions and needs to be executed in 2 hours. The real exam may be a little tougher than this. You need to score 35 correct answers out of 60 to clear the real exam in 180 minutes. Please let us know at ngabrani At hotmail dot com if you find any issues with the test. The site also offers another mock exam and questions by topic. 1. Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer. A. public static int main(char args[]) B. public static void main(String args[]) C. public static void MAIN(String args[]) D. public static void main(String args) E. public static void main(char args[]) 2. What all gets printed when the following code is compiled and run? Select the three correct answers.
public class xyz { public static void main(String args[]) { for(int i = 0; i < 2; i++) { for(int j = 2; j>= 0; j--) { if(i == j) break; System.out.println("i=" + i + " j="+j); } } } }

A. i=0 j=0 B. i=0 j=1 C. i=0 j=2 D. i=1 j=0 E. i=1 j=1 F. i=1 j=2 G. i=2 j=0 H. i=2 j=1 I. i=2 j=2 3. What gets printed when the following code is compiled and run with the following command java test 2 Select the one correct answer.
public class test { public static void main(String args[]) { Integer intObj=Integer.valueOf(args[args.length-1]);

int i = intObj.intValue(); if(args.length > 1) System.out.println(i); if(args.length > 0) System.out.println(i - 1); else System.out.println(i - 2); } }

A. test B. test -1 C. 0 D. 1 E. 2 4. In Java technology what expression can be used to represent number of elements in an array named arr ? 5. How would the number 5 be represented in hex using up-to four characters. 6. Which of the following is a Java keyword. Select the four correct answers. A. extern B. synchronized C. volatile D. friend E. friendly F. transient G. this H. then 7. Is the following statement true or false. The constructor of a class must not have a return type. A. true B. false 8. What is the number of bytes used by Java primitive long. Select the one correct answer. A. The number of bytes is compiler dependent. B. 2 C. 4 D. 8 E. 64 9. What is returned when the method substring(2, 4) is invoked on the string "example"? Include the answer in quotes as the result is of type String. 10. Which of the following is correct? Select the two correct answers. A. The native keyword indicates that the method is implemented in another language like C/C++. B. The only statements that can appear before an import statement in a Java file are comments. C. The method definitions inside interfaces are public and abstract. They cannot be private or protected. D. A class constructor may have public or protected keyword before them, nothing else.

11. What is the result of evaluating the expression 14 ^ 23. Select the one correct answer. A. 25 B. 37 C. 6 D. 31 E. 17 F. 9 G. 24 12. Which of the following are true. Select the one correct answers. A. && operator is used for short-circuited logical AND. B. ~ operator is the bit-wise XOR operator. C. | operator is used to perform bitwise OR and also short-circuited logical OR. D. The unsigned right shift operator in Java is >>. 13. Name the access modifier which when used with a method, makes it available to all the classes in the same package and to all the subclasses of the class. 14. Which of the following is true. Select the two correct answers. A. A class that is abstract may not be instantiated. B. The final keyword indicates that the body of a method is to be found elsewhere. The code is written in non-Java language, typically in C/C++. C. A static variable indicates there is only one copy of that variable. D. A method defined as private indicates that it is accessible to all other classes in the same package. 15. What all gets printed when the following program is compiled and run. Select the two correct answers.

public class test { public static void main(String args[]) { int i, j=1; i = (j>1)?2:1; switch(i) { case 0: System.out.println(0); break; case 1: System.out.println(1); case 2: System.out.println(2); break; case 3: System.out.println(3); break; } } }

A. 0 B. 1 C. 2 D. 3 16. What all gets printed when the following program is compiled and run. Select the one correct answer.

public class test {

public static void main(String args[]) { int i=0, j=2; do { i=++i; j--; } while(j>0); System.out.println(i); } }

0 1 2 The program does not compile because of statement "i=++i;" 17. What all gets printed when the following gets compiled and run. Select the three correct answers.
18. 19. public class test { 20. public static void main(String args[]) { 21. int i=1, j=1; 22. try { 23. i++; 24. j--; 25. if(i/j > 1) 26. i++; 27. } 28. catch(ArithmeticException e) { 29. System.out.println(0); 30. } 31. catch(ArrayIndexOutOfBoundsException e) { 32. System.out.println(1); 33. } 34. catch(Exception e) { 35. System.out.println(2); 36. } 37. finally { 38. System.out.println(3); 39. } 40. System.out.println(4); 41. } 42. } 43. 44.

A. B. C. D.

A. 0 B. 1 C. 2 D. 3 E. 4 45. What all gets printed when the following gets compiled and run. Select the two correct answers.

public class test { public static void main(String args[]) { int i=1, j=1;

try { i++; j--; if(i == j) i++; } catch(ArithmeticException e) { System.out.println(0); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(1); } catch(Exception e) { System.out.println(2); } finally { System.out.println(3); } System.out.println(4); } }

A. 0 B. 1 C. 2 D. 3 E. 4 46. What all gets printed when the following gets compiled and run. Select the two correct answers.

public class test { public static void main(String args[]) { String s1 = "abc"; String s2 = "abc"; if(s1 == s2) System.out.println(1); else System.out.println(2); if(s1.equals(s2)) System.out.println(3); else System.out.println(4); } }

A. 1 B. 2 C. 3 D. 4 47. What all gets printed when the following gets compiled and run. Select the two correct answers.

public class test { public static void main(String args[]) { String s1 = "abc"; String s2 = new String("abc"); if(s1 == s2) System.out.println(1); else System.out.println(2); if(s1.equals(s2)) System.out.println(3); else System.out.println(4); } }

A. 1 B. 2 C. 3 D. 4 48. Which of the following are legal array declarations. Select the three correct answers. A. int i[5][]; B. int i[][]; C. int []i[]; D. int i[5][5]; E. int[][] a; 49. What is the range of values that can be specified for an int. Select the one correct answer. A. The range of values is compiler dependent. B. -231 to 231 - 1 C. -231-1 to 231 D. -215 to 215 - 1 E. -215-1 to 215 50. How can you ensure that the memory allocated by an object is freed. Select the one correct answer. A. By invoking the free method on the object. B. By calling system.gc() method. C. By setting all references to the object to new values (say null). D. Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object. 51. What gets printed when the following code is compiled and run. Select the one correct answer.

public class test { public static void main(String args[]) { int i = 1; do { i--;

} while (i > 2); System.out.println(i); } }

A. 0 B. 1 C. 2 D. -1 52. Which of these is a legal definition of a method named m assuming it throws IOException, and returns void. Also assume that the method does not take any arguments. Select the one correct answer. A. void m() throws IOException{} B. void m() throw IOException{} C. void m(void) throws IOException{} D. m() throws IOException{} E. void m() {} throws IOException 53. Which of the following are legal identifier names in Java. Select the two correct answers. A. %abcd B. $abcd C. 1abcd D. package E. _a_long_name 54. At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.

void method X() { String r = new String("abc"); String s = new String("abc"); r = r+1; //1 r = null; //2 s = s + r; //3 } //4

A. B. C. D. E.

Before statement labeled 1 Before statement labeled 2 Before statement labeled 3 Before statement labeled 4 Never.

55. String s = new String("xyz"); Assuming the above declaration, which of the following statements would compile. Select the one correct answer. A. s = 2 * s; B. int i = s[0]; C. s = s + s; D. s = s >> 2;

E. None of the above. 56. Which of the following statements related to Garbage Collection are correct. Select the two correct answers. A. It is possible for a program to free memory at a given time. B. Garbage Collection feature of Java ensures that the program never runs out of memory. C. It is possible for a program to make an object available for Garbage Collection. D. The finalize method of an object is invoked before garbage collection is performed on the object. 57. If a base class has a method defined as void method() { } Which of the following are legal prototypes in a derived class of this class. Select the two correct answers. A. void method() { } B. int method() { return 0;} C. void method(int i) { } D. private void method() { } 58. In which all cases does an exception gets generated. Select the two correct answers.

int i = 0, j = 1;

A. if((i == 0) || (j/i == 1)) B. if((i == 0) | (j/i == 1)) C. if((i != 0) && (j/i == 1)) D. if((i != 0) & (j/i == 1)) 59. Which of the following statements are true. Select the two correct answers. A. The wait method defined in the Thread class, can be used to convert a thread from Running state to Waiting state. B. The wait(), notify(), and notifyAll() methods must be executed in synchronized code. C. The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state. D. The Thread class is an abstract class. 60. Which keyword when applied on a method indicates that only one thread should execute the method at a time. Select the one correct answer. A. transient B. volatile C. synchronized D. native E. static F. final 61. What is the name of the Collection interface used to represent elements in a sequence (in a particular order). Select the one correct answer. A. Collection B. Set C. List D. Map

62. Which of these classes implement the Collection interface SortedMap. Select the one correct answers. A. HashMap B. Hashtable C. TreeMap D. HashSet E. TreeSet F. Vector 63. Which of the following are true about interfaces. Select the two correct answers. A. Methods declared in interfaces are implicitly private. B. Variables declared in interfaces are implicitly public, static, and final. C. An interface can extend any number of interfaces. D. The keyword implements indicate that an interface inherits from another. 64. Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer. A. test(); B. super.test(); C. super.super.test(); D. ::test(); E. C.test(); F. It is not possible to invoke test() method defined in C from a method in A. 65. What is the return type of method round(double d) defined in Math class. 66. What gets written on the screen when the following program is compiled and run. Select the one right answer.
public class test { public static void main(String args[]) { int i; float f = 2.3f; double d = 2.7; i = ((int)Math.ceil(f)) * ((int)Math.round(d)); System.out.println(i); } }

A. 4 B. 5 C. 6 D. 6.1 E. 9 67. Is the following statement true or false. As the toString method is defined in the Object class, System.out.println can be used to print any object. A. true B. false 68. Which of these classes defined in java.io and used for file-handling are abstract. Select the two correct answers.

A. InputStream B. PrintStream C. Reader D. FileInputStream E. FileWriter 69. Name the collection interface used to represent collections that maintain unique elements. 70. What is the result of compiling and running the following program.
public class test { public static void main(String args[]) { String str1="abc"; String str2="def"; String str3=str1.concat(str2); str1.concat(str2); System.out.println(str1); } }

A. abc B. def C. abcabc D. abcdef E. defabc F. abcdefdef 71. Select the one correct answer. The number of characters in an object of a class String is given by A. The member variable called size B. The member variable called length C. The method size() returns the number of characters. D. The method length() returns the number of characters. 72. Select the one correct answer. Which method defined in Integer class can be used to convert an Integer object to primitive int type. A. valueOf B. intValue C. getInt D. getInteger 73. Name the return type of method hashCode() defined in Object class, which is used to get the unique hash value of an Object. 74. Which of the following are correct. Select the one correct answer. A. An import statement, if defined, must always be the first non-comment statement of the file. B. private members are accessible to all classes in the same package. C. An abstract class can be declared as final. D. Local variables cannot be declared as static. 75. Name the keyword that makes a variable belong to a class, rather than being defined for each instance of the class. Select the one correct answer. A. static B. final

C. abstract D. native E. volatile F. transient 76. Which of these are core interfaces in the collection framework. Select the one correct answer. A. Tree B. Stack C. Queue D. Array E. LinkedList F. Map 77. Which of these statements are true. Select the two correct answers. A. For each try block there must be at least one catch block defined. B. A try block may be followed by any number of finally blocks. C. A try block must be followed by at least one finally or catch block. D. If both catch and finally blocks are defined, catch block must precede the finally block.

Answers to Sample Test 1 1. b 2. b, c, f 3. d. Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true. 4. arr.length 5. Any of these is correct - 0x5, 0x05, 0X05, 0X5 6. b, c, f, g 7. a 8. d 9. "am" 10. a, c. Please note that b is not correct. A package statement may appear before an import statement. A class constructor may be declared private also. Hence d is incorrect. 11. a 12. a 13. protected 14. a, c 15. b, c 16. c 17. a, d, e 18. d, e 19. a, c 20. b, c 21. b, c, e 22. b 23. d 24. a

25. a 26. b, e . The option c is incorrect because a Java identifier name cannot begin with a digit. 27. d 28. c 29. c, d 30. a, c 31. b, d 32. b, c 33. c 34. c 35. c 36. b, c 37. f 38. long 39. e 40. a 41. a, c 42. Set 43. a 44. d 45. b 46. int 47. d 48. a 49. f 50. c, d

http://www.javaprepare.com/quests/test2.html

Mock Exam 2 for SCJP 6


The mock exam is modeled on the Sun Certification for Java Programmer SCJP 6 exam. The exam has 29 questions. The real exam may be a little tougher than this. You need to score 58.33% correct answers to clear the real exam. Please let us know at ngabrani AT hotmail dot com if you find any issues with this exam. Some differences between this and the real exam are given below. a. The real exam will be tougher than this. b. The real exam will have 60 questions. This one has only 29 c. The real exam would have more programmatic questions. Questions of the type "what will happen when this code is compiled".

1. Which of the following are Java keywords? Select the three correct answers. A. external B. implement C. throw D. void E. integer F. private G. synchronize H. unsigned

2. Which of the following are legal definitions of the main method that can be used to execute a class. Select the one correct answer. A. public void main(String args) B. public static int main(String args[]) C. public static void main(String args[]) D. static public void MAIN(String args[]) E. public static void main(string args[]) F. public static void main(String *args)

3. Which of these are legal array declarations or definitions? Select the two correct answers. A. int[] []x[]; B. int *x; C. int x[5]; D. int[] x = {1,2,3};

4. Name the collection interface used to represent a sequence of numbers in a fixed order.

5. The class Hashtable is used to implement which collection interface. Select the one correct answer. A. Table B. List C. Set D. SortedSet E. Map

6. What gets printed when the following program is compiled and run? Select the one correct answer.

class test { public static void main(String args[]) { int i; do { i++; } while(i < 0); System.out.println(i); } }

A. B. C. D. E.

The program does not compile as i is not initialized. The program compiles but does not run. The program compiles and runs but does not print anything. The program prints 0. The program prints 1.

7. What gets printed when the following program is compiled and run? Select the one correct answer.

8. 9. 10. 11. class xyz { 12. 13. static int i; 14. 15. public static void main(String args[]) { 16. 17. 18. 19. while (i < 0) { 20. 21. i--; 22. 23. } 24. 25. System.out.println(i); 26. 27. } 28. 29. } 30. 31. 32.

A. B. C. D. E.

The program does not compile as i is not initialized. The program compiles but does not run. The program compiles and runs but does not print anything. The program prints 0. The program prints 1.

33. What gets printed when the following program is compiled and run? Select the one correct answer.

class xyz {

public static void main(String args[]) { int i,j,k; for (i = 0; i < 3; i++) { for(j=1; j < 4; j++) { for(k=2; k<5; k++) { if((i == j) && (j==k))

System.out.println(i); }

} } } }

A. B. C. D. E.

0 1 2 3 4

34. Using up to four characters what is the Java representation of the number 23 in hex?

35. What gets printed when the following program is compiled and run? Select the one correct answer.

class test { static boolean check; public static void main(String args[]) { int i; if(check == true) i=1; else i=2;

if(i=2) i=i+2; else i = i + 4; System.out.println(i); } }

A. B. C. D. E.

3 4 5 6 The program does not compile because of the statement if(i=2)

36. Select the one correct answer. The smallest number that can be represented using short primitive type in Java is A. 0 B. -127 C. -128 D. -16384 E. -32768 F. The smallest number is compiler dependent.

37. Given the following declarations, which of the assignments given in the options below would compile. Select the two correct answers.
38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50.

int i = 5; boolean t = true; float f = 2.3F; double d = 2.3;

A. B. C. D. E.

t = (boolean) i; f = d; d = i; i = 5; f = 2.8;

51. What gets printed when the following program is compiled and run. Select the one correct answer.
52. 53. 54. 55. public class incr { 56. 57. public static void main(String args[]) {

58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. } 72. 73. 74.

int i , j; i = j = 3; int n = 2 * ++i; int m = 2 * j++; System.out.println(i + " " + j + " " + n + " " + m); }

A. B. C. D. E. F.

4486 4488 4466 4386 4388 4468

75. Given two non-negative integers a and b and a String str, what is the number of characters in the expression str.substring(a,b) . Select the one correct answer. A. a + b B. a - b C. b - a - 1 D. b - a + 1 E. b - a F. b

76.

What is the result of compiling and running the following program. Select the one correct answer.

77. 78. 79. 80. class test { 81. 82. public static void main(String args[]) { 83. 84. char ch; 85. 86. String test2 = "abcd"; 87. 88. String test = new String("abcd"); 89. 90. if(test.equals(test2)) { 91. 92. if(test == test2) 93.

94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. } 119. 120. 121.

ch = test.charAt(0); else ch = test.charAt(1); } else { if(test == test2) ch = test.charAt(2); else ch = test.charAt(3); } System.out.println(ch); }

A. B. C. D.

'a' 'b' 'c' 'd'

122.

What is the result of compiling and running the following program. Select the one correct answer.

123. 124. 125. 126. class test { 127. 128. public static void main(String args[]) { 129. 130. int i,j=0; 131. 132. for(i=10;i<0;i--) { j++; } 133. 134. switch(j) { 135. 136. case (0) : 137. 138. j=j+1; 139. 140. case(1): 141. 142. j=j+2; 143. 144. break;

145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. } 171. 172. 173.

case (2) : j=j+3; break;

case (10) : j=j+10; break; default : break; } System.out.println(j); }

A. B. C. D. E. F.

0 1 2 3 10 20

174. What is the number displayed when the following program is compiled and run.

class test { public static void main(String args[]) { test test1 = new test(); System.out.println(test1.xyz(100)); } public int xyz(int num) { if(num == 1) return 1; else return(xyz(num-1) + num);

} }

175. Which of the following statements are true. Select the one correct answer. A. Arrays in Java are essentially objects. B. It is not possible to assign one array to another. Individual elements of array can however be assigned. C. Array elements are indexed from 1 to size of array. D. If a method tries to access an array element beyond its range, a compile warning is generated.

176. Which expression can be used to access the last element of an array. Select the one correct answer. A. array[array.length()] B. array[array.length() - 1] C. array[array.length] D. array[array.length - 1]

177. What is the result of compiling and running the following program. Select the one correct answer.

class test { public static void main(String args[]) { int[] arr = {1,2,3,4}; call_array(arr[0], arr); System.out.println(arr[0] + "," + arr[1]); } static void call_array(int i, int arr[]) { arr[i] = 6; i = 5; } }

A. B. C. D.

1,2 5,2 1,6 5,6

178. Which of the following statements are correct. Select the one correct answer. A. Each Java file must have exactly one package statement to specify where the class is stored. B. If a Java file has both import and package statement, the import statement must come before package statement. C. A Java file has at least one class defined. D. If a Java file has a package statement, it must be the first statement (except comments).

179. What happens when the following program is compiled and then the command "java check it out" is executed. Select the one correct answer.

class check { public static void main(String args[]) { System.out.println(args[args.length-2]); } }

A. The program does not compile. B. The program compiles but generates ArrayIndexOutOfBoundsException exception. C. The program prints java D. The program prints check E. The program prints it F. The program prints out

180. What all gets printed when the following code is compiled and run. Select the three correct answers.

class test { public static void main(String args[]) { int i[] = {0,1}; try { i[2] = i[0] + i[1]; } catch(ArrayIndexOutOfBoundsException e1) { System.out.println("1"); } catch(Exception e2) { System.out.println("2"); } finally { System.out.println(3); } System.out.println("4"); } }

A. B. C. D.

1 2 3 4

181. A program needs to store the name, salary, and age of employees in years. Which of the following data types should be used to create the Employee class. Select the three correct answers. A. char B. boolean C. Boolean

D. String E. int F. double

182. To make a variable defined in a class accessible only to methods defined in the classes in same package, which of the following keyword should be used. Select the one correct answer. A. By using the keyword package before the variable. B. By using the keyword private before the variable. C. By using the keyword protected before the variable. D. By using the keyword public before the variable. E. The variable should not be preceded by any of the above mentioned keywords.

183. In implementing two classes Employee and Manager, such that each Manager is an Employee, what should be the relationship between these classes. Select the one correct answer. A. Employee should be the base class of Manager class. B. Manager should be the base class of Employee class. C. Manager class should include the Employee class as a data member. D. Employee class should include Manager class as a data member. E. The Manager and Employee should not have any relationship.

184. Select the one most appropriate answer. What is the purpose of method parseInt defined in Integer class. A. The method converts an integer to a String. B. The method is used to convert String to an integer, assuming that the String represents an integer. C. The method is used to convert String to Integer class, assuming that the String represents an integer. D. The method converts the Integer object to a String.

185. What should be done to invoke the run() method on a thread for an object derived from the Thread class. Select the one correct answer. A. The run() method should be directly invoked on the Object. B. The start() method should be directly invoked on the Object. C. The init() method should be directly invoked on the Object. D. The creation of the object using the new operator would create a new thread and invoke its run() method.

186. A. B. C. D.

What is the default priority of a newly created thread. MIN_PRIORITY (which is defined as 1 in the Thread class.) NORM_PRIORITY (which is defined as 5 in the Thread class.) MAX_PRIORITY (which is defined as 10 in the Thread class.) A thread inherits the priority of its parent thread.

Answers to Sample Test 2 1. c, d, f 2. c. The main method must be static and return void. Hence a and b are incorrect. It must take an array of String as argument. Hence e and f are incorrect. As Java is case sensitive, d is incorrect. 3. a, d 4. List 5. e. The collection interface Map has two implementation HashMap and Hashtable. 6. a. Local variables are not initialized by default. They must be initialized before they are used. 7. d. The variable i gets initialized to zero. The while loop does not get executed. 8. c. During various iterations of three loops, the only time i, j and k have same values are when all of them are set to 2. 9. 0x17 or 0X17. 10. e. The statement "i=2" evaluates to 2. The expression within the if block must evaluate to a boolean. 11. e. The range of short primitive type is -32768 to 32767. 12. c,d. Java does not allow casts between boolean values and any numeric types. Hence a is incorrect. Assigning double to a float requires an explicit cast. Hence b and e are incorrect. 13. a 14. e 15. b. Both Strings test and test2 contain "abcd" . They are however located at different memory addresses. Hence test == test2 returns false, and test.equals(test2) returns true. 16. d. The for loop does not get executed even once as the condition (i < 0) fails in the first iteration. In the switch statement, the statement j = j +1; gets executed, setting j to 1. As there is no break after this case, the next statement also gets executed setting j to 3. 17. 5050. The recursive function xyz essentially sums up numbers 1 to num. This evaluates to (num * (num + 1))/2. 18. a. Java supports assignment of one array to another. Hence b is incorrect. Array elements are indexed from 0. Hence c is incorrect. A method that accesses array elements out of its range does not generate a compilation error. Hence d is incorrect. 19. d. array.length gives the number of elements in the array. As indexes in Java start from 0, d is the correct answer. 20. c. In the invocation of call_array, the first element is invoked using call-byvalue, and the second using call-by-reference.

21. d. import statement, package statement and class definitions are all optional in a file. Hence a and c are incorrect. If both import and package statements are present in a file, then package statement must appear before the import statement. Hence b is incorrect. 22. e. The args array consists of two elements "it" and "out". args.length is set to two. 23. a,c,d. The exception ArrayIndexOutOfBoundsException is generated as the main method tries to access i[2]. Hence 1 gets printed. After this finally block gets excuted, before the program exits. 24. d,e,f 25. e. A data member that does not have public/protected/private is accessible to all methods in the same package. 26. a. The Manager and Employee share as "is a" relationship - A Manager is an Employee. This is captured by making Employee the base class of Manager. 27. b. The method int parseInt(Sting s) returns the integer value corresponding to input String, assuming that the input string represents an integer in base 10. 28. b. The start() method invokes the run() method when the thread is ready to execute. 29. d

http://www.javaprepare.com/quests/funda_q.html

Questions on Language Fundamentals


1. Which of these are legal identifiers. Select the three correct answers. A. number_1 B. number_a C. $1234 D. -volatile 2. Which of these are not legal identifiers. Select the four correct answers. A. 1alpha B. _abcd C. xy+abc D. transient E. account-num F. very_long_name 3. Which of the following are keywords in Java. Select the two correct answers. A. friend B. NULL C. implement D. synchronized E. throws 4. Which of the following are Java keywords. Select the four correct answers. A. super B. strictfp C. void D. synchronize E. instanceof 5. Which of these are Java keywords. Select the five correct answers A. TRUE B. volatile C. transient D. native E. interface F. then G. new 6. Using up to four characters, write the Java representation of octal literal 6. 7. Using up to four characters, write the Java representation of integer literal 3 in hexadecimal. 8. Using up to four characters, write the Java representation of integer literal 10 in hexadecimal. 9. What is the minimum value of char type. Select the one correct answer. A. 0 B. -215 C. -28 D. -215 - 1 E. -216 F. -216 - 1

10. How many bytes are used to represent the primitive data type int in Java. Select the one correct answer. A. 2 B. 4 C. 8 D. 1 E. The number of bytes to represent an int is compiler dependent. 11. What is the legal range of values for a variable declared as a byte. Select the one correct answer. A. 0 to 256 B. 0 to 255 C. -128 to 127 D. -128 to 128 E. -127 to 128 F. -215 to 215 - 1 12. The width in bits of double primitive type in Java is --. Select the one correct answer. A. The width of double is platform dependent B. 64 C. 128 D. 8 E. 4 13. What would happen when the following is compiled and executed. Select the one correct answer.
14. 15. public class Compare { 16. public static void main(String args[]) { 17. int x = 10, y; 18. if(x < 10) 19. y = 1; 20. if(x>= 10) y = 2; 21. System.out.println("y is " + y); 22. } 23. } 24.

The program compiles and prints y is 0 when executed. The program compiles and prints y is 1 when executed. The program compiles and prints y is 2 when executed. The program does not compile complaining about y not being initialized. The program throws a runtime exception. 25. What would happen when the following is compiled and executed. Select the one correct answer.
26. 27. class example { 28. int x; 29. int y; 30. String name; 31. public static void main(String args[]) { 32. example pnt = new example(); 33. System.out.println("pnt is " + pnt.name + 34. " " + pnt.x + " " + pnt.y); 35. } 36. } 37.

A. B. C. D. E.

A. The program does not compile because x, y and name are not initialized. B. The program throws a runtime exception as x, y, and name are used before initialization. C. The program prints pnt is 0 0. D. The program prints pnt is null 0 0. E. The program prints pnt is NULL false false 38. The initial value of an instance variable of type String that is not explicitly initialized in the program is --. Select the one correct answer. A. null B. "" C. NULL D. 0 E. The instance variable must be explicitly assigned. 39. The initial value of a local variable of type String that is not explicitly initialized and which is defined in a member function of a class. Select the one correct answer. A. null B. "" C. NULL D. 0 E. The local variable must be explicitly assigned. 40. Which of the following are legal Java programs. Select the four correct answers. A. // The comments come before the package
package pkg; import java.awt.*; class C{} package pkg; import java.awt.*; class C{} package pkg1; package pkg2; import java.awt.*; class C{} package pkg; import java.awt.*; import java.awt.*; class C{} import java.awt.*; package pkg; class C {}

B. C.

D. E. F.

41. Which of the following statements are correct. Select the four correct answers. A. A Java program must have a package statement. B. A package statement if present must be the first statement of the program (barring any comments). C. If a Java program defines both a package and import statement, then the import statement must come before the package statement. D. An empty file is a valid source file. E. A Java file without any class or interface definitions can also be compiled. F. If an import statement is present, it must appear before any class or interface definitions.

42.

What would be the results of compiling and running the following class. Select the one correct answer.

43. 44. class test { 45. public static void main() { 46. System.out.println("test"); 47. } 48. } 49.

A. The program does not compile as there is no main method defined. B. The program compiles and runs generating an output of "test" C. The program compiles and runs but does not generate any output. D. The program compiles but does not run. 50. Which of these are valid declarations for the main method? Select the one correct answer. A. public void main(); B. public static void main(String args[]); C. static public void main(String); D. public static void main(String ); E. public static int main(String args[]); 51. Which of the following are valid declarations for the main method. Select the three correct answers. A. public static void main(String args[]); B. public static void main(String []args); C. final static public void main (String args[]); D. public static int main(String args[]); E. public static abstract void main(String args[]); 52. What happens when the following program is compiled and executed with the command - java test. Select the one correct answer.
53. 54. class test { 55. public static void main(String args[]) { 56. if(args.length > 0) 57. System.out.println(args.length); 58. } 59. } 60.

A. The program compiles and runs but does not print anything. B. The program compiles and runs and prints 0 C. The program compiles and runs and prints 1 D. The program compiles and runs and prints 2 E. The program does not compile. 61. What is the result of compiling and running this program? Select the one correct answer.
62. 63. public class test { 64. public static void main(String args[]) { 65. int i, j; 66. int k = 0; 67. j = 2; 68. k = j = i = 1; 69. System.out.println(k); 70. } 71. } 72.

73.

A. The program does not compile as k is being read without being initialized. B. The program does not compile because of the statement k = j = i = 1; C. The program compiles and runs printing 0. D. The program compiles and runs printing 1. E. The program compiles and runs printing 2. 74. What gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the one correct answer.
75. 76. public class test { 77. public static void main(String args[]) { 78. System.out.println(args[0]+" "+args[args.length-1]); 79. } 80. } 81.

The program will throw an ArrayIndexOutOfBounds exception. The program will print "java test" The program will print "java happens"; The program will print "test happens" The program will print "lets happens" 82. What gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the one correct answer.
83. 84. public class test { 85. public static void main(String args[]) { 86. System.out.println(args[0]+" "+args[args.length]); 87. } 88. } 89.

A. B. C. D. E.

The program will throw an ArrayIndexOutOfBounds exception. The program will print "java test" The program will print "java happens"; The program will print "test happens" The program will print "lets happens" 90. What all gets printed on the standard output when the class below is compiled and executed by entering "java test lets see what happens". Select the two correct answers.
91. 92. public class test { 93. public static void main(String args[]) { 94. System.out.println(args[0]+" "+args.length); 95. } 96. } 97.

A. B. C. D. E.

A. B. C. D. E. F. G.

java test lets 3 4 5 6

98.

What happens when the following program is compiled and run. Select the one correct answer.

99. 100. public class example { 101. int i = 0; 102. public static void main(String args[]) { 103. int i = 1; 104. i = change_i(i); 105. System.out.println(i); 106. } 107. public static int change_i(int i) { 108. i = 2; 109. i *= 2; 110. return i; 111. } 112. } 113.

The program does not compile. The program prints 0. The program prints 1. The program prints 2. The program prints 4. 114. What happens when the following program is compiled and run. Select the one correct answer.
115. 116. public class example { 117. int i = 0; 118. public static void main(String args[]) { 119. int i = 1; 120. change_i(i); 121. System.out.println(i); 122. } 123. public static void change_i(int i) { 124. i = 2; 125. i *= 2; 126. } 127. } 128.

A. B. C. D. E.

The program does not compile. The program prints 0. The program prints 1. The program prints 2. The program prints 4. 129. What happens when the following program is compiled and run. Select the one correct answer.
130. 131. public class example { 132. int i[] = {0}; 133. public static void main(String args[]) { 134. int i[] = {1}; 135. change_i(i); 136. System.out.println(i[0]); 137. } 138. public static void change_i(int i[]) { 139. i[0] = 2; 140. i[0] *= 2; 141. } 142. }

A. B. C. D. E.

143.

The program does not compile. The program prints 0. The program prints 1. The program prints 2. The program prints 4. 144. What happens when the following program is compiled and run. Select the one correct answer.
145. 146. public class example { 147. int i[] = {0}; 148. public static void main(String args[]) { 149. int i[] = {1}; 150. change_i(i); 151. System.out.println(i[0]); 152. } 153. public static void change_i(int i[]) { 154. int j[] = {2}; 155. i = j; 156. } 157. } 158.

A. B. C. D. E.

A. B. C. D. E.

The program does not compile. The program prints 0. The program prints 1. The program prints 2. The program prints 4.

Answers to questions on Language Fundamentals a, b, c a, c, d, e d, e a, b, c, e. Please note that strictfp is a new keyword in Java 2. See Sun's site for more details. 5. b, c, d, e, g 6. Any of the following are correct answers - 06, 006, or 0006 7. Any of the following are correct answers - 0x03, 0X03, 0X3 or 0x3 8. Any of the following are correct answers - 0x0a, 0X0a, 0Xa, 0xa, 0x0A, 0X0A, 0XA, 0xA 9. a 10. b 11. c 12. b 13. d. The variable y is getting read before being properly initialized. 14. d. Instance variable of type int and String are initialized to 0 and null respectively. 15. a 16. e 17. a, b, d, e 18. b, d, e, f 1. 2. 3. 4.

19. d 20. b 21. a, b, c 22. a 23. d 24. e 25. a 26. c, e 27. e 28. c 29. e 30. c

http://www.javaprepare.com/quests/operat_q.html

Questions on Operator and Assignments


1.

In the following class definition, which is the first line (if any) that causes a compilation error. Select the one correct answer.

2. 3. public class test { 4. public static void main(String args[]) { 5. char c; 6. int i; 7. c = 'A'; // 1 8. i = c; //2 9. c = i + 1; //3 10. c++; //4 11. } 12. } 13.

A. The line labeled 1. B. The line labeled 2. C. The line labeled 3. D. The line labeled 4. E. All the lines are correct and the program compiles. 14. Which of these assignments are valid. Select the four correct answers. A. short s = 28; B. float f = 2.3; C. double d = 2.3; D. int I = '1'; E. byte b = 12; 15. What gets printed when the following program is compiled and run. Select the one correct answer.
16. 17. class test { 18. public 19. 20. 21. 22. 23. 24. } 25. } 26. static void main(String args[]) { int i,j,k,l=0; k = l++; j = ++k; i = j++; System.out.println(i);

A. 0 B. 1 C. 2 D. 3 27. Which of these lines will compile? Select the four correct answers. A. short s = 20; B. byte b = 128; C. char c = 32; D. double d = 1.4;; E. float f = 1.4;

F. byte e = 0; 28. The signed right shift operator in Java is --. Select the one correct answer. A. <<; B. >> C. >>>; D. None of these. 29. What gets printed on the standard output when the class below is compiled and executed. Select the one correct answer.
30. 31. public class ShortCkt { 32. public static void main(String args[]) { 33. int i = 0; 34. boolean t = true; 35. boolean f = false, b; 36. b = (t && ((i++) == 0)); 37. b = (f && ((i+=2) > 0)); 38. System.out.println(i); 39. } 40. } 41.

0 1 2 3 42. What gets printed on the standard output when the class below is compiled and executed. Select the one correct answer.
43. 44. public class ShortCkt { 45. public static void main(String args[]) { 46. int i = 0; 47. boolean t = true; 48. boolean f = false, b; 49. b = (t & ((i++) == 0)); 50. b = (f & ((i+=2) > 0)); 51. System.out.println(i); 52. } 53. } 54.

A. B. C. D.

0 1 2 3 55. What gets printed on the standard output when the class below is compiled and executed. Select the one correct answer.
56. 57. public class ShortCkt { 58. public static void main(String args[]) { 59. int i = 0; 60. boolean t = true; 61. boolean f = false, b; 62. b = (t || ((i++) == 0)); 63. b = (f || ((i+=2) > 0)); 64. System.out.println(i); 65. } 66. } 67.

A. B. C. D.

A. 0

B. 1 C. 2 D. 3 68. What gets printed on the standard output when the class below is compiled and executed. Select the one correct answer.
69. 70. public class ShortCkt { 71. public static void main(String args[]) { 72. int i = 0; 73. boolean t = true; 74. boolean f = false, b; 75. b = (t | ((i++) == 0)); 76. b = (f | ((i+=2) > 0)); 77. System.out.println(i); 78. } 79. } 80.

A. 0 B. 1 C. 2 D. 3 81. Which operator is used to perform bitwise inversion in Java. Select the one correct answer. A. ~ B. ! C. & D. | E. ^ 82. What gets printed when the following program is compiled and run. Select the one correct answer.
83. 84. 85. public class test { 86. public static void main(String args[]) { 87. byte x = 3; 88. x = (byte)~x; 89. System.out.println(x); 90. } 91. } 92. 93.

3 0 1 11 252 214 124 -4 94. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
95. 96. public class test { 97. public static void main(String args[]) { 98. int x,y;

A. B. C. D. E. F. G. H.

99. 100. 101. 102. 103. } 104.

x = 3 & 5; y = 3 | 5; System.out.println(x + " " + y); }

71 37 17 31 13 73 75 105. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
106. 107. public class test { 108. public static void main(String args[]) { 109. int x,y; 110. x = 1 & 7; 111. y = 3 ^ 6; 112. System.out.println(x + " " + y); 113. } 114. } 115.

A. B. C. D. E. F. G.

13 35 51 36 17 15 116. Which operator is used to perform bitwise exclusive or. A. & B. ^ C. | D. ! E. ~ 117. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
118. 119. public class test { 120. public static void main(String args[]) { 121. boolean x = true; 122. int a; 123. if(x) a = x ? 1: 2; 124. else a = x ? 3: 4; 125. System.out.println(a); 126. } 127. } 128.

A. B. C. D. E. F.

A. B. C. D.

1 2 3 4

129.

What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.

130. 131. public class test { 132. public static void main(String args[]) { 133. boolean x = false; 134. int a; 135. if(x) a = x ? 1: 2; 136. else a = x ? 3: 4; 137. System.out.println(a); 138. } 139. } 140.

1 2 3 4 141. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
142. 143. public class test { 144. public static void main(String args[]) { 145. int x, y; 146. 147. x = 5 >> 2; 148. y = x >>> 2; 149. System.out.println(y); 150. } 151. } 152.

A. B. C. D.

5 2 80 0 64 153. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
154. 155. public class test { 156. public static void main(String args[]) { 157. int x; 158. 159. x = -3 >> 1; 160. x = x >>> 2; 161. x = x << 1; 162. System.out.println(x); 163. } 164. } 165.

A. B. C. D. E.

A. B. C. D. E. F. 166.

1 0 7 5 23 2147483646 Which of the following are correct. Select all correct answers.

Java provides two operators to do left shift - << and <<<. >> is the zero fill right shift operator. >>> is the signed right shift operator. For positive numbers, results of operators >> and >>> are same. 167. What is the result of compiling and running the following program. Select one correct answer.
168. 169. public class test { 170. public static void main(String args[]) { 171. int i = -1; 172. i = i >> 1; 173. System.out.println(i); 174. } 175. } 176.

A. B. C. D.

63 -1 0 1 127 128 255 177. What all gets printed when the following gets compiled and run. Select the two correct answers.
178. 179. public class example { 180. public static void main(String args[]) { 181. int x = 0; 182. if(x > 0) x = 1; 183. 184. switch(x) { 185. case 1: System.out.println(1); 186. case 0: System.out.println(0); 187. case 2: System.out.println(2); 188. break; 189. case 3: System.out.println(3); 190. default: System.out.println(4); 191. break; 192. } 193. } 194. } 195.

A. B. C. D. E. F. G.

0 1 2 3 4 196. What happens when the following class is compiled and run. Select one correct answer.
197. 198. public class test { 199. public static void main(String args[]) { 200. int x = 0, y = 1, z; 201. if(x) 202. z = 0; 203. else 204. z = 1;

A. B. C. D. E.

205. 206. 207. 208. 209. 210. 211. 212. } 213.

if(y) z = 2; else z = 3; System.out.println(z); }

The program prints 0 The program prints 1 The program prints 2 The program prints 3 The program does not compile because of problems in the if statement. 214. Which all lines are part of the output when the following code is compiled and run. Select the nine correct answers.
215. 216. public class test { 217. public static void main(String args[]) { 218. for(int i = 0; i < 3; i++) { 219. for(int j = 3; j >= 0; j--) { 220. if(i == j) continue; 221. System.out.println(i + " " + j); 222. } 223. } 224. } 225. } 226.

A. B. C. D. E.

00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 The program does not print anything. 227. Which all lines are part of the output when the following code is compiled and run. Select the one correct answer.
228. 229. public class test { 230. public static void main(String args[]) { 231. for(int i = 0; i < 3; i++) { 232. for(int j = 3; j <= 0; j--) { 233. if(i == j) continue; 234. System.out.println(i + " " + j); 235. } 236. }

A. B. C. D. E. F. G. H. I. J. K. L. M. N. O. P. Q.

237. 238. } 239.

00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 The program does not print anything. 240. Which all lines are part of the output when the following code is compiled and run. Select the six correct answers.
241. 242. public class test { 243. public static void main(String args[]) { 244. for(int i = 0; i < 3; i++) { 245. for(int j = 3; j >= 0; j--) { 246. if(i == j) break; 247. System.out.println(i + " " + j); 248. } 249. } 250. } 251. } 252.

A. B. C. D. E. F. G. H. I. J. K. L. M. N. O. P. Q.

00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 253. Which all lines are part of the output when the following code is compiled and run. Select the six correct answers.
254.

A. B. C. D. E. F. G. H. I. J. K. L. M. N. O. P.

255. public class test { 256. public static void main(String args[]) { 257. outer: for(int i = 0; i < 3; i++) { 258. for(int j = 3; j >= 0; j--) { 259. if(i == j) continue outer; 260. System.out.println(i + " " + j); 261. } 262. } 263. } 264. } 265.

00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 266. Which all lines are part of the output when the following code is compiled and run. Select the three correct answers.
267. 268. public class test { 269. public static void main(String args[]) { 270. outer : for(int i = 0; i < 3; i++) { 271. for(int j = 3; j >= 0; j--) { 272. if(i == j) break outer; 273. System.out.println(i + " " + j); 274. } 275. } 276. } 277. } 278.

A. B. C. D. E. F. G. H. I. J. K. L. M. N. O. P.

A. B. C. D. E. F. G. H. I. J. K. L. M.

00 01 02 03 10 11 12 13 20 21 22 23 30

N. 3 1 O. 3 2 P. 3 3

Answers to questions on Operators and Assignments 1. 2. 3. 4. c. It is not possible to assign an integer to a character in this case without a cast. a, c, d, e. 2.3 is of type double. So it cannot be assigned to a float without a cast. b a, c, d, f. If RHS (Right hand side) is an integer within the correct range of LHS (Left hand side), and if LHS is char, byte, or short, no cast is required. A decimal number is a double by default. Assigning it to float requires a cast. 5. b 6. b. In the second assignment to variable b, the expression (i+=2) does not get evaluated. 7. d 8. c 9. d 10. a 11. h 12. c 13. f 14. b 15. a 16. d 17. d 18. f 19. d 20. b 21. a, c 22. e. The expression in the if statement must evaluate to a boolean. 23. b, c, d, e, g, h, i, j, l 24. q 25. b, c, d, g, h, l 26. b, c, d, g, h, l 27. b, c, d

http://www.javaprepare.com/quests/declar_q.html

Questions on Declaration and Access Control


1. Given a one dimensional array arr, what is the correct way of getting the number of elements in arr. Select the one correct answer. A. arr.length B. arr.length - 1 C. arr.size D. arr.size - 1 E. arr.length() F. arr.length() - 1 2. Which of these statements are legal. Select the three correct answers. A. int arr[][] = new int[5][5]; B. int []arr[] = new int[5][5]; C. int[][] arr = new int[5][5]; D. int[] arr = new int[5][]; E. int[] arr = new int[][5]; 3. Write the expression to access the number of elements in a one dimensional array arr. The expression should not be assigned to any variable. 4. Which of these array declarations and initializations are legal? Select the two correct answers. A. int arr[4] = new int[4]; B. int[4] arr = new int[4]; C. int arr[] = new int[4]; D. int arr[] = new int[4][4]; E. int[] arr = new int[4]; 5. What will the result of compiling and executing the following program. Select the one correct answer.
6. 7. class Test { 8. 9. public static void main(String args[]) { 10. 11. int arr[] = new int[2]; 12. 13. System.out.println(arr[0]); 14. 15. } 16. 17. } 18.

A. The program does not compile because arr[0] is being read before being initialized. B. The program generates a runtime exception because arr[0] is being read before being initialized. C. The program compiles and prints 0 when executed. D. The program compiles and prints 1 when executed. E. The program compiles and runs but the results are not predictable because of un-initialized memory being read.

19. Which of the following are legal declaration and definition of a method. Select all correct answers. A. void method() {}; B. void method(void) {}; C. method() {}; D. method(void) {}; E. void method {}; 20. Which of the following are valid constructors within a class Test. Select the two correct answers. A. test() { } B. Test() { } C. void Test() { } D. private final Test() { } E. abstract Test() { } F. Test(Test t) { } G. Test(void) { } 21. What is the result of compiling and running the following class. Select the one correct answer.
22. 23. 24. 25. class Test { 26. 27. public void methodA(int i) { 28. 29. System.out.println(i); 30. 31. } 32. 33. public int methodA(int i) { 34. 35. System.out.println(i+1); 36. 37. return i+1; 38. 39. } 40. 41. public static void main(String args[]) { 42. 43. Test X = new Test(); 44. 45. X.methodA(5); 46. 47. } 48. 49. } 50. 51. 52.

Select the one correct answer. A. The program compiles and runs printing 5. B. The program compiles and runs printing 6. C. The program gives runtime exception because it does not find the method Test.methodA(int)

D. The program give compilation error because methodA is defined twice in class Test.

Answers to questions on Declarations 1. 2. 3. 4. 5. 6. 7. a a, b, c arr.length c, e. The size of the array should not be specified when declaring the array. c a b, f. A constructor must have the same name as the class, hence a is not a constructor. It must not return any value, hence c is not correct. A constructor cannot be declared abstract or final. 8. d

http://www.javaprepare.com/quests/class_q.html

Questions on Classes
1.

What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.

2. 3. protected class example { 4. public static void main(String args[]) { 5. String test = "abc"; 6. test = test + test; 7. System.out.println(test); 8. } 9. } 10.

A. The class does not compile because the top level class cannot be protected. B. The program prints "abc" C. The program prints "abcabc" D. The program does not compile because statement "test = test + test" is illegal. 11. A top level class may have only the following access modifier. Select the one correct answer. A. package B. friendly C. private D. protected E. public 12. Write down the modifier of a method that makes the method available to all classes in the same package and to all the subclasses of this class. 13. Select the one most appropriate answer. A top level class without any modifier is accessible to A. any class B. any class within the same package C. any class within the same file D. any subclass of this class. 14. Is this True or False. In Java an abstract class cannot be sub-classed. 15. Is this True or False. In Java a final class must be sub-classed before it can be used. 16. Which of the following are true. Select the three correct answers. A. A static method may be invoked before even a single instance of the class is constructed. B. A static method cannot access non-static methods of the class. C. Abstract modifier can appear before a class or a method but not before a variable. D. final modifier can appear before a class or a variable but not before a method. E. Synchronized modifier may appear before a method or a variable but not before a class.

Answers to questions on classes in Java 1. 2. 3. 4. 5. 6. 7. a e protected b False False a, b, c. final modifier may appear before a method, a variable or before a class.

http://www.javaprepare.com/quests/files_q.html

Questions on Files and Input/Output


1. Which abstract class is the super class of all classes used for reading bytes. Select the one correct answer. A. Reader B. FileReader C. ByteReader D. InputStream E. FileInputStream 2. Which abstract class is the super class of all classes used for writing characters. Select the one correct answer. A. Writer B. FileWriter C. CharWriter D. OutputStream E. FileOutputStream 3. Which of these are legal ways of accessing a File named "file.tst" for reading. Select the two correct answers. A. FileReader fr = new FileReader("file.tst"); B. FileInputStream fr = new FileInputStream("file.tst"); InputStreamReader isr = new InputStreamReader(fr, "UTF8"); C. FileReader fr = new FileReader("file.tst", "UTF8"); D. InputStreamReader isr = new InputStreamReader("file.tst"); 4. Name the class that allows reading of binary representations of Java primitives from an input byte stream. 5. Which of these classes are abstract. Select the three correct answers. A. FilterWriter B. Reader C. InputStream D. CharArrayReader E. DataInputStream 6. Name the exception thrown by the read method defined in InputStream class Answers to questions on Files and I/O 1. d 2. a 3. a, b. FileReader class uses the default character encoding, hence c is incorrect. InputStreamReader character class does not have a constructor that takes file name as an argument. Hence d is incorrect. 4. DataInpiutStream 5. a,b,c 6. IOException

http://www.javaprepare.com/quests/collct_q.html

Questions on Collections
1. TreeMap class is used to implement which collection interface. Select the one correct answer. A. Set B. SortedSet C. List D. Tree E. SortedMap 2. Name the Collection interface implemented by the Vector class. 3. Name the Collection interface implemented by the Hashtable class. 4. Name the Collection interface implemented by the HashSet class. 5. Which of these are interfaces in the collection framework. Select the two correct answers. A. Set B. List C. Array D. Vector E. LinkedList 6. Which of these are interfaces in the collection framework. Select the two correct answers. A. HashMap B. ArrayList C. Collection D. SortedMap E. TreeMap 7. What is the name of collection interface used to maintain non-unique elements in order. 8. What is the name of collection interface used to maintain unique elements. 9. What is the name of collection interface used to maintain mappings of keys to values. 10. Is this true or false. Map interface is derived from the Collection interface. A. True B. False Answers to questions on Collections 1. e 2. List 3. Map 4. Set 5. a,b 6. c,d 7. List 8. Set 9. Map 10. b

http://www.javaprepare.com/quests/assert_q.html

Questions on Assertions
This topic is part of SCJP 1.4 exam but not SCJP 1.2 exam. 1. What happens when the following code is compiled and run. Select the one correct answer.

for(int i = 1; i < 3; i++) for(int j = 3; j > i; j--) assert i!=j {System.out.println(i); }

A. B. C. D. E.

The class compiles and runs, but does not print anything. The number 1 gets printed with AssertionError The number 2 gets printed with AssertionError The number 3 gets printed with AssertionError The program generates a compilation error.

2. What happens when the following code is compiled and run. Select the one correct answer.

for(int i = 1; i < 3; i++) for(int j = 3; j >= 1; j--) assert i!=j : i;

A. B. C. D. E.

The class compiles and runs, but does not print anything. The number 1 gets printed with AssertionError The number 2 gets printed with AssertionError The number 3 gets printed with AssertionError The program generates a compilation error.

3. What happens when the following code is compiled and run. Select the one correct answer.

for(int i = 1; i < 4; i++) for(int j = 1; j < 4; j++) if(i < j) assert i!=j : i;

A. The class compiles and runs, but does not print anything. B. The number 1 gets printed with AssertionError C. The number 2 gets printed with AssertionError

D. The number 3 gets printed with AssertionError E. The program generates a compilation error.

4. Which of the following statement is true about the assert statement. Select the one correct answer. A. If a Java class contains assert statements, then it must be compiled with 1.4 option. B. When a program having assertions is run, -assertion option must be specified, otherwise the assertions get ignored. C. A possible syntax of assert statement is assert logical_expression If logical_expression evaluates to true, the program generates an AssertionError. D. The program terminates on its first AssertionError.

Answers to questions on Assertions 1. e. The condition in assert statement must be followed by a semi-colon. 2. b. When i and j are both 1, assert condition is false, and AssertionError gets generated. 3. a. When the if condition returns true, the assert statement also returns true. Hence AssertionError does not get generated. 4. d. The option A is incorrect, as the Java compiler option is -source 1.4 . The option B is incorrect, as the runtime option is -ea or -enableassertions. If the logical expression evaluates to false, then the program generates an AssertionError, hence C is incorrect.