«Java» Trial Test

You have 1 hour to complete the Test. It is not allowed to use any technical literature.

Part 1. Language fundamentals

1. What will be the result of trying to compile and run an application in which the following is the only declaration of a main method? (Assume the rest of the class is correct)

public static void main(){
    System.out.println("hello world");
}
  1. The class will compile without error but the program will not run.
  2. The class will compile and run, writing "hello world" to the standard output.
  3. The compiler will report an error.
  4. The compiler will report an error but the program will run fine.

2. Consider the following line of code:

int[] x = new int[25];
After execution, which statement is true?
  1. x[24] is null
  2. x[24] is undefined
  3. x[25] is 0
  4. x[0] is null
  5. x.length is 25

3. Given:

class test
{
int x;
	public static void main (  String [] args )
	{
		final int i;
		i = 127;
		byte b = i;
		System.out.println(b);
	}
}
  1. Compile error: loss of precision
  2. No error. Compiles fine. Prints 0
  3. Runtime error
  4. Compiles with a warning
  5. No error. Compiles fine. Prints 127

4. What will be the result of calling the following method with an input of 2?

public int adder( int N ){
    return  0x100 + N++ ;
  }
  1. The method will return 258.
  2. The method will return 102.
  3. The method will return 259.
  4. The method will return 103.

5. How many String objects are created in the following code?

String A, B, C ;
  A = new String( "1234" ) ;
  B = A ;
  C = A + B ;
  1. One
  2. Two
  3. Three
  4. Four

6. Consider the following code:

StringBuffer sbuf = new StringBuffer();
 sbuf = null;
 System.gc();
Choose all true statements:
  1. After line 2 executes, the StringBuffer object is garbage collected.
  2. After line 3 executes, the StringBuffer object is garbage collected.
  3. After line 2 executes, the StringBuffer object is eligible for garbage collection.
  4. After line 3 executes, the StringBuffer object is eligible for garbage collection.
  5. None of the above

7. What is the return type of the instanceof operator?

  1. A reference
  2. A class
  3. An int
  4. A Boolean

8. What is the minimal modification that will make this code compile correctly?

final class Aaa  {
 	int xxx;
 	void yyy() { xxx = 1; }
 }


 class Bbb extends Aaa {
 	final Aaa finalref = new Aaa();

 	final void yyy() {
 		System.out.println("In method yyy()");
 		finalref.xxx = 12345;
 	}
 }
  1. On line 1, remove the final modifier.
  2. On line 6, remove the final modifier.
  3. Remove line 9.
  4. On lines 1 and 6, remove the final modifier.
  5. The code will compile as is. No modification is needed.

9. Which modifier or modifiers should be used to denote a variable that should not be written during the process of serialization? (Choose the shortest possible answer.)

  1. private
  2. protected
  3. private protected
  4. transient
  5. volatile

10. Which of the following statements are true?

  1. An abstract class may be instantiated.
  2. An abstract class must contain at least one abstract method.
  3. An abstract class must contain at least one abstract data field.
  4. An abstract class must be overridden to compile correctly.
  5. An abstract class must declare that it implements an interface.
  6. None of the above.

Part 2. Flow control & exceptions

11. Which of the following is legal argument type for a switch statement?

  1. Object
  2. double
  3. long
  4. float
  5. char
  6. String

12. A method to compute the sum of all elements in an array of int is needed. The following proposed method is incomplete:

public int total( int[] x ){
   int i, t = 0 ;
   -select statement to go here
   { t += x[ i++ ] ;
   }
   return t ;
 }
What is the correct statement for line 3?
  1. for( int i = 0 ; i < x.length ; )
  2. for( i = 0 ; i < x.length ; )
  3. for( i = 0 ; i < x.length ; i++ )
  4. for( i = 1 ; i <= x.length ; i++ )

13. Here is a test method:

String test( int n ){
   String tmp = "?" ;
   if( n < 3 ) n-- ;
   switch( n ){
     case 1 :
       return "one" ;
     case 2 :
       n = 3 ;
     case 3 :
       break ;
     case 4 :
     default :
       return tmp ;
   }
   return "Result " + n ;
 }
Which of the options correctly describes the input and returned value from this method? [Check all correct answers.]
  1. Input 1 - Return = “ one ”
  2. Input 2 - Return = “ Result 3 ”
  3. Input 3 - Return = “ Result 3 ”
  4. Input 4 - Return = “ ? ”
  5. Input 5 - Return = “ ? ”

14. What is in your opinion recommended rule of using checked and unchecked exceptions?

  1. One should use unchecked exception only if he/she doesn’t want someone to catch it.
  2. There is no rules. It is up to developer whenever to use in particular situation checked or unchecked exception
  3. In general one should use unchecked exception in case of unexpected, non-recoverable emergency situation, and checked in case of expected.
  4. One shouldn't use checked exceptions at all, if possible, because checked exception force you to mention it in a throw clause.

15. Here is the hierarchy of exceptions related to array index and string index errors:

Exception
	+-- RuntimeException
		+-- IndexOutOfBoundsException
			+-- ArrayIndexOutOfBoundsException
			+-- StringIndexOutOfBoundsException

Suppose you had a method X that could throw both array index and string index exceptions. Assuming that X does not have any try/catch statements, which of the following statements are correct?

[Check all correct answers.]
  1. The declaration for X must include "throws ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException".
  2. If a method calling X catches IndexOutOfBoundsException, both array and string index exceptions are caught.
  3. If the declaration for X includes "throws IndexOutOfBoundsException", any calling method must use a try/catch block.
  4. The declaration for X does not have to mention exceptions.

16. You are writing a set of classes related to cooking and have created your own exception hierarchy derived from java.lang.Exception as follows (note that both BitterException and SourException descend from BadTasteException):

Exception
	+-- BadTasteException
		+-- BitterException
		+-- SourException

Your base class, BaseCook, has a method declared as follows:

int rateFlavor(Ingredient[] list) throws
   BadTasteException

A class, TexMexCook, derived from BaseCook has a method that overrides BaseCook.rateFlavor(). Which of the following are legal declarations of the overriding method?

[Check all correct answers.]
  1. int rateFlavor(Ingredient[] list) throws BadTasteException
  2. int rateFlavor(Ingredient[] list) throws Exception
  3. int rateFlavor(Ingredient[] list) throws BitterException
  4. int rateFlavor(Ingredient[] list)

17. Given:

class test
{
	test()
	{
	    try
	    {
		throw new RuntimeException();
	    }
	    finally
	    {
		System.out.print("Damn ! ");
	    }

	}
	public static void main( String args[] )
	{
	    try
	    {
		new test();
	    }
	    catch ( Throwable t )
	    {
		System.out.print("Caught");
	    }
	}
}
What is the output?
  1. Damn ! RuntimeException
  2. Damn ! Caught RuntimeException
  3. RuntimeException caught
  4. Damn ! Caught
  5. Caught
  6. None of the above

18. What will happen when you attempt to compile and run the following code?

public class Twc{
    int iPayment=10;
    static boolean bComplete;
    public static void main(String argv[]){
      Twc  t = new Twc();
   System.out.println(t.checkParam("one"));
   System.out.println(bComplete);
    }
    public int checkParam(String param){
   try{
       if(param.equals("one")){
      return iPayment * 2;
       }else if (param.equals("two")){
      return iPayment * 3;
       }
   }finally{
       bComplete=true;
   }

   return -1;
}
  1. Compile-time error; the try block has no matching catch clause.
  2. Compilation and output of 20 followed by false.
  3. Compilation and output of 20 followed by true.
  4. Compilation, but a runtime error as bComplete has not been initialized.

Part 3. Classes and objects

19. Which of the following class declarations use modifier keywords incorrectly?

[Check all correct answers.]
  1. public synchronized class FastClass extends Thread
  2. private protected class FastClass
  3. public abstract class FastClass
  4. class FastClass extends Thread

20. When you try to compile the following source code, it produces a compiler warning to the effect that the variable tmp may not have been initialized:

	class Demo{
   String msg = "Type is " ;
   public void showType( int n ) {
     String tmp ;
     if( n > 0 ) tmp = "positive" ;
     System.out.println( msg + tmp ) ;
   }
 }
Which of the following changes would eliminate this warning? [Check all correct answers]
  1. Make line 4 read: String tmp = null ;
  2. Make line 4 read: String tmp = " " ;
  3. Insert a line following line 5: else tmp = "not positive" ;
  4. Remove line 4 and insert a new line after 2 so tmp becomes a member variable instead of a local variable in showType: String tmp ;

21. Look at the following class definition:

	public class DerivedDemo extends Demo{
   int M, N, L ;
   public DerivedDemo( int x, int y ){
     M = x ; N = y ;
   }
   public DerivedDemo( int x ){
     super( x );
   }
 }
Which of the following constructor signatures must exist in the Demo class for DerivedDemo to compile correctly? [Check all correct answers.]
  1. public Demo( int a, int b )
  2. public Demo( int c )
  3. public Demo( )
  4. There is no requirement for a constructor in Demo.

22. Consider this class:

	public class Test1 {
 	public float aMethod(float a, float b) {
 	}
 }
Which of the following method would be legal if added (individually) at line 4?
  1. public float aMethod(float a, float b) { }
  2. public float aMethod(float a, float b, int c) throws Exception { }
  3. public float aMethod(float c, float d) { }

23. Which of the following may override a method whose signature is void xyz(float f)?

  1. void xyz(float f)
  2. public float xyz(float f)
  3. private void xyz(float f)
  4. public int xyz(float f)
  5. private int xyz(float f)

24. Suppose class Lemon extends class Citrus. Given the following code:

	Lemon lem = new Lemon();
	Citrus cit = new Citrus();
Which line compiles without error?
  1. lem = cit;
  2. cit = lem;
  3. lem = (Citrus)cit;
  4. cit = (Lemon)lem;
  5. cit = (Object)lem;

25. Given:

	class test
{
     public static void main( String args[] )
	{
		Map m = new HashMap();
		String str = null;
		m.put(new test() , "mill" );
		m.put(new test() , "sill" );
		System.out.println(m.size());
	}
	public boolean equals( Object o)
	{
		return false;  // 1
	}
	public int hashCode()
	{
		return 0;
	}
}
Choose all that apply.
  1. Prints 1
  2. Prints 2
  3. If Line 1 is replaced with return true; then m.size() returns 1.
  4. If hashCode() is not overridden then regardless of whether line 1 returns true or false 2 will be printed on the screen.
  5. Compile time error
  6. Runtime exception is encountered.
  7. If Line 1 is replaced with return true; then size() will not return any number greater than 1.

26. Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply)

  1. If the equals() method returns true, the hashCode() comparison == might return false.
  2. If the equals() method returns false, the hashCode() comparison == might 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.
  5. If the hashCode() comparison ! = returns true, the equals() method might return true.

27. Which are true about a static nested class? (Choose all that apply)

  1. You must have a reference to an instance of the enclosing class in order to instantiate it.
  2. It does not have access to non-static members of the enclosing class.
  3. Its variables and methods must be static.
  4. If the outer class is named MyOuter, and the nested class is named MyInner, it can be instantiated using new MyOuter.MyInner();.
  5. It must extend the enclosing class.

28. Which are true about an anonymous inner class? (Choose all that apply)

  1. It can extend exactly one class and implement exactly one interface.
  2. It can extend exactly one class and can implement multiple interfaces.
  3. It can extend exactly one class or implement exactly one interface.
  4. It can implement multiple interfaces regardless of whether it also extends a class.
  5. It can implement multiple interfaces if it does not extend a class.

Part 4. Converting and Casting Primitives and Objects

29. What will happen when you try to compile the following code?

	public void printArray( Object x ){
   		if( x instanceof int[] ){
     		int[] n = (int[]) x ;
     		for( int i = 0 ; i < n.length ; i++ ) {
       			System.out.println(″integers = ″ + n[i] );}
   			}
   		if( x instanceof String[] ){
     		System.out.println(″Array of Strings″) ;
   		}
 	}
  1. It compiles without error.
  2. The compiler objects to line 2, which compares an Object with an array.
  3. The compiler objects to line 3, which casts an Object to an array of int primitives.
  4. The compiler objects to line 7, which compares an Object to an array of Objects.

30. Here are three proposed alternatives to be used in a method to return false if the object reference x has the null value. Which statement will work?

  1. A. if( x == null ) return false ;
  2. B. if( x.equals( null ) ) return false ;
  3. C. if( x instanceof null ) return false ;

31. Suppose you have an ApBase class declared as: class ApBase extends Object implements Runnable

The following code fragment takes a reference to an ApBase object and assigns it to a variety of variables:

	ApBase aBase = new ApBase();
 	Runnable aR = aBase;
 	Object obj = aR;
 	ApBase x = (ApBase)obj;
What will happen when you try to compile and run this code?
  1. The compiler objects to line 2.
  2. The compiler objects to line 3.
  3. The code compiles but, when run, it throws a ClassCastException in line 4.
  4. The code compiles and runs without a problem.

32. You are working on an aquarium-simulation class named Aquarius. You already have a method that adds a Fish object to the aquarium and returns the remaining fish capacity. This method has the following declaration:

	public int addFish( Fish f )

Now you want to provide for adding a whole school of fish at once. The proposed method declaration is as follows:

	protected boolean addFish( Fish[] f )

The idea is that it will return true if there is more room in the tank or false if the tank is too full.

Which of the following statements about this proposal are true?
  1. This technique is called overloading.
  2. This technique is called overriding.
  3. The compiler will reject the new method because the return type is different.
  4. The compiler will reject the new method because the access modifier is different.

33. The GenericFruit class declares the following method:

	public void setCalorieContent( float f )

You are writing a class Apple to extend GenericFruit and want to add methods that overload the method in GenericFruit. Which of the following would constitute legal declarations of overloading methods?

[Check all correct answers.]
  1. protected float setCalorieContent(String s )
  2. protected void setCalorieContent( float x )
  3. public void setCalorieContent( double d )
  4. public void setCalorieContent(String s ) throws NumberFormatException

34. You are taking over an aquarium simulation project. Your predecessor created a generic Fish class that includes an oxygenConsumption method declared as follows:

	public float oxygenConsumption( float
  	temperature )

The aquarium simulation sums oxygen consumption for all fish in the tank with the following code fragment, where fishes is an array of Fish object references:

float total = 0 ;
    for( int i =0 ; i < fishes.length ;i++ ){
    total +=
        fishes[i].oxygenConsumption( t );
}

You are writing a subclass for a particular fish species. Your task is to provide a method with species-specific metabolism data that will transparently fit into the simulation.

Do you want to overload or override the oxygenConsumption method?
  1. Overload it.
  2. Override it.

Part 5. Threads

35. What is the Sun recommended approach to stop a thread?

  1. stop() method
  2. stop() or suspend() method
  3. the thread check particular variable and exit run() method on special condition
  4. it isn't possible to stop particular Java thread until it finishes its job

36. Which of the following may not be synchronized?

  1. Blocks within methods
  2. Static methods
  3. Blocks within static methods
  4. Classes

37. How do you prevent shared data from being corrupted in a multithreaded environment?

  1. Mark all variables as synchronized.
  2. Mark all variables as volatile.
  3. Use only static variables.
  4. Access the variables only via synchronized methods.

38. If you attempt to compile and execute the following application, will it ever print out the message In xxx?

	class TestThread3 extends Thread {
	public void run() {
 	System.out.println(“Running”);
 	System.out.println(“Done”);
 }
 private void xxx() {
 	System.out.println(“In xxx”);
 }

 public static void main(String args[]) {
 	TestThread3 ttt = new TestThread3();
 	ttt.xxx();
 	ttt.start();
 }
 }

  1. Yes
  2. No

39. Which are true? (Choose all that apply.)

  1. The notifyAll() method must be called from a synchronized context.
  2. To call wait(), an object must own the lock on the thread.
  3. The notify() method is defined in class java.lang.Thread.
  4. When a thread is waiting as a result of wait(), it release its lock.
  5. The notify() method causes a thread to immediately release its lock.
  6. The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they're waiting on.

Part 6. Packages java.lang.* java.util.*

40. Given a string constructed by calling s = new String(“xyzzy”), which of the calls modifies the string?

  1. s.append(“aaa”);
  2. s.trim();
  3. s.substring(3);
  4. s.replace(‘z’, ‘a’);
  5. s.concat(s);
  6. None of the above

41. Suppose you want to write a class that offers static methods to compute hyperbolic trigonometric functions. You decide to subclass java.lang.Math and provide the new functionality as a set of static methods.

Which one statement is true about this strategy?
  1. The strategy works.
  2. The strategy works, provided the new methods are public.
  3. The strategy works, provided the new methods are not private.
  4. The strategy fails because you cannot subclass java.lang.Math.
  5. The strategy fails because you cannot add static methods to a subclass

42. Which one statement is true about the following code fragment?

	import java.lang.Math;
 	Math myMath = new Math();
 	System.out.println(“cosine of 0.123 = “ +  myMath.cos(0.123));
  1. Compilation fails at line 2.
  2. Compilation fails at line 3.
  3. Compilation succeeds, although the import on line 1 is not necessary. During execution, an exception is thrown at line 3.
  4. Compilation succeeds. The import on line 1 is necessary. During execution, an exception is thrown at line 2 or 3.
  5. Compilation succeeds and no exception is thrown during execution.

43. Which of the following classe implements java.util.List? (Choose all that apply.)

  1. java.util.Array
  2. java.util.HashList
  3. java.util.StackList
  4. java.util.Stack

44. Given:

	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() + " " );
    }
What is the result?
  1. Compilation fails.
  2. one two three four
  3. four three two one
  4. four one three two
  5. one two three four one
  6. one four three two one
  7. An exception is thrown at runtime.
  8. The print order is not guaranteed.

45. Fill all the blanks from the following? (You need to provide an answer for each A,B,C,D option)

  1. Math.abs(3.0) returns 3.0
    Math.abs(-3.4) returns ____
  2. Math.ceil(3.4) returns ____
    Math.ceil(-3.4) returns -3.0
  3. Math.floor(3.4) returns ____
    Math.floor(-3.4) returns -4.0
  4. Math.round(3.4) returns 3
    Math.round(-3.4) returns ____

Part 7. Patterns

46. Which design pattern can be used to create a family of dependent objects?

  1. Factory Method
  2. Prototype
  3. Builder
  4. Abstract
  5. Singleton

47. You can traverse through the elements of many Java Collection objects because they provide a way to access their elements sequently. What design pattern is used here?

  1. Visitor
  2. Observer
  3. Builder
  4. Iterator
  5. Proxy
  6. Decorator

48. You are designing complex set of classes that provides a secure framework for other developers to use.

The main idea of this framework is to allow other developers to write secure programs without knowing the complexities of writing secure applications. What sort of design pattern is being used here?
  1. Composite
  2. Façade
  3. Decorator
  4. Adapter

49. Here is realization of singleton pattern:

1.	public  class MySingleton
2.	{
3.	    private static MySingleton _instance = null;
    
4.	    public static MySingleton getInstance()
5.	   {
6.	        if (_instance == null)
7.	        {
8.	             _instance = new MySingleton();
9.	         }
10.	         return _instance;
11.	    }	
12.	 }
What kind of problems can lead such realization? [Check all correct answers]
  1. User can create different instances of MySingleton class form single thread
  2. User can create different instances of MySingleton class from several threads
  3. NullpointerException rises when method MySingleton.getInstance() will be invoked
  4. Code will not compile
What should be done to prevent it? [Check all correct answers]
  1. A. Add following line after line 3:
    4. private MySingleton() {}
  2. B. Add following line after line 7 instead of line8:
    8. synchronized (MySingleton.class) {
    9. if (_instance == null) {
    10. _instance = new MySingleton();
    11. }
  3. C. Modify line 4 in this way:
    4. public synchronized static MySingleton getInstance()
  4. D. Add following line after line 7 instead of line8:
    8. synchronized (this) {
    9. _instance = new MySingleton();
    10. }
  5. E. Modify line 3in this way:
    3. private volatile static MySingleton _instance = null;

Part 8. Internationalization

50. What is ResourceBundle class used for?

  1. To store information about the program like external configuration file.
  2. To store parts of the program that is Locale sensitive, e.g. the text on a message window
  3. To get access to the local system resources like files etc.
  4. To access properties of the users environment, language and a region

Part 9. Swing

51. Which text component is best suited for controlling the format of a single line of user-entered text?

  1. JTextField
  2. JMaskTextField
  3. JFormattedTextField
  4. JControlField

52. What interface does the class containing the below code most likely implement?

	public void actionPerformed(ActionEvent e) {
	}
  1. AWTEvent
  2. ComponentEvent
  3. ActionListener
  4. WindowListener
  5. ActionAdapter

53. Which method will cause a Frame to be displayed?

  1. show()
  2. setEnabled(b)
  3. displayWindow()
  4. displayFrame()

54. Choose valid layout:

  1. RowLayout
  2. FrameLayout
  3. GridBagLayout
  4. LeftToRightLayout