You are on page 1of 46

Java Puzzles

Author Date Version Declaration: I hereby declare that this document is based on my personal experiences. To the best of my knowledge, this document does not contain any material that infringes the copyrights of any other individual or organization including the customers of Infosys. Target Audience: Java Developers, People who are quite familiar with Java Programming. It will be very helpful for the people who are preparing for SCJP or internal certification of Java. Summary This document contains some of the interesting behaviors of Java Programming Language. The content here is given in the form of question and answers which includes many tricky responses and unknown behaviors of Java. This content is collected from standard study materials of SCJP 1.4. : : : Sudhindra GS (sudhindra_s) 12/12/06 1.1

Chapter 1: Language Fundamentals


1) Mention the unused reserved words in Java.(Select two) a) b) c) d) e) const include goto volatile overload

Ans: a, c const and goto are the keywords in Java which are unused. Include and overload are not keywords in Java. And the keyword volatile is used for declaring the volatile variables (variables which may change out of sync because it is used in threads) 2) null, true and false are keywords in Java a) TRUE b) FALSE Ans: FALSE null, false and true are reserved literals in Java not keywords. 3) What is the numerical range of a char? (Choose one.) a) b) c) d) e) 128 to 127 (2^15) to (2^15)-1 0 to 32767 Platform dependent 0 to 65535

Ans: e Behind the scene, char behaves like 16 bit signed integer. 4) Which among the following declarations compile without error a) b) c) d) e) f) char char char char char char a = 0x892; b = 071; c = 08; d = 70000; e = -93; f = \u004E

Ans: a,b,f Ans a is hexadecimal representation of integer. 071 represents octal integer. 08 is not valid since there is no digit 8 in octal system 70000 is out of char range, so it will work only with the type cast -93 looks ridiculous but still legal if there is a typecast \u004E is the Unicode representation of character N 5) What will be the output of the following program 1. 2. 3. 4. 5. 6. public cl\u0061ss Test{ public static void main(String \u0061rgs[]){ ch\u0061r \u0061 = '\u0061'; System.out.println(a); } }

a) Compiles properly but will not print anything b) Compiles and prints a c) Compilation Error d) Runtime Error Ans: b \u0061 is the Unicode representation of a and we can use it in the programs like above. 6) Given the following 1.public class testUninitialise{ 2. public static void main(String args[]){ 3. int i; 4. int j = 5; 5. if(j == 5){ 6. i=j; 7. } 8. If(i == 4){ 9. System.out.println(i); 10. } 11. } 12.} What is the output of the given code? a) b) c) d) e) 5 Compilation error at line number 8 Compilation error at line number 9 Run time exception No output

Ans: b This will give compilation error variable i might not have been initialized. This is because initialization of i is done inside if block. 7) Which among the following are valid character declarations?(Chose 3) a) b) c) d) e) f) char char char char char char c1 c2 c3 c4 c5 c6 = = = = = = 02667; 0xabcd; abcd; \u0041; \uface; \iface;

Ans: a,b,d Behind the scene, char variables work like 16 bit signed integers. So it is legal to assign signed numbers in decimal, octal and hexadecimal form. *a is correct because the number which is assigned is octal *in b, the assigned number is hexadecimal

*In d, \u0041 is missing single quotes *the option e represents Unicode representation of character 8) Which among the following is valid float declaration? a) b) c) d) float float float float f1 f2 f3 f4 = = = = 0.7; 10; 192.6f; 42e2;

Ans: b,c a is false because by default all real numbers are double which will not be typecasted to float by default. In b, the integer value is assigned to float which is legal because both integer and float takes same bytes of memory(32 bits) and conversion will not lead to any loss of precision. Option c is implicit typecasting and is correct. Option d is again trying to assign double literal to float which may lead in loss of precision. Hence it is illegal. 9) What will be the output of the following program? public class Test{ public static void main(String args[]){ int a[] = new int[3]; int b[] = new int[2]; for(int i=0;i<3;i++){ a[i]=i; } for(int i=0;i<2;i++){ b[i] = i+4; } b=a; for(int i=0;i<3;i++){ System.out.println(b[i]); }

} }

a) 0 1 2 b) Compilation Error c) Exception thrown at the run time. Ans: a The program runs without error. Here b initially refers to an array of 2 elements which is then assigned to an array of three elements. The former will be garbage collected after the assignment.

Chapter 2: Declarations and Access Control


10) a) b) c) d) e) f) g) h) i) j) k) l) m) Which among the following will give compilation error? protected abstract void m1(){} protected abstract void m1(); static final void m1(){} static final void m1(); transient private native void m1(); private native void m1(){}; private native void m1(); synchronized public final void m1(){} abstract public final void m1(){} abstract synchronized void m1(); abstract strictfp void m1(); abstract static void m1(); abstract native void m1();

Ans: a,d,e,f,i,j,k,l,m *Option a will give error because the abstract functions should not have body *Option d will give error because if the method is not abstract, it should be defined *Option e is incorrect because of the wrong usage of keyword transient. The keyword transient will be used for instance variables only. *f will give error because native methods cannot have definitions *Option i,j,k,l and m gives error because of illegal combination of modifiers. 11) Which among the following modifiers can be used with instance variables? a) b) c) d) e) f) final transient abstract synchronized strictfp native

Ans: a,b *final is used to restrict the value of variable from being changed *by using transient, the variable will not be included in the serialization process. Serialization is a process of storing the state of the object by which objects can be written to IO Streams or files. *synchronized and native can be used only with methods. *strictfp and abstract can be used with only classes and methods. 12) Which among the following modifiers can be used with both instance variables and local variables? a) public b) private c) protected

d) e) f) g) h)

transient volatile abstract static final

Ans: h All the other modifiers can be used with instance variables only 13) What will be the output of the following code?

1.public class Test{ 2. final int x; 3. 4. public static void main(String args[]){ 5. System.out.println("In main function"); 6. } 7.} a) b) c) d) In main function. Compilation error pointing to line 1. Compilation error pointing to line 2. Exception will be thrown at run time.

Ans: b The final variables must be assigned a value either in intializer or in every constructor. The error message will be like this Test.java:1: variable x might not have been initialized public class Test{ ^ 1 error 14) What will be the output of the following code?

1.public class Test{ 2. final int x; 3. 4. void Test(){ 5. x=10; 6. } 7. 8. public static void main(String args[]){ 9. System.out.println("Inside Main"); 10. } 11.} a) b) c) d) Inside main Compilation Error pointing to line 1 Compilation Error pointing to line 2 Compilation Error pointing to line 5

Ans: d The error message will be Test.java:5: cannot assign a value to final variable x x=10; ^ 1 error Note that the function void Test() is not a constructor. 15) What will be the output of the following code?

1.public class Test{ 2. final int x; 3. 4. Test(){ 5. x=10; 6. } 7. 8. Test(int x){ 9. x=x; 10. } 11. 12. public static void main(String args[]){ 13. System.out.println("Inside Main"); 14. } 15.} a) b) c) d) e) Ans: d The error message will be Test.java:10: variable x might not have been initialized } ^ 1 error As told earlier, the final variables should either be assigned value in initializer or it should be assigned value in all constructors. Here, the one argument constructor is not initializing the instance variable. Instead its assigning value to local parameter variable. 16) Given Inside Main Compilation Compilation Compilation Compilation Error Error Error Error pointing pointing pointing pointing to to to to line line line line 1 2 10 15

pck2/Parent.java package pck2; public class Parent{

Parent(){ System.out.println("Parent Created"); }

pck1/Test.java package pck1; import pck2.*; public class Test extends Parent{ Test(){ System.out.println("Child Created"); } } What will be the output of Test.java? a) Child Created Parent Created b) Parent Created Child Created c) Compilation Error Ans: c The classes Parent and Test are in different packages and the constructor Parent is not public but it has default access. So, the constructor Test() will not be able to access its parents constructor Parent(). The error message will be pck1\Test.java:4: Parent() is not public in pck2.Parent; cannot be accessed from outside package Test(){ ^ 1 error 17) Given

interface TestInterface{ void foo(); } class Test implements TestInterface{ void foo(){ System.out.println(Foo Implemented in Test Class); } } public class InterfaceExample{ public static void main(String args[]){ Test t1 = new Test(); t1.foo(); }

} What is the output of following program? a) Foo Implemented in Test Class b) Compilation Error in main function c) Compilation Error in class Test Ans: c All the functions declared in the interface are by default abstract and public. So while implementing in the class, it is mandatory to mention the method as public. The program will give following error InterfaceExample.java:6: foo() in Test cannot implement foo() in TestInterface; attempting to assign weaker access privileges; was public void foo(){ ^ 1 error 18) A java file can have only one main function a) TRUE b) FALSE Ans: b You can have multiple classes in a java file and each class can have a main function definition. But a java file can contain only one public class. And the name of the public class should be same as that of java file. A Java file needs not to have any public class. And public class needs not to have main method for the program to compile. 19) What will be the output of the following program?

public class Test{ int a = 0; public static void main(String args[]){ System.out.println(a=+a); } } a) 0. b) Compilation Error. c) Exception is thrown at run time. Ans: b Static functions can access only static methods and static variables of the same class. 20) What will be the output of the following program?

interface TestInterface{ int i = 0; void foo(); } public class Test implements TestInterface{ public static void main(String args[]){ Test t = new Test(); for(i=0;i<10;i++){ t.foo(); } } public void foo(){ System.out.println("Foo defined in class Test"); } } a) b) c) d) Prints Foo defined in class Test 10 times Compilation error because public class cannot implement interfaces Compilation error because the function foo is called inside static method Compilation error because the value of I cannot be initialized in the interface definition e) Compilation Error because the value of variable i cannot be changed Ans: e Any class can implement interfaces. So option b is wrong. Foo is called using the object. Main method is not calling the foo directly. So option c is wrong. Interface variables must be initialized inside the interface definition. All the interface variables are public static and final. So its not possible to change the value of interface variable.

Chapter 3: Java Operators


21) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. What will be the output of the following program??

class A{ } class B extends A{ } interface C{ } class D{ } public class Ticker{

14. 15. 16. 17. 18. 19. 20. 21.

} a) b) c) d)

public static void main(String args[]){ B b = new B(); System.out.println(b instanceof System.out.println(b instanceof System.out.println(b instanceof System.out.println(b instanceof } true true false false false true false false Compilation error at line 18 Compilation error at line 19

A); B); C); D);

Ans: d The instanceof operator can be used for either superclass/subclasses of the object or for interfaces (the class of the object needs not to implement the interface). The following will be the error message java:19: inconvertible types found : B required: D System.out.println(b instanceof D); ^ 1 error 22) What will be the output of the following program?

public class Test{ public static void main(String args[]){ float f = 07.f; double d = 0.7d; if(f==d){ System.out.println("Equal"); } else{ System.out.println("Not Equal"); } } } a) Equal b) Not Equal c) Compilation Error in the if condition Ans : b This is the classical puzzle in C programming. The float 0.7 is slightly lesser than double 0.7. In C you can print the value of float f (f=0.7) using the following line of code.

printf(%.25f,f); This will print a value which is slightly lesser than 0.7. 23) What will be the output of the following program

public class Test{ public static void main(String args[]){ float f= 20; System.out.println(f/0); System.out.println(-f/0); System.out.println(f/-0); System.out.println(-f/-0); } } NaN NaN NaN NaN a)

b) Infinity -Infinity Infinity -Infinity NaN -NaN -NaN NaN c)

d) Infinity -Infinity -Infinity Infinity e) Compilation error f) Runtime Exception (Arithmetic Exception: Divide by zero error) Ans: b An integer divided by zero will cause Runtime Arithmetic Exception but when a float is divided by zero, it will result in either Infinity or Infinity. The value of -0 is equal to zero. So sign before 0 will not affect the result. 24) 1. What will be the output of the following program

public class Test{

2. 3. 4. 5. 6. 7. 8. 9.

public static void main(String args[]){ String s = new String("Hello"); int a = 11; int b = 6; System.out.println(s+a+b); System.out.println(a+b+s); }

a) Hello17 116Hello b) Hello116 17Hello c) Hello116 116Hello d) Hello17 17Hello e) Compilation error in line 6 and 7 Ans: b The numbers will be appended to the string. 25) The operators >> and >>> behaves same for positive integers a) TRUE b) FALSE Ans: TRUE. The operator >> adds sign bit in the end whereas the operator >>> adds 0s. Sign bit is equal to 0 for positive integers.

Chapter 4: Flow Control and Exceptions


26) What will be the output of the following program

public class Test{ public static void main(String args[]){ int i=97; switch(i){ case 'a': System.out.println("Case a"); break; case 'b': System.out.println("Case b"); break; case 1:

System.out.println("Case 1"); break; case 97: System.out.println("Case 97"); break; case default: System.out.println(Default); Break; } } a) b) c) d) Case 97 e) Ans: e The error message will be Test.java:14: duplicate case label case 97: ^ 1 error 27) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. What will be the output of the following program? Case a Case 97 Default Case a Compilation error }

public class Test{ public static void main(String args[]){ long i=2; final int b = 10; int c = 20; switch(i){ case 2: System.out.println("Case break; case b: System.out.println("Case break; case c: System.out.println("Case break; case 3000000000: System.out.println("Case break; } } }

2"); b"); c"); d");

a) b) c) d) e)

Prints Case 2 Compilation error Compilation error Compilation error Compilation error

in in in in

line line line line

6 10 13 16

Ans: b, d and e Switch expects integer and the provided value is long which will not be implicitly casted to int. Only constant expressions can be used in case. So using final int b will not cause any error but using int c will give compilation error. And the case expressions can hold maximum value of (2^31)-1. So it will not accept 3000000000 which is more than (2^31)-1. The error message will be Test.java:16: integer number too large: 3000000000 case 3000000000: ^ Test.java:6: possible loss of precision found : long required: int switch(i){ ^ Test.java:13: constant expression required case c: ^ 28) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. What will be the output of the following program?

public class Test{ public static void main(String args[]){ byte g = 2; switch(g){ case 2: System.out.println("Case a"); break; case 128: System.out.println("Case c"); break; } } } a) Prints Case a b) Compilation error in line 4 c) Compilation error in line 8

Ans: c Although switch argument is legal (byte is implicitly cast to an int), the second case statement has the value which is too large for a byte. Explicit cast for g to int in the

switch statement or explicit cast for 128 to byte in the case statement will remove the compilation error. The error message will be like this Test.java:8: possible loss of precision found : int required: byte case 128: ^ 29) What will be the output of the following program? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. import java.io.*; public class ReadData { public static void main(String args[]) { try{ RandomAccessFile raf = new RandomAccessFile("myfile.txt", "r"); byte b[] = new byte[1000]; raf.readFully(b, 0, 1000); } catch(IOException e) { System.err.println("IO Error"); } catch(FileNotFoundException e) { System.err.println("File not found"); } } } a) b) c) d) Compiles and runs but no output Prints IO error Prints File not found Compilation fails

Ans: d The FileNotFoundException is a subclass of IOException. So catch statement for IOException should come after catch statement of FileNotFoundException. The error message will be ReadData.java:13: exception java.io.FileNotFoundException has already been caught catch(FileNotFoundException e) { ^

Chapter 5: Object Orientation


30) 1. Find out the error in the following program

class Animal{

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.

} class Horse extends Animal{ void eat(){ System.out.println("Horse Eating Hay"); } void jump(){ System.out.println("Jumping Horse"); } } public class Test{ public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); a.eat(); b.eat(); a.jump(); b.jump(); } } a) b) c) d) Compilation Compilation Compilation Compilation error error error error in in in in line line line line 18 19 20 21

void eat(){ System.out.println("Generic animal eating generic"); }

Ans: c, d Since eat is overridden method in class Horse, it can be run by using the object of Horse as well as Animal. Here a.eat will execute the eat of class Animal whereas b.eat will execute the eat of class Horse. The method jump is not present in class Animal. So it is not possible to access jump method by using the Animal reference even though it is pointing to Horse object. 31) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. What will be the output of following program?

class Animal{ public void eat(){ System.out.println("Generic animal eating generic"); } } class Horse extends Animal{ private void eat(){ System.out.println("Horse Eating Hay"); } } public class Test{ public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); a.eat();

16. 17. 18. a) b) c) d) Ans: a

} }

b.eat();

Compilation error at line 7 Compilation error at line 15 Compilation error at line 16 Compiles and runs properly

It is not possible to assign narrow access privileges to the overridden method in the subclass. The error message will be Test.java:7: eat() in Horse cannot override eat() in Animal; attempting to assign weaker access privileges; was public private void eat(){ ^ 32) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. a) b) c) d) Ans: d This is an example of overload but not override. The program compiles and runs properly. Both a.eat and b.eat will execute the method eat of Animal class. What will be the output of the following program?

class Animal{ public void eat(){ System.out.println("Generic animal eating generic"); } } class Horse extends Animal{ public int eat(String eatable){ System.out.println("Horse Eating "+eatable); return 0; } } public class Test{ public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); a.eat(); b.eat(); } } Compilation error at line 7 Compilation error at line 16 Compilation error at line 17 The program compiles and runs properly

33) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. a) b) c) d) Ans: a

What will be the output of the following program?

class Animal{ public void eat(){ System.out.println("Generic animal eating generic"); } } class Horse extends Animal{ public int eat(){ System.out.println("Horse Eating Hey"); } } public class Test{ public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); a.eat(); b.eat(); } } Compilation error at line 7 Compilation error at line 15 Compilation error at line 16 Program Compiles and runs properly

This is neither overload nor override. This is not overload because the argument list is same. Not override because the return type is different. The error will be like below Test.java:7: eat() in Horse cannot override eat() in Animal; attempting to use incompatible return type found : int required: void public int eat(){ ^ 34) What is the output of the following program? class Animal{ } class Horse extends Animal{ } public class Test{ public static void Kill(Animal a){ System.out.println("Animal is killed"); } public static void Kill(Horse h){ System.out.println("Horse is killed");

1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

11. 12. 13. 14. 15. 16. 17. 18.

} public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); Kill(a); Kill(b); }

a) Animal is killed Horse is killed b) Animal is killed Animal is killed c) Horse is killed Horse is killed d) Compilation error Ans: b Method overloading is compile time polymorphism whereas method overriding is runtime polymorphism. Here the output depends on the type of reference but not on the type of object. 35) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. What will be the output of the following program?

import java.io.*; class Animal{ public void eat()throws FileNotFoundException{ System.out.println("Generic animal eating generic"); } } class Horse extends Animal{ public void eat() throws IOException{ System.out.println("Horse Eating Hey"); } } public class Test{ public static void main(String args[]){ Animal a = new Animal(); Animal b = new Horse(); a.eat(); b.eat(); } } a) Compilation error at line 8 b) Compiles fine as IOException is superclass of FileNotFoundException c) Gives compilation error because the method calls a.eat() and b.eat() are not enclosed in try-catch block

Ans: a The overridden method cannot throw a broader or new checked exception. But the exception can reduce or eliminate. On compiling, the following error message will be displayed Test.java:8: eat() in Horse cannot override eat() in Animal; overridden method does not throw java.io.IOException public void eat() throws IOException{ ^ 36) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. a) b) c) d) Ans: c In the subclass Horse, since no constructor is called explicitly, it will try to call the no argument constructor. But the class Animal doesnt have no argument constructor and also default constructor will not be created as we are defining the constructor for the same. 37) 1. 2. 3. 4. 5. 6. 7. 8. 9. What will be the output of the following program? What will be the output of the following program?

class Animal{ public Animal(String name){ System.out.println("The animal "+name+" is created"); } } class Horse extends Animal{ public Horse(String name){ System.out.println("The horse "+name+" is created"); } } public class Test{ public static void main(String args[]){ Animal h = new Horse("Hero"); } } Prints The horse Hero is created. Compilation error at line 2 Compilation error at line 7 Compilation error at line 13

class B{ public B(){ System.out.println("No argument Constructor"); } public B(int i){ System.out.println("One argument Constructor"); this(); } }

10. 11. 12. 13. 14.

public class Test{ public static void main(String args[]){ B b = new B(); } } a) One argument Constructor No argument Constructor b) One argument Constructor c) Compilation error

Ans: c The call to other constructor should come before any other statements other than call to super constructor. The call this() should come before the System.out.println statement. If super() is there in the constructor, then that should come before this() call.

Chapter 6: Java.lang String, Math and Wrappers


38) What will be the output of the following program?

public class Test{ public static void main(String [] args) { String s1 = new String("abc"); String s2 = "abc"; System.out.println(s1==s2); System.out.println(s1.equals(s2)); } } a) true true b) false true c) true false d) false false e) Compilation Error f) Exception will be thrown at the run time Ans: b The objects s1 and s2 will contain the same string abc. But both these are referring to different objects. Whenever we use new operator to create a String, two string objects will be created. One String object will be created and stored in heap. Another String object will be stored in String Shared Pool (If the String is not present in the pool) which will not be garbage collected.

39)

What will be the output of the following program?

public class Test{ public static void main(String [] args) { String s1 = "abc"; String s2 = "abc"; System.out.println(s1==s2); System.out.println(s1.equals(s2)); } } a) true true b) false true c) true false d) false false e) Compilation Error f) Exception will be thrown at the run time Ans: a If you dont use the new operator to create String object, and if the String object with that value is already created, the JVM will not create new object. Instead it will just make the String variable to refer the old object which is stored in String Shared Pool. So here both s1 and s2 points to same object. 40) What will be the output of following program?

public class Test{ public static void main(String args[]){ String s = "Test String"; System.out.println(s.length); } } a) Compilation Error b) Runtime exception c) Prints 11 Ans: a String class doesnt have property length as array. We need to use the method length() to find the length of the string. 41) What will be the output of the following program?

public class Test{ public static void main(String args[]){ double notanum = Double.NaN;

} }

if(notanum != notanum){ System.out.println("Not Equal"); } else{ System.out.println("Equal"); }

a) Not Equal b) Equal c) Compilation Error Ans: a NaN is not equal to anything. Not even to NaN. You can use Double.isNaN(notanum) to check whether it is NaN or not. 42) Given the following

12. String x = new String(xyz); 13. y = abc; 14. x = x+y How many objects will be created? a) b) c) d) Ans: c Two objects will be created in line 12(the new object will be created whenever we use new operator). And one object will be created in line 13 and 14 (line 14 will create new object since String objects are immutable) 43) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Which lines will cause compilation error? 2 3 4 5

public class Test{ public static void main(String [] args) { Long b = new Long(42); int x = Integer.valueOf("345"); int x2 = (int) Integer.parseInt("345", 8); int x3 = Integer.parseInt(42); int x4 = Integer.parseInt("42"); int x5 = b.intValue(); } } a) Line 3 b) Line 4

c) d) e) f) Ans: b, d

Line Line Line Line

5 6 7 8

The method Integer.valueOf(345) returns Integer object which cannot be assigned to primitive int. The method Integer.parseInt takes String parameter not int. 44) 4. 5. 6. 7. 8. Given the following

String d = "bookkeeper"; d.substring(1,7); d = "w" + d; d.append("woo"); System.out.println(d);

What is the output? a) b) c) d) e) Ans: d The method append belongs to class StringBuffer which has been used with String object. 45) 11. 12. 13. 14. 15. Given the following Wookkeewoo Wbookkeeper Wbookkeewoo Compilation fails Exception will be thrown at the run time.

String x = "xyz"; x.toUpperCase(); String y = x.replace('Y', 'y'); y = y + "abc"; System.out.println(y);

What is the output? a) b) c) d) e) Ans: c The line 12 will not affect the string object. The method toUpperCase creates the new String object and returns the reference without altering the old object or reference. XyZabc XyZABC xyzabc Compilation fails Exception will be thrown at the runtime

46) 1. 2. 3. 4. 5. 6.

Given the following

public class SqrtExample { public static void main(String [] args) { double value = -9.0; System.out.println( Math.sqrt(value)); } }

What is the output? a) b) c) d) e) Ans: c The square root of negative number will be NaN. The square root of Infinity will be Infinity. 47) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. Given the following 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) { System.out.print("y "); } System.out.println("z"); } } 3.0 -3.0 NaN Compilation fails Runtime Exception

what is the result? a) b) c) d) e) f) Ans: e z xz yz xyz Compilation Fails Runtime Exception

b1 is a Boolean object and hence cannot be used in if condition. Also cannot perform logical operations with primitive boolean. 48) 1. 2. 3. 4. 5. 6. Given the following public class WrapTest3 { public static void main(String [] args) { String s = "98.6"; // insert code here } }

Which three lines inserted independently at line 4 will cause compiler errors? (Choose three.) a) b) c) d) e) f) float f1 = Float.floatValue(s); float f2 = Float.valueOf(s); float f3 = new Float(3.14f).floatValue(); float f4 = Float.parseFloat(1.23f); float f5 = Float.valueOf(s).floatValue(); Float f6 = (float)Double.parseDouble(3.14);

Ans: a, b, d The method floatValue will not take arguments. The method Float.valueOf returns Float object which cannot be assigned to primitive float. Method ParseFloat takes only String parameter. Note: Method Static Method Argument Returns xxxValue NO None primitive valueOf YES String Object parseXxx YES String primitive

Refer the table below for more information.

49) 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. try {

Given the following 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) { System.out.println("bad number"); }

What is the output? a) b) c) d) e) 9.0 bad number compilation fails at line 13 compilation fails at line 14 compilation fails at line 16

Ans: 9.0 The xxxValue() method converts any numeric wrapper objects value to any primitive type.

50)

Which among the following statement are true? a) If x and y refers to instances of different wrapper classes, then x.equals(y) will cause compilation failure. b) If x and y refers to instances of different wrapper classes but contains same value, then x.equals(y) will return true. c) If x and y refers to instances of two different wrapper classes, then x.equals(y) returns false even if the values contained in the object are equal. d) If x == y is true. Then x.equals(y) is always true. e) If x.equals(y) is true. Then x==y is always true.

Ans: c, d The equals method fails if the object classes are different and not in the same hierarchy. If both x and y points to the same object, then x == y returns true. But for x.equals(y) to return true, it is not necessary that both x and y refers to same object, but the value contained in both objects should be same. 51) a) b) c) d) e) Ans: a,b,c,e Which among the following will compile without error? Boolean Boolean Boolean boolean boolean b1 = new Boolean(true); b2 = new Boolean(TRUE); b3 = new Boolea(tRuE); b4 = True; b5 = true;

Chapter 7: Objects and Collections


52) What will be the output of the following program?

class A{ private int val; public int getVal(){ return val; } public void setVal(int val){ this.val = val; } public A(int val){ this.val = val; } public A(){ }

public boolean equals(Object o){ if(((A)o).getVal() == this.val){ return true; } else{ return false; } } } class B{ } public class Test{ public static void main(String [] args) { A a1 = new A(8); A a2 = new A(8); B b1 = new B(); if(a1.equals(b1)){ System.out.println("Equals"); } else{ System.out.println("Not Equals"); } } } a) b) c) d) Ans: d The object b1 cannot be casted to type A. So it will throw ClassCastException in runtime. To avoid this u can use the condition (o instanceof A) in the if condition of equals function. 53) What will be the output of the following program? Equals Not Equals Compilation Error Runtime Exception

class A{ String toString(){ return "This is class A object"; } } public class Test{ public static void main(String [] args) { A a = new A(); System.out.println(a); }

} a) This is class A object b) Compilation error c) Runtime exception Ans: b The toString method in Object class has access privilege public. As told in earlier problem, it is not possible to narrow the access privilege while overriding the methods. This also applies to the methods equals and hashCode. 54) What will be the output of the following program?

class A{ private int val; public int getVal(){ return val; } public A(int val){ this.val = val; } boolean equals(A o){ if(o.getVal() == this.val){ return true; } else{ return false; } } } class B{ } public class Test{ public static void main(String [] args) { A a1 = new A(8); A a2 = new A(8); B b1 = new B(); if(a1.equals(a2)){ System.out.println("Equals"); } else{ System.out.println("Not Equals"); } if(a1.equals(b1)){ System.out.println("Equals"); } else{ System.out.println("Not Equals");

} }

a) Equals Not Equals b) Not Equals Equals c) Compilation Error d) Runtime Exception Ans: a The method equals is accepting the reference of type A instead of Object. So this is not override but overload. So it will not give any compilation error because of default access specifier. In the first if condition, the function equals written in class A is invoked as it is accepting the reference of type A. Hence it compares and returns true. In second if condition, the equals method of class Object is called instead of the method defined in class A. So it will not give any runtime exception but returns false to the calling function. 55) What is the output of the following program? And how many objects will be eligible for garbage collection during the execution of the t1.print statement public class Test{ int val; public Test(int val){ this.val = val; } public void set(int val){ this.val = val; } public void print(){ System.out.println(val); } public static void main(String [] args) { Test t1 = new Test(1); Test t2 = m1(t1); Test t3 = new Test(3); t2 = t3; t1.print(); t2.print(); t3.print(); }

} a) 2 3 b) 3 3 c) 3 3 d) e)

public static Test m1(Test tt){ tt = new Test(2); return tt; } 1 1 2 2 objects will be eligible for garbage collection before the end of the program 1 object will be eligible for garbage collection before the end of the program

Ans: b, e The flow goes like below 1) t1->Object1------------------------ On assigning t1 = new Test(1) 2) t1->Object1------------------------ On calling the method m1 tt->Object1 3) t1->Object1------------------------ On assigning tt = new Test(2) tt->Object2 4) t1->Object1------------------------ After the execution of the method m1. t2->Object2 tt will be local to method m1 and will be destroyed on coming out of the method 5) t1->Object1------------------------ On assigning t3 = new Test(3) t2->Object2 t3->Object3 6) t1->Object1------------------------ On assigning t2 = t3. t2->Object3 t3->Object3 By the end of step 6, there will not be any live threads which contain reference to Object2. Hence that will become eligible for garbage collection. 56) Which among the following are true about equals() and hashCode() methods assuming that the methods are overridden according to the contract rules. a) If the equals() method returns true, then hashCode() comparison == must return true. b) If the equals() method returns false, then hasCode() comparison != must return false.

c) If hashCode() comparison == returns true, then equals() method must return true. d) If the hashCode() comparison == returns true, then the equals() method might return true. e) If the hashCode() comparison != returns true, then the equals() method might return true. Ans: a, d According to the contract, If two objects are equal, the hashCode of both should also be same. And the reverse is not necessary. It is legal even if all the objects of the class returns same hashcode value. But that will be less efficient. 57) Which among the following collection is a List implementation which gives fast iteration and fast random access and the methods are synchronized. a) b) c) d) Ans: b ArrayList, Vector and LinkedList are the List implementations and Hashtable is Map implementation. LinkedList is the doubly linked list implementation and insertion and deletion will be comparatively faster. ArrayList and Vector gives faster iteration and faster random access. Vector is basically same as an ArrayList, but Vector() methods are synchronized for thread safety. Normally, usage of ArrayList is preferable than that of Vector because the synchronized methods add performance hit which might not be necessary. 58)Which among the following is sorted collection set? a) b) c) d) e) Ans: c HashSet, LinkedHashSet and TreeSet are the three Set implementations. There is no collection by name ArraySet and TreeMap is the Map implemented collection which is sorted. Among the Set implementations, HashSet is unordered and unsorted, LinkedHashSet is ordered but not sorted and TreeSet is sorted. 59) For which type of collection, the efficiency of hashCode matters? a) List b) Set HashSet LinkedHashSet TreeSet TreeMap ArraySet ArrayList Vector LinkedList Hashtable

c) Map Ans: c 60) Which Map collection is ordered but not sorted in which iteration is comparatively faster and insertion and deletion are much slower than other Map collections. a) b) c) d) Ans: c All the collections mentioned above are of type Map. HashMap is unsorted and unordered Map. Hashtable is synchronized version of HashMap. LinkedHashMap is the ordered and unsorted Map. The order in LinkedHashMap might be insertion order or access order. TreeMap is ordered and sorted. Only TreeMap and TreeSet are the sorted collections. HashMap HashTable LinkedHashMap TreeMap

Chapter 8: Inner Classes


61) Given

class MyOuter{ class MyInner{ } } Mention the proper way of creating instance of MyInner class in a class other than MyInner and MyOuter. a) MyOuter.MyInner m1= new MyOuter.MyInner(); b) MyInner m2 = new MyOuter().new MyInner(); c) MyOuter mo = new MyOuter(); MyOuter.MyInner mi = new mo.MyInner(); d) MyOuter mo = new MyOuter(); MyOuter.MyInner mi = mo.new MyInner(); e) MyOuter.MyInner = new MyOuter().new MyInner(); f) MyOuter.MyInner = new (new MyOuter()).MyInner(); Ans: d, e If the inner class is not static, then outer class should be instantiated to instantiate the inner class. If the inner class is static, then option a) also works fine. 62) Given

class MyInner{ public Main(){ System.out.println("From Class MyInner"); } } public class Test{ public static void main(String args[]){ MyInner m = new MyInner(){ public MyInner(){ System.out.println("Anonymous Inner Class"); } }; } } What is the output? a) b) c) d) e) Ans: d It is not possible to override constructors. The error message will be Test.java:10: invalid method declaration; return type required public Main(){ ^ 1 error 63) Given From Class MyInner Anonymous Inner Class No output Compilation fails Runtime Exception

class MyInner{ public void Go(){ System.out.println("From Class MyInner"); } } public class Test{ public static void main(String args[]){ MyInner m = new MyInner(){ void Go(){ System.out.println("Anonymous Inner Class"); } }; m.Go();

} } What is the output? a) From Class MyInner b) Anonymous Inner Class c) Compilation Error Ans: c All the rules of override apply here also. The method void Go() has weaker privilege (default) in the inner class. 64) Given

class MyInner{ public void Go(){ System.out.println("From Class MyInner"); } } public class Test{ public static void main(String args[]){ MyInner m = new MyInner(){ public void Go(){ System.out.println("Anonymous Inner Class"); } } m.Go(); } } What is the output? a) From Class MyInner b) Anonymous Inner Class c) Compilation Error Ans: c Semicolon is missing after the definition of inner class. 65) Given

class MyOuter{ private String x = "Outer"; void doStuff(){ String loc = "Local"; final String loc2 = "Local and Final"; class MyInner{ public void seeOuter(){ System.out.println(x);

} } }

} public void seeLocal(){ System.out.println(loc); } public void seeFinalLocal(){ System.out.println(loc2); }

Which method in the inner class MyInner gives compilation error? a) b) c) d) e) Ans: b A method-local Inner Class can access the class variables of the class. But to access the local variables of the method in which the class is defined, the method should be declared final. 66) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. Given interface Cookable{ public void cook(); } class Food{ Cookable c = new Cookable(){ public void cook(){ System.out.println("Anonymous Cookable"); } }; public Food(){ c.cook(); } } public class Test{ public static void main(String args[]){ Food f = new Food(); } } seeOuter seeLocal seeFinalLocal All the above None of the above

What is the output? a) Prints Anonymous Cookable b) Compilation error in line 6 as it is not possible to instantiate the interface c) Compilation error in line 7 as inner class cannot be created here

d) Runtime Exception Ans: a The code works perfectly fine. It is possible to instantiate the interface by defining the anonymous inner classes like above provided the inner class should implement all the methods declared in the interface. 67) 1. 2. 3. 4 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. Given interface Foo{ void foo(); } class Bar{ void doStuff(Foo f){ } } public class Test{ public static void main(String args[]){ Bar b = new Bar(); b.doStuff(new Foo(){ public void foo(){ System.out.println("Inner Anonymous Class"); } }); } }

What is the output? a) b) c) d) Ans: d The method doStuff takes Foo as argument. So while calling the method, we are creating an anonymous object. But the method foo in the anonymous class is never called. So nothing will be printed. 68) 1. 2. 3. 4. 5. 6. Given Inner Anonymous Class Compilation Error Runtime Exception Compiles and Runs properly but nothing will be printed

class MyOuter{ int x; public MyOuter(){ x = 10; } class MyInner{

7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28.

int x; public MyInner(){ x = 11; } public void seeOuter(){ System.out.println(MyOuter.x); } public void seeInner(){ System.out.println(x); }

} }

public class Test{ public static void main(String args[]){ MyOuter mo = new MyOuter(); MyOuter.MyInner mi = mo.new MyInner(); mi.seeOuter(); mi.seeInner(); } }

What is the output? a) b) c) d) Ans: b The syntax MyOuter.x (classname.membername) can be used only with static members. By using MyOuter.x the compiler thinks that it is trying to access a static member even though it is not. So compilation fails. The error message will be as follows Test.java:13: non-static variable x cannot be referenced from a static context System.out.println(MyOuter.x); ^ 1 error To avoid this error, we can use MyOuter.this.x instead of MyOuter.x. Since MyOuter.this refers to object, it is legal to access the nonstatic member through it. 69) a) b) c) d) Which are true about the method-local inner class? It It It It must be marked final. can be marked abstract. can be marked public. can be marked static. 10 11 Compilation error in line 13 Compilation error in line 24 Runtime Exception

e) It can access private members of the enclosing class. f) It can access non-final local variables of the enclosing method. g) It can access final variables which are local to enclosing method. Ans: b, e, f The method-local inner classes can be marked as final or abstract but it is not must. It is not possible to mark public or static to any local variables. Similarly it is not possible to mark method-inner classes as public or static. And finally, the methodinner classes can access members of enclosing class and local variables of the enclosing method which are marked as final. 70) Which is true about anonymous inner class? a) It can extend exactly one class and implement exactly one interface b) It can extend exactly one class but can implement more than one interface c) It can extend exactly one class or implement exactly one interface d) It can implement multiple interfaces but it will not extend any class Ans: c The syntax of the anonymous class allows only one named type after the operator new.

Chapter 9: Threads
71) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. Given class MyThread extends Thread{ public static void main(String args[]){ MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.run(); t2.run(); } public void run(){ for(int i=0;i<3;i++){ System.out.print(i+".."); } } }

What is the output? a) b) c) d) Compilation error 0..1..2..0..1..2 Unpredictable as method runs in thread Runtime exception

Ans: b Note that the objects t1 and t2 are not invoking the thread. Instead they are just calling the run method. So the output will be predictable and as in the answer. 72) a) b) c) d) e) f) Ans: a,d,e The methods wait(), notify() and notifyAll() belongs to Object class. There is no method called terminate in any Thread related classes. 73) Given Which among the following methods are defined in Thread class? start(); wait(); notify(); run(); sleep(); terminate();

class MyThread extends Thread{ public static void main(String args[]){ MyThread t = new MyThread(); t.start(); try{ sleep(2000); } catch(InterruptedException e){ } t.start(); } public void run(){ for(int i=0;i<3;i++){ System.out.print(i+".."); } } } What is the output? a) b) c) d) Ans: d Its illegal to start a thread for second time even though it has finished running. It will throw IllegalThreadStateException Compilation fails 0..1..2..0..1..2 Unpredictable output Prints 0..1..2 and throws runtime exception while starting the thread for second time

74)

Given

import java.lang.String; class MyThread{ public static void main(String args[]){ printall(args); } public static void printall(String[] str){ for(int i=0;i<str.length;i++){ System.out.print(str[i]); Thread.currentThread.sleep(1000); } }

What is the output? a) Each String in array str will output with 1 sec pulse. b) The lines will output but without 1 sec pulse. c) Each string in array will output but there is no guarantee there will be a pause because currentThread() may not retrieve this thread. d) Compilation Error e) Runtime Exception Ans: d The sleep method declares the checked exception InterruptedException. Hence sleep should be called within the try-catch block. 75) Which among the following are true?

a) The static method cannot be synchronized b) If a class has synchronized code, multiple threads still can access nonsynchronized code. c) Variables can be protected from concurrent access problem by marking them with synchronized keyword. d) When thread sleeps, it releases its locks. e) When a thread invokes wait, it releases its locks. Ans: b, e Only methods can be marked as synchronized but not the variables. All the other are self explanatory. 76) Given

class MyThread{ public static void main(String args[]){ System.out.print("1.."); synchronized(args){ System.out.print("2..");

try{

} }

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

args.wait(); } catch(InterruptedException e){ }

What is the output? a) b) c) d) Ans: c The main thread waits infinitely for object args to issue notify after it prints 2. 77) Which among the following are correct? a) The wait method should be called from a synchronized block b) The notify and notifyAll methods should be called from synchronized block c) The thread will resume as soon as its sleep duration expires. d) The wait method is overloaded to accept duration. Ans: a,c,d The thread should own the lock on the object to invoke wait() /notify() /notifyAll(). The thread will go to runnable state as soon as the sleep duration expires. The wait method is overloaded to accept duration. If the thread is not notified within the given duration, the thread will move back to runnable state even without notification. Compilation fails 1..2..3 1..2.. Runtime exception

78) Which among the following are valid constructors of Thread class? a) b) c) d) e) Ans: a, b, e 79) 1. Given public class Test{ Thread(Runnable r, String name); Thread(); Thread(int priority); Thread(Runnable r, ThreadGroup g); Thread(int priority, Runnable r);

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33.

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){ try{ x=10; wait(); }catch(InterruptedException e){} } else{ notify(); } System.out.println("x is "+ (x++)); }

What is the output? a) Compilation error at line 25 b) Compilation error at line 29 c) Compilation error in the test class d) Runtime exception e) x is 10 x is 11 Ans: d The methods wait and notify should be called from a synchronized block. Here the threads are trying to call wait and notify without owning lock on the object. It will give IllegalMonitorStateException.