Course: CPS 189: Java Certification - Review, Practice & Prepare (Development)

Q: Identify the invalid Java identifier.
- 1Week
- Week1
- amountDue
- amount_due
A: 1Week

Q: What is the value of the variable amountDue?

double price = 2.50
double quantity = 5
double amountDue = 0
amountDue = price*  quantity
- 12
- 12.25
- 12.5
- 13
A: 12.5

Q: The syntax that declares a Java named constant named SALES_TAX is:
- double SALES_TAX = 7.50;
- public double SALES_TAX = 7.50;
- public static double SALES_TAX = 7.50;
- public static final double SALES_TAX = 7.50;
A: public static final double SALES_TAX = 7.50;

Q: Java does not require that a variable be declared before it is used within a program.
- True
- False
A: False

Q: Define the terms class, object, method, and method call.

Q: What is the value of the variable c in the statements that follow?
String phrase = "Make hay while the sun is shining.";
char c = phrase.charAt(10);
- w
- h
- i
- None of the above
A: h

Q: A variable of type boolean can be explicitly converted to that of type int.
- True
- False
A: False

Q: Objects of type String are strings of characters that are written within single quotes.
- True
- False
A: False

Q: In Java, Strings are immutable objects. Immutable objects can be changed.
- True
- False
A: False

Q: List the primitive data types Java supports. Indicate the kind of values each type can store.

Q: What does the String method trim() do? Give an example of its use.

Q: What is the output of the following Java statements?
//String method examplesString str = "Java Programming!";
System.out.println(str.equals("Java Programming!"));
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
System.out.println(str.substring(5,8));
System.out.println(str.lastIndexOf("m"));

Q: Write a Java statement to access the 7th character in the String variable myString and place it in the char variable [c].
A: c = myString.charAt(6);

Q: Write a Java statement to determine the length of a string variable called input. Store the result in an integer variable called strLength. int strLength =
A: input.length();

Q: In Java, the equal sign is used as the _______ operator.
- Increment
- Decrement
- Assignment
- Negation
A: Assignment

Q: What is the Java expression for 4a2 + 2b * c?
- (4 * a)+(2 * b) * c
- (4 * a * a)+((2 * b) * c)
- ((4 * a * a)+(2 * b)) * c
- (4 + a * a)+((2 + b) * c)
A: (4 * a * a)+((2 * b) * c)

Q: What is the Java expression for 27xy?
- 27 + (x * y)
- 27 * (x + y)
- 27 * x * y
- 27x * y
A: 27 * x * y

Q: Which operator is used to concatenate two strings?
- +
- -
- *
- /
A: +

Q: Which operator returns the remainder of integer division?
- %
- /
- *
- None of the above
A: %

Q: An if selection statement executes if and only if:
- The Boolean condition evaluates to false
- The Boolean condition evaluates to true
- The Boolean condition is short-circuited
- None of the above
A: The Boolean condition evaluates to true

Q: The ______ operator has the highest precedence.
- *
- dot
- +=
- decrement
A: dot

Q: In a switch statement, the choice of which branch to execute is determined by an expression given in parentheses after the keyword switch.
- True
- False
A: True

Q: In a switch statement, the default case is always executed.
- True
- False
A: False

Q: What is the output produced by the following lines of code?

int value1 = 3
int vale2 = 4
int result  = 0
result = value1++ * value2--
System.out.println("Post increment/decrement: " + result)
result = ++value1 * --value2
System.out.println("Pre increment/decrement: " + result)
Feedback: Post increment/decrement: 12 Pre increment/decrement: 10

Q: The looping mechanism that always executes at least once is the ______ statement.
- if...else
- do...while
- while
- for
A: do...while

Q: When the number of repetitions are known in advance, you should use a ______ statement.
- while
- do...while
- for
- None of the above
A: for

Q: The for statement, do...while statement, and while statement are examples of branching mechanisms.
- True
- False
A: False

Q: What is a sentinel value and how is it used?

Q: Write Java code that uses a do...while loop that prints even numbers from 2 through 10.
Feedback: int evenNumber =2; do { System.out.println(evenNumber); evenNumber +=2; }while(evenNumber <= 10);

Q: Write Java code that uses a while loop to print even numbers from 2 through 10.
Feedback: int evenNumber = 2; while(evenNumber <= 10) { System.out.println(evenNumber); evenNumber +=2; }

Q: What is the output of the following code segment?

public static void main(String[] args)
{
int x = 5;
System.out.println("The value of x is:" + x);
while(x > 0)
{
x++;
}
System.out.println("The value of x is:" + x);
}
Feedback: The value of x is 5. The program then enters an infinate loop because the value of x is always greater than 0.

Q: Discuss the differences between the break and the continue statements when used in looping mechanisms.

Q: Write a complete Java program that prompts the user for a series of numbers to determine the smallest value entered. Before the program terminates, display the smallest value.
Feedback: import java.util.Scanner; public class FindMin { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int smallest = 9999999; String userInput; boolean quit = false; System.out.println(”This program finds the smallest number” + “in a series of numbers”); while(quit !=true) { System.out.print(”Enter a number: “); userInput = keyboard.next(); if(userInput.equals(”Q”) || userInput.equals(”q”)) { quit = true; } else { int userNumber = Integer.parseInt(userInput); if(userNumber < smallest) smallest = userNumber; } } System.out.println(”The smallest number is “ + smallest); System.exit(0); } }

Q: Write a complete Java program that uses a for loop to compute the sum of the even numbers and the sum of the odd numbers between 1 and 25.
Feedback: public class sumEvenOdd { public static void main(String[] args) { int evenSum = 0; int oddSum = 0; //loop through the numbers for(int i=1; i <= 25; i++) { if(i % 2 == 0) { //even number evenSum += i; } else { oddSum += i; } } //Output the results System.out.println(”Even sum = “ + evenSum); System.out.println(”Odd sum = “ + oddSum); } }

Q: A method that preforms some action other than returning a value is called a _______ method.
- Null
- Void
- Public
- Private
A: Void

Q: The body of a method that returns a value must contain at least one ______ statement.
- Void
- Invocation
- Throws
- Return
A: Return

Q: A variable whose meaning is confined to an object of a class is called:
- Instance variable
- Local variable
- Glocal variable
- None of the above
A: Instance variable

Q: A variable whose meaning is confined to a method definition is called an/a:
- Instance variable
- Local variable
- Global variable
- None of the above
A: Local variable

Q: In Java, a block is delimited by:
- ( )
- /* */
- " "
- { }
A: { }

Q: When you want the parameters in a method to be the same as the instance variables you can use the ______ parameter.
- String
- Hidden
- Default
- This
A: This

Q: Java has a way of offically hiding details of a class definition. To hide details, you mark them as ______.
- Public
- Protected
- Private
- All of the above
A: Private

Q: A set method is:
- An accessor method
- A mutator method
- A recursive method
- None of the above
A: A mutator method

Q: Accessor methods:
- Return something equivalent to the value of an instance variable.
- Promotes abstraction
- Both A and B
- None of the above
A: Both A and B

Q: The name of a method and the list of _______ types in the heading of the method definition is called the method signature.
- Parameter
- Argument
- Return
- Primitive
A: Parameter

Q: Method overloading is when two or more methods of the same class have the same name but differ in number or types of parameters.
- True
- False
A: True

Q: Java supports operator overloading.
- True
- False
A: False

Q: Define the terms arguments and parameters. How are they different?

Q: Inheritance is the process by which a new class - known as a ______ - is created from another class, called the ______.
- Base class, Derived class
- Dervied class, Base class
- Inherited class, Base class
- Base class, inherited class
A: Dervied class, Base class

Q: Inheritance promotes code ______.
- Reinvention
- Reuse
- Repeats
- All of the above
A: Reuse

Q: The keyword extends indicates:
- Encapsulation
- Polymorphism
- Inheritance
- None of the above
A: Inheritance

Q: A derived class is also called a:
- Sub class
- Super class
- Base class
- All of the above
A: Sub class

Q: A super class is also called a:
- Derived class
- Dominant class
- Sub class
- Base class
A: Base class

Q: What does a derived class automatically inherit from the base class?
- Instance variables
- Static variables
- Public variables
- All of the above
A: All of the above

Q: A base class is synonymous with a:
- Child class
- Parent class
- Derived class
- Sub class
A: Parent class

Q: The special syntax for invoking a constructor of the base class is:
- super()
- base()
- parent()
- child()
A: super()

Q: In using the keyword this in place of super(), the invocation of this must be the ______ action taken by the constructor.
- First
- Last
- It does not matter
- None of the above
A: First

Q: A method or instance variable modified by protected:
- Can not be accessed by name inside its own class definitions
- Can not be accessed by name inside any class derived from it
- Can not be accessed by name in the definition of any class in the same package
- Can not be accessed by name in any other class (that is, other than classes named in a-c)
A: Can not be accessed by name in any other class (that is, other than classes named in a-c)

Q: The class ______ is an ancestor class of all Java classes.
- String
- Object
- Math
- JFrame
A: Object

Q: Inheritance refers to a very specialized form of a class.
- True
- False
A: False

Q: The keyword extends indicates polymorphism.
- True
- False
A: False

Q: Overriding is when a derived class redefines a method from the base class.
- True
- False
A: True

Q: A constructor for a derived class begins with an invocation of a constructor for a base class.
- True
- False
A: True

Q: You may substitute the keyword this for super() to call a constructor of the derived class.
- True
- False
A: True

Q: An instance variable (or method) that is private in a base class is accessible by name in the definition of a method in any other class.
- True
- False
A: False

Q: Try blocks contain code that could possibly:
- Handle an exception
- Throw an exception
- Catch an exception
- Display an exception
A: Throw an exception

Q: A ______ block should immediately follow a try block.
- Try
- Catch
- Fail
- Final
A: Catch

Q: Exceptions that are subject to the catch or declare rule are called:
- Checked exceptions
- Unchecked exceptions
- Fatal exceptions
- All of the above
A: Checked exceptions

Q: Exception handling is an example of a programming methodology known as:
- Structured programming
- Object oriented programming
- Goto programming
- Event-driven programming
A: Event-driven programming

Q: A ______ block executes regardless of whether an exception occurs.
- Final
- Finally
- Catch
- None of the above
A: Finally

Q: An exception is caught in a ______ block.
- Try
- Catch
- Finally
- All of the above
A: Catch

Q: The basic way of handling exceptions in Java consists of the try-catch-throw trio.
- True
- False
A: False

Q: When an exception is thrown, the code is the surrounding try block continues executing and then the catch block begins execution.
- True
- False
A: False

Q: A program can catch multiple exceptions.
- True
- False
A: True

Q: Exceptions that must follow the Catch or Declare Rule are often called unchecked exceptions.
- True
- False
A: False

Q: Write a Java statement that throws a new exception with the String: File Not Found.
Feedback: throw next Exception("File Not Found");

Q: Write a Java statement that throws a new exception with the String: Disk drive not ready.
Feedback: throw new Exception("Disk Drive Not Ready!");

Q: Two methods that are expected to be in all Java classes are:
- getName and setName
- toString and equals
- compareTo and charAt
- toLowerCase and toUpperCase
A: toString and equals

Q: An object of class A is an instance of class A.
- True
- False
A: True

Q: An invocation of a method that returns a value can be used as an expression any place that a value of the Type_Returned can be used.
- True
- False
A: True

Q: In a method invocation, there must be exactly the same number of arguments in parentheses as there are formal parameters in the method definition heading.
- True
- False
A: True

Q: Inside a Java method definition, you can use the keyword this as a name for the calling object.
- True
- False
A: True

Q: What is the purpose of the new operator?

Q: Discuss a situation in which it is appropriate to use the this parameter.

Q: Discuss the public and private modifiers in context of methods and instance variables.

Q: Discuss the importance of accessor and mutator methods and how they apply to the abstraction concept.

Q: A Java interface is an example of:
- encapsulation
- abstraction
- polymorphism
- all of the above
A: abstraction

Q: A class that uses an interface must use the keyword:
- Extends
- Inherits
- Super
- Implements
A: Implements

Q: An interface and all of its method headings are normally declared to be:
- public
- private
- protected
- package access
A: public

Q: In Java, a derived class can have ________ base class(es).
- one
- two
- three
- there is no limit
A: one

Q: A class that implements an interface but only gives definitions for some of the method headings given in the interface is called a/an:
- concrete class
- abstract class
- discrete class
- friendly class
A: abstract class

Q: An interface may contain:
- instance variables
- primitive variables
- constant variables
- all of the above
A: constant variables

Q: Any constant variables defined in an interface must be defined as:
- public
- private
- protected
- package access
A: public

Q: Java interfaces are a way of simulating multiple inheritance.
- True
- False
A: True

Q: An interface specifies the headings and definitions for methods that must be defined in any class that implements the interface.
- True
- False
A: False

Q: A class may only implement one interface.
- True
- False
A: False

Q: An interface is a type.
- True
- False
A: True

Q: You can not derive an interface from a base interface.
- True
- False
A: False

Q: What are the obligations of a class that implements a specific interface?

Q: Class and method definitions that include parameters for types are called:
- generics
- ArrayList
- Base type
- None of the above
A: generics

Q: All of the following are methods of the ArrayList class except:
- length()
- size()
- set()
- get()
A: length()

Q: To place an element in an ArrayList position for the first time, you usually use the method:
- put()
- set()
- add()
- place()
A: add()

Q: A class obtained from a generic class by plugging in a type for the type parameter is said to ________ the generic class.
- Inherit
- Encapsulate
- Instantiate
- None of the above
A: Instantiate

Q: A generic class can be instantiated as any of the following base types except:
- Character
- Array
- String
- Double
A: Array

Q: The keyword ___________ can be used to place a bound on a type parameter.
- Implements
- Inherits
- Encapsulates
- Extends
A: Extends

Q: The Type parameter is always indicated as a T.
- True
- False
A: False

Q: The definition of a parameterized class is a class with one or more type parameters.
- True
- False
A: True

Q: You can plug in a primitive type for a type parameter.
- True
- False
A: False

Q: What is a parameterized class?

Q: A ____________ is a data structure for holding elements.
- Collection
- Iterator
- Vector
- Wildcard
A: Collection

Q: All of the following are members of Java’s Collection class except:
- Queue<T>
- LinkedList<T>
- Vector<T>
- Set<T>
A: Queue<T>

Q: The interface SortedSet and the concrete class _________ is designed for implementations of the Set interface that provide for rapid retrieval of elements.
- Vector<T>
- LinkedList<T>
- HashSet<T>
- TreeSet<T>
A: TreeSet<T>

Q: The difference between the List<T> interface and the Set<T> interface is that the Set<T> interface does not impose an order on its unique elements.
- True
- False
A: True

Q: The V parameter in a HashMap<K,V> may be any object, but the K parameter must be a String.
- True
- False
A: False

Q: The Java programming language allows you to concatenate two strings using the plus sign.
- True
- False
A: True

Q: To compare two strings lexicographically the String method ____________ should be used.
- equals
- equalsIgnoreCase
- compareTo
- ==
A: compareTo

Q: The method trim of the String class trims off:
- Leading white space
- Trailing white space
- Leading and trailing white space
- Blanks
A: Leading and trailing white space

Q: The String class is a mutable class.
- True
- False
A: False

Q: Write a complete Java program that prompts the user for a phrase.  The program converts and displays the phrase in uppercase letters.

import java.util.Scanner;

public class convertToUpper
{

public static void main(String[] args)
{
//Create a scanner object for input
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a phrase and I'll convert it to uppercase.");
String phrase = keyboard.nextLine();
System.out.println(phrase.toUpperCase());
}
}

Q: An array of chars is the same as a String in Java.
- True
- False
A: False

Q: Write a Java statement that declares and creates an array of Strings named Breeds.  Your array should be large enough to hold the names of 100 dog breeds.

Q: An ___________ allows data to flow into your program.
- input stream
- output stream
- file name
- all of the above
A: input stream

Q: Files whose contents must be handled as sequences of binary digits are called:
- text files
- ASCII files
- binary files
- output files
A: binary files

Q: The output stream connected to the computer screen is:
- System.exit
- System.quit
- System.in
- System.out
A: System.out

Q: In Java, when you open a text file you should account for a possible:
- FileNotFoundException
- FileFullException
- FileNotReadyException
- all of the above
A: FileNotFoundException

Q: There are two common classes used for reading from a text file.  They are:
- PrintWriter and BufferedReader
- FileInputStream and Scanner
- BufferedReader and Scanner
- None of the above
A: BufferedReader and Scanner

Q: All of the following are methods of the Scanner class except:
- nextFloat()
- next()
- useDelimiter()
- readLine()
A: readLine()

Q: The method _________ reads a single character from an input stream.
- readLine()
- skip()
- read()
- close()
A: read()

Q: A __________ path name gives the path to a file, starting with the directory that the program is in.
- relative
- descendant
- full
- complete
A: relative

Q: The stream that is automatically available to your Java code is:
- System.out
- System.in
- System.err
- all of the above
A: all of the above

Q: All of the following are methods of the File class except:
- exists()
- delete()
- getDirectory()
- getName()
A: getDirectory()

Q: When your program is finished writing to a file, it should close the stream connected to that file.
- True
- False
A: True

Q: Using BufferedReader to read integers from a file requires the String input to be parsed to an integer type.
- True
- False
A: True

Q: Explain what happens when an output file is opened in Java.
Feedback: In Java, when an output stream is connected to a file, the program always starts with an empty file. If the file you are trying to connect to exists, the contents of the file are deleted before the output stream writes new data to the file. If the file you are trying to connect to does not exist, then a new empty file is created.

Q: Write a Java statement to create an input stream to the binary file statistics.dat.

Q: Write a Java statement to create an input stream to a file named “statistics.dat”.
Feedback: Scanner inputStream = new Scanner(new FileReader("statistics.dat"));

Q: Create try and catch block that opens a file named statistics.txt for output.  Writes the integers 24, 55, and 76 to the file, and then closes the file.
Feedback: PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream("statistics.txt")); outputStream.println(24); outputStream.println(55); outputStream.println(76); outputStream.close(); } catch(FileNotFoundException e) { System.out.println("Error opening the file autos.txt"); System.exit(0); }

Q: The Java library that supports database connectivity is called:
- ODBC
- CDBC
- MDBC
- JDBC
A: JDBC

Q: SQL stands for Structured Query Language.
- True
- False
A: True

Q: Threads execute in a ___________ fashion.
- parallel
- serial
- complex
- none of the above
A: parallel

Q: Java’s Thread class is in the ____________ package.
- java.util
- java.thread
- java.lang
- javax.swing
A: java.lang

Q: The sleep method of the Thread class requires one formal parameter that represents the number of:
- nanoseconds
- microseconds
- picoseconds
- milliseconds
A: milliseconds

Q: 4) What method in the Thread class is responsible for pausing a thread for a specific amount of milliseconds?
- pause()
- sleep()
- hang()
- kill()
A: sleep()

Q: The programming statements used to accomplish a threads task should be included in the method:
- start()
- init()
- run()
- none of the above
A: run()

Q: The Java language does not support multithreading.
- True
- False
A: False

Q: An InterruptedException is a checked exception.
- True
- False
A: True

Q: A thread’s start method invokes the thread’s run method.
- True
- False
A: True

Q: An alternative to deriving a thread from the Thread class is to inherit the Runnable interface.
- True
- False
A: False

Q: What is the output of this program?
- Height
- Male
- Exception
- Warning
A: Height

Q: What is the output of this program when run with command java PE02 44?
- 44
- 4 4
- Exception
- Warning
A: Exception

Q: What is the correct order for the following parts of a class?
- package, imports, static methods, classes
- imports, package, classes
- package, static imports, classes
- imports, static imports, package, classes
A: package, static imports, classes

Q: What is the output of this program?
- The sum is 12
- The sum is 24
- The sum is 5712
- Compilation error
- Exception
- Warning
A: Compilation error

Q: What is the output of this program?
- 7
- 0
- Compilation error
- Exception
- Warning
A: Compilation error

Q: What is the output of this program?
- 10
- 1
- 11
- Compilation error
- Exception
- Warning
A: Compilation error

Q: What is the output of this program?
- true
- false
- Compilation error
- Exception
- Warning
A: false

Q: What is the output of this program?
- 123d
- 012d2d
- 0123d
- Compilation error
- Exception
A: 012d2d

Q: Which of the following data types may not be used in the switch statement expression?
- int
- String
- enum
- boolean
A: boolean

Q: Which of the following one-dimensional array declarations are legal?
- int a[] = new int [3] {1, 2, 3};
- int b[2] = {1, 2};
- int c[] = {1, 2, 3, 4};
- int[] d = new int[][4];
- int[] e = new int [2] {1};
A: int c[] = {1, 2, 3, 4};

Q: What is the output of this program?
- 789
- 78
- 7
- Compilation error
- Exception
A: Exception

Q: What is the output of this program?
- 810420
- 6121824
- 6121812
- Compilation error
- Exception
A: Compilation error

Q: What is the output of this program?
- 0
- 4
- Compilation error
- Infinite loop
- Exception
A: Infinite loop

Q: What is the output of this program?
- wxyz
- w
- Compilation error
- Infinite loop
- Exception
A: Compilation error

Q: What is the output of this program?
- true
- false
- Compilation error
- Infinite loop
- Exception
A: false

Q: What is the output of this program?
- 3
- 2
- 1
- Compilation error
- Infinite loop
A: 3

Q: Which of the following method declaration is valid?
- methodA(void) {}
- void methodB() {;}
- void methodC {}
- void methodD() {//}
A: void methodB() {;}

Q: What is the output of this program?
- 30
- 300
- Compilation error
- Exception
A: Compilation error

Q: Which of the following is false?
- A class can be marked abstract only if at least one of its methods is abstract.
- A class inherits all the public methods of its parent class.
- Interface methods are public, even if they don’t have that modifier.
- Abstract classes may not be instantiated.
A: A class can be marked abstract only if at least one of its methods is abstract.

Q: What is the output of this program?
- 38
- 35
- 5
- Compilation error
- Exception
A: 38

Q: What is the output of this program?
- AB
- BA
- Compilation error
- Exception
A: Compilation error

Q: What is the output of this program?
- 0
- Compilation error
- Exception
A: Exception

Q: What is the output of this program?
- 21
- Compilation error
- Exception
A: 21

Q: Which of the following is true?
- All try blocks must have at least one catch block.
- Subclasses of RuntimeException cannot be declared in a throws clause.
- Error is a subclass of Exception.
- Only exceptions provided by Java may be used.
- The throw statement can throw any subclass of RuntimeException.
A: The throw statement can throw any subclass of RuntimeException.

Q: What is the output of this program?
- Exception myExcept is thrown.
- Exception PE25 is thrown.
- Exception is thrown.
A: Exception myExcept is thrown.

Q: What is the output of this program?
- nothing
- Programming
- Compilation error
- Exception
A: Programming

Q: What is the output of this program?
- 156
- 150
- 50
- Compilation error
- Exception
A: 156

Q: What is the output of this program?
- 25
- 26
- 5
- 6
A: 26

Q: What is the output of this program?
- 9
- 109
- Compilation error
- Exception
A: Compilation error

Q: What of the above array declarations is correct?
- A
- B
- C
- D
A: A

Q: Which of the following statements is true?
- The for-each loop cannot be used within a regular for loop.
- The for-each loop can be used within a do-while loop.
- The for-each loop can be used to loop through and modify array elements.
- The for-each loop cannot be used within a while loop.
- All the statements are false.
A: The for-each loop can be used within a do-while loop.

Q: What is the output of this program?
- 0

1
- In else clause
- Compilation error
- Exception
A: In else clause

Q: Which statement is correct?
- This code is well-encapsulated.
- This code insures that the score will be less than 300.
- This code insures that the score will be a positive number.
- This code is not well-encapsulated.
A: This code is not well-encapsulated.

Q: What is the output of this program?
- 30

31

40

30
- 31

30

40

30
- Compilation error
- Exception
A: 31

30

40

30

Q: What is the output of this program?
- Animal walking

Dog Walking
- Cat walking

Dog walking
- Animal walking

Animal walking
- Exception
A: Animal walking

Dog Walking

Q: Which statement is correct?
- This shows polymorphism with classes.
- This shows polymorphism with interfaces.
- This shows polymorphism with concrete methods.
- None of the above.
A: None of the above.

Q: What is the output of this program?
- X

Inner try

Y

Outer try
- X

Inner try

Y
- X

Y
- Exception
A: X

Inner try

Y

Q: Which statement is correct?
- If A is a class and B is an interface, then A extends B.
- If A is an interface and B is a class, then A extends B.
- If A and B are both classes or both interfaces, then A extends B.
- For any combination of classes and interfaces, then A extends B.
A: If A and B are both classes or both interfaces, then A extends B.

Q: What is the output of this program?
- 7
- 4
- Compilation error
- Exception
A: Compilation error

Q: What is the output of this program?
- Just drive

Drive vehicle
- Just drive

Just drive
- Compilation error
- Exception
A: Just drive

Drive vehicle

Q: What is the output of this program?
- blue Drive vehicle
- green Drive car
- green Drive vehicle
- blue Drive car
A: blue Drive car

Q: What is the output of this program?
- +124
- +134
- +434
- Compilation error
- Exception
A: +434

Q: What is the output of this program?
- A4B
- A4
- Compilation error
- Exception
A: Compilation error

Q: Which class can adjust its size, provide indexed access to its elements, but is not synchronized?
- java.util.Vector
- java.util.HashSet
- java.util.List
- java.util.PriorityQueue
- java.util.ArrayList
A: java.util.ArrayList

Q: What is the output of this program?
- A A B
- A A D
- A D
- A D B
- Compilation error
- Exception
A: A A B

Q: What is the size of the tree set?
- 6
- 5
- 4
- 3
A: 5

Q: What is the output of this program?
- 3 3
- 1 1
- Compilation error
- Exception
A: Exception

Q: class Person
{
static class Male
{
static String description = "Male";
}
static Height male = new Height();

}
class Height
{
String description = "Height";
}
public class PE01
{
public static void main (String[] args)
{
System.out.println(Person.male.description);
}
}

What is the output of this program?
- Height
- Male
- Exception
- Warning
A: Height

Q: public class PE02
{
public static void main (String[] args)
{
System.out.println(args[0] + args[1]);
}
}

What is the output of this program when run with command java PE02 44?
- 44
- 4 4
- Exception
- Warning
A: Exception

Q: What is the correct order for the following parts of a class?
- package, imports, static methods, classes
- imports, package, classes
- package, static imports, classes
- imports, static imports, package, classes
A: package, static imports, classes

Q: public class PE04
{
int a = 5;
int b = 7;
static String c = "The sum is ";
public int sum (int n)
{
return a + b + n;
}
public static void main (String[] args)
{
String message = c + new PE04().sum(a + b);

System.out.println(message);
}
}

What is the output of this program?
- The sum is 12
- The sum is 24
- The sum is 5712
- Compilation error
- Exception
- Warning
A: Compilation error

Q: public class PE05
{
public PE05 t;
public int number;
PE05()
{
}
PE05(PE05 o)
{
t = o;
}
public void print()
{
System.out.println(t.number);
}
public static void main (String[] args)
{
PE05 t1 = new PE05();
PE05 t2 = new PE05(t1);
PE05 t3 = new PE05(t2);
t1.number = 7;
t1.print();
}
}

What is the output of this program?
- 7
- 0
- Compilation error
- Exception
- Warning
A: Compilation error

Q: public class PE06
{
private static int basePrice = 1;
static
{
basePrice += COST;
}
public final static int COST = 10;
public static void main (String[] args)
{
System.out.print(basePrice);
}
}

What is the output of this program?
- 10
- 1
- 11
- Compilation error
- Exception
- Warning
A: Compilation error

Q: public class PE07
{
public static void main (String[] args)
{
System.out.print(false?true:false!=false?true:false);
}
}

What is the output of this program?
- true
- false
- Compilation error
- Exception
- Warning
A: false

Q: public class PE08
{
public static void main (String[] args)
{
String result = "";
for (int i = 0; i < 3; i++)
{
switch (i++)
{
case 0: result += "0";
case 1: result += "1";
case 2: result += "2";
default: result += "d"; break;
case 3: result += "3";
}
}
System.out.print(result);
}
}

What is the output of this program?
- 123d
- 012d2d
- 0123d
- Compilation error
- Exception
A: 012d2d

Q: Which of the following data types may not be used in the switch statement expression?
- int
- String
- enum
- boolean
A: boolean

Q: Which of the following one-dimensional array declarations are legal?
- int a[] = new int [3] {1, 2, 3};
- int b[2] = {1, 2};
- int c[] = {1, 2, 3, 4};
- int[] d = new int[][4];
- int[] e = new int [2] {1};
A: int c[] = {1, 2, 3, 4};

Q: import java.util.ArrayList;
public class PE11
{
public static void main (String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(7);
al.add(8);
al.add(9);
Integer[] a = new Integer[2];
al.toArray(a);
for (int i : a)
System.out.print(i);
}
}

What is the output of this program?
- 789
- 78
- 7
- Compilation error
- Exception
A: Exception

Q: public class PE12
{
public static void main (String[] args)
{
int[] a = {5, 10, 15, 20};
a[2] = 4;
a[0] = 8;
a = {6, 12, 18, 24};
a[3] = 12;
for (int i = 0; i < a.length; i++)
System.out.print(a[i]);
}
}

What is the output of this program?
- 810420
- 6121824
- 6121812
- Compilation error
- Exception
A: Compilation error

Q: public class PE13
{
public static void main (String[] args)
{
for (int i = 0; i < 40; i = 4)
{
if (i % 2 != 0) System.out.print(i);
}
}
}

What is the output of this program?
- 0
- 4
- Compilation error
- Infinite loop
- Exception
A: Infinite loop

Q: public class PE14
{
public static void main (String[] args)
{
String[] arr = {"w", "x", "y", "z"};
String l;
for (l : arr)
System.out.print(l);
}
}

What is the output of this program?
- wxyz
- w
- Compilation error
- Infinite loop
- Exception
A: Compilation error

Q: public class PE15
{
public static void main (String[] args)
{
int i = 0;
int c1 = 0;
int c2 = 0;
while (++i < 10)
{
if (i % 2 == 0)
c1++;
}
i = 0;
do
{
if (i % 2 == 0)
c2++;
} while (++i < 10);
System.out.println(c1 == c2);
}
}

What is the output of this program?
- true
- false
- Compilation error
- Infinite loop
- Exception
A: false

Q: public class PE16
{
static int counter = 0;
static void methodWithArbitraryParms(String... a)
{
counter++;
}
public static void main (String[] args)
{
methodWithArbitraryParms();
methodWithArbitraryParms(null);
methodWithArbitraryParms(new String[]{"x", "y", "z"});
System.out.println(counter);
}
}

What is the output of this program?
- 3
- 2
- 1
- Compilation error
- Infinite loop
A: 3

Q: Which of the following method declaration is valid?
- methodA(void) {}
- void methodB() {;}
- void methodC {}
- void methodD() {//}
A: void methodB() {;}

Q: class ParentClass
{
protected int i = 10;
private void multiply(int m)
{
i *= m;
}
}
public class PE18 extends ParentClass
{
public static void main (String[] args)
{
PE18 obj = new PE18();
obj.multiply(30);
System.out.println(obj.i);
}
}

What is the output of this program?
- 30
- 300
- Compilation error
- Exception
A: Compilation error

Q: Which of the following is false?
- A class can be marked abstract only if at least one of its methods is abstract.
- A class inherits all the public methods of its parent class.
- Interface methods are public, even if they don’t have that modifier.
- Abstract classes may not be instantiated.
A: A class can be marked abstract only if at least one of its methods is abstract.

Q: class ParentClass
{
static int y = 7;
ParentClass(int x)
{
y = y * 5;
}
ParentClass()
{
this(y);
++y;
}
}
public class PE20 extends ParentClass
{
public static void main (String[] args)
{
new PE20();
System.out.println(y);
}
PE20()
{
y = y + 2;
}
}

What is the output of this program?
- 38
- 35
- 5
- Compilation error
- Exception
A: 38

Q: interface inf
{
inf()
{
System.out.println("A");
}
}
abstract class abs implemnts inf
{
abs()
{
System.out.println("B");
}
}
public class PE21 extends abs
{
public static void main (String[] args)
{
new PE21();
}
}

What is the output of this program?
- AB
- BA
- Compilation error
- Exception
A: Compilation error

Q: public class PE22
{
public static void main (String[] args)
throws IndexOutOfBoundsException
{
int d1 = 9;
int d2 = 0;
int result = d1 / d2;
System.out.println(result);
}
}

What is the output of this program?
- 0
- Compilation error
- Exception
A: Exception

Q: public class PE23
{
public static void main (String[] args)
{
PE23 obj = new PE23();
System.out.println(obj.number());
}
private int number()
{
try
{
new RuntimeException();
}
finally
{
return 21;
}

}
}

What is the output of this program?
- 21
- Compilaton error
- Exception
A: 21

Q: Which of the following is true?
- All try blocks must have at least one catch block.
- Subclasses of RuntimeException cannot be declared in a throws clause.
- Error is a subclass of Exception.
- Only exceptions provided by Java may be used.
- The throw statement can throw any subclass of RuntimeException.
A: The throw statement can throw any subclass of RuntimeException.

Q: class myExcept extends Exception {}
public class PE25 extends Exception
{
public static void main (String[] args)
throws myExcept, PE25
{
try
{
if (1 != 3)
throw new myExcept();
else
throw new PE25();
}
catch (Exception e)
{
throw e;
}

}
}

What is the output of this program?
- Exception myExcept is thrown.
- Exception PE25 is thrown.
- Exception is thrown.
A: Exception myExcept is thrown.

Q: class Course
{

protected String courseName;
}
public class PE26
{
public static void main (String[] args)
{
Course c = new Course();
c.courseName = "Programming";
System.out.println(c.courseName);
}
}

What is the output of this program?
- nothing
- Programming
- Compilation error
- Exception
A: Programming

Q: public class PE27
{
public static void main (String[] args)
{
int w = 5;
long x = 10;
short y = 15;
System.out.println(++w + x++ * y);
}
}

What is the output of this program?
- 156
- 150
- 50
- Compilation error
- Exception
A: 156

Q: public class PE28
{
public static void main (String[] args)
{
int w = 5;
do
w = w + 20;
while (w++ < 15);
while (w < 3);
System.out.println(w);
}
}

What is the output of this program?
- 25
- 26
- 5
- 6
A: 26

Q: public class PE29
{
public static void main (String[] args)
{
int[] arr = new int[7];
byte b = 3;
char c = 'd';
long l = 6;
arr[0] = b;
arr[1] = c;
arr[2] = l;
System.out.println(arr[0] + arr[1] + arr[2]);
}
}

What is the output of this program?
- 9
- 109
- Compilation error
- Exception
A: Compilation error

Q: public class PE30
{
public static void main (String[] args)
{
(a)        int[][] arr1 = {{4, 5, 6}, {7, 8, 9}};
(b)        int[][] arr2 = new array() {{4, 5, 6}, {7, 8, 9}};
(c)        int[][] arr3 = {4, 5, 6, 8}, {7, 8, 9};
(d)        int[][][] arr4 = new int[][];
}
}

What of the above array declarations is correct?
- A
- B
- C
- D
A: A

Q: Which of the following statements is true?
- The for-each loop cannot be used within a regular for loop.
- The for-each loop can be used within a do-while loop.
- The for-each loop can be used to loop through and modify array elements.
- The for-each loop cannot be used within a while loop.
- All the statements are false.
A: The for-each loop can be used within a do-while loop.

Q: public class PE32
{
public static void main (String[] args)
{
boolean flag = false;
if (flag)
for (int i = 0; i < 2; i++)
System.out.println(i);
else
System.out.println("In else clause.");
}
}

What is the output of this program?
- 0
1
- In else clause
- Compilation error
- Exception
A: In else clause

Q: public class PE33
{
public int score;
public void setScore (int newScore)
{
if (newScore <= 300)
score = newScore;
}
}

Which statement is correct?
- This code is well-encapsulated.
- This code insures that the score will be less than 300.
- This code insures that the score will be a positive number.
- This code is not well-encapsulated.
A: This code is not well-encapsulated.

Q: public class PE34
{
public static void main (String[] args)
{
int x = 30;
method1(x);
System.out.println(x);
method2(x);
System.out.println(x);
}
static void method1(int value1)
{
++value1;
System.out.println(value1);
}
static void method2(int value2)
{
value2 = 40;
System.out.println(value2);
}
}

What is the output of this program?
- 30
31
40
30
- 31
30
40
30
- Compilation error
- Exception
A: 31
30
40
30

Q: class Animal
{
void walk()
{
System.out.println("Animal walking");
}
}
class Cat extends Animal
{
void walk(int distance)
{
System.out.println("Cat walking");
}
}
class Dog extends Animal
{
void walk()
{
System.out.println("Dog walking");
}
}
public class PE35
{
public static void main (String[] args)
{
Animal cat = new Cat();
Dog dog = new Dog();
cat.walk();
dog.walk();
}
}

What is the output of this program?
- Animal walking
Dog walking
- Cat walking
Dog walking
- Animal walking
Animal walking
- Exception
A: Animal walking
Dog walking

Q: class Animal { }
class Cat extends Animal { }
class Dog extends Animal { }

Which statement is correct?
- This shows polymorphism with classes.
- This shows polymorphism with interfaces.
- This shows polymorphism with concrete methods.
- None of the above.
A: None of the above.

Q: public class PE37
{
public void m1()
{
try
{
String s = null;
System.out.println("X");
try
{
System.out.println(s.length());
}
catch (NullPointerException e1)
{
System.out.println("Inner try");
}
System.out.println("Y");
}
catch (NullPointerException e2)
{
System.out.println("Outer try");
}
}
public static void main (String[] args)
{
PE37 obj = new PE37();
obj.m1();
}
}

What is the output of this program?
- X
Inner try
Y
Outer try
- X
Inner try
Y
- X
Y
- Exception
A: X
Inner try
Y

Q: Which statement is correct?
- If A is a class and B is an interface, then A extends B.
- If A is an interface and B is a class, then A extends B.
- If A and B are both classes or both interfaces, then A extends B.
- For any combination of classes and interfaces, then A extends B.
A: If A and B are both classes or both interfaces, then A extends B.

Q: class Ship
{
int countSails(int a, int b)
{
return a + b;
}
}
public class PE39
{
public static void main (String[] args)
{
Short sails = 4;
System.out.println(countSails(sails, 3));
}
}

What is the output of this program?
- 7
- 4
- Compilation error
- Exception
A: Compilation error

Q: class Vehicle
{
public static String drive()
{
return "Drive vehicle";
}
}
public class PE40 extends Vehicle
{
public static String drive()
{
return "Just drive";
}
public static void main (String[] args)
{
PE40 v1 = new PE40();
Vehicle v2 = new PE40();
System.out.println(v1.drive());
System.out.println(v2.drive());
}
}

What is the output of this program?
- Just drive
Drive vehicle
- Just drive
Just drive
- Compilation error
- Exception
A: Just drive
Drive vehicle

Q: class Vehicle
{
String color = "blue";
String drive()
{
return "Drive vehicle";
}
}
class Car extends Vehicle
{
String color = "green";
String drive()
{
return "Drive car";
}
}
public class PE41
{
void go()
{
Vehicle v = new Car();
System.out.println(v.color + " " + v.drive());
}
public static void main (String[] args)
{
new PE41().go();
}
}

What is the output of this program?
- blue Drive vehicle
- green Drive car
- green Drive vehicle
- blue Drive car
A: blue Drive car

Q: class one {}
class two extends one {}
public class PE42
{
static void over (one[]... a2) { s += "1"; }
static void over (two[]... b1) { s += "2"; }
static void over (two[] b1) { s += "3"; }
static void over (Object o) { s += "4"; }
static String s = "+";
public static void main (String[] args)
{
one[] a1 = new one[2];
two[] a2 = new two[2];
over (a1);
over (a2);
over (7);
System.out.println(s);
}
}

What is the output of this program?
- +124
- +134
- +434
- Compilation error
- Exception
A: +434

Q: import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class PE43
{
@SuppressWarnings("rawtypes")
public static void method ()
{
Set set = new TreeSet();
set.add("A");
set.add(4);
set.add("B");
Iterator iter = set.iterator();
while (iter.hasNext())
System.out.println(iter.next() + " ");
}
public static void main (String[] args)
{
method();
}
}

What is the output of this program?
- A4B
- A4
- Compilation error
- Exception
A: Compilation error

Q: Which class can adjust its size, provide indexed access to its elements, but is not synchronized?
- java.util.Vector
- java.util.HashSet
- java.util.List
- java.util.PriorityQueue
- java.util.ArrayList
A: java.util.ArrayList

Q: import java.util.PriorityQueue;
public class PE45
{
public static void main (String[] args)
{
PriorityQueue<String> priorQ = new PriorityQueue<String>();
priorQ.add("A");
priorQ.add("B");
System.out.print(priorQ.peek() + " ");
priorQ.offer("C");
priorQ.add("D");
priorQ.remove("C");
System.out.print(priorQ.poll() + " ");
if (priorQ.remove("A"))
System.out.print(priorQ.poll() + " ");
System.out.print(priorQ.peek() + " ");
}
}

What is the output of this program?
- A A B
- A A D
- A D
- A D B
- Compilation error
- Exception
A: A A B

Q: import java.util.TreeSet;
public class PE46
{
public static void main (String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();
ts1.add("A");
ts1.add("B");
ts1.add("C");
ts1.add("D");
ts1.add("E");
ts1.add("F");
ts1.pollFirst();
ts1.pollFirst();
ts1.add("G");
System.out.println(ts1.size());
}
}

What is the size of the tree set?
- 6
- 5
- 4
- 3
A: 5

Q: import java.util.TreeSet;
class Truck
{
int size;
Truck(int w) { size = w; }
}
public class PE47
{
public static void main (String[] args)
{
TreeSet<Integer> ts1 = new TreeSet<Integer>();
TreeSet<Truck> ts2 = new TreeSet<Truck>();
ts2.add(new Truck(2));
ts2.add(new Truck(4));
ts2.add(new Truck(6));
ts1.add(2);
ts1.add(4);
ts1.add(6);
System.out.println(ts1.size() + " " + ts2.size());
}
}

What is the output of this program?
- 3 3
- 1 1
- Compilation error
- Exception
A: Exception

Q: import java.util.Arrays;
import java.util.Comparator;
class Season implements Comparator<String>
{
public int compare (String x, String y)
{
return y.compareTo(x);
}
}
public class PE48
{
public static void main (String[] args)
{
String[] arr = {"fall", "winter", "spring", "summer"};
Season s = new Season();
Arrays.sort(arr, s);
for (String a: arr)
System.out.print(a + " ");
System.out.println(Arrays.binarySearch(arr,  "map"));
}
}

What is the output of this program?
- winter summer spring fall 1
- -1
- winter summer spring fall -1
- Compilation error
- Exception
A: winter summer spring fall -1

Q: enum Animals
{

DOG("bark"), CAT("meow"), FISH("bubble");
String sound;
Animals(String s) { sound = s; }
}
public class PE49
{
static Animals a;
public static void main(String[] args)
{
System.out.println(a.DOG.sound + " " + a.FISH.sound);
}
}

What is the output of this program?
- bark meow bubble
- bark bubble
- Compilation error
- Exception
A: bark bubble

Q: public class PE50 implements Device
{
public void doSomething() { }
public static void main(String[] args)
{
System.out.println("In main.");
}
}
abstract class Car1 extends PE50 { }
abstract class Car2 extends PE50
{
public void doIt(int x) { }
}
class Car3 extends PE50 implements Device
{
public void doSomeProcessing() { }
}
interface Device
{
public void doSomething();
}

What is the output of this program?
- (blank)
- Compilatin error
- Exception
- In main.
A: In main.

Q: public class PE51
{
public enum Months { APR, MAY, JUN };
public static void main(String[] args)
{
for(Months d : Months.values() );
Months[] d2 = Months.values();
System.out.println(d2[2]);
}
}

What is the output of this program?
- JUN
- MAY
- APR
- Compilation error
- Exception
A: JUN

Q: Given:
public abstract interface PE52 { public void buildRoad(String s); }

1)
public abstract class City1 implements PE52
{
public abstract void buildRoad(String s) { }
}

2)
public abstract class City2 implements PE52 { }

3)
public class City3 extends PE52
{
public void buildRoad(Integer i) { }
}

4)
public class City4 implements PE52
{
public void buildRoad(Integer i) { }
}

5)
public class City5 implements PE52
{
public void buildRoad(String i) { }
public void buildRoad(Integer s) { }
}

Which of the above definitions are incorrect?
- 1 and 5
- 1 and 4
- 2 and 5
- All of the above
A: 2 and 5

Q: class PE53
{
public PE53(String s)
{
System.out.print("2");
}
}

public class ChildClass extends PE53
{
public ChildClass(String s)
{
System.out.print("4");
}
public static void main(String [] args)
{
new ChildClass("3");
System.out.println(" ");
}
}

What is the output of this program?
- 24
- 42
- 243
- Compilation error
A: Compilation error

Q: class PE54
{
private final void method1()
{
System.out.println("PE54");
}
}

public class ChildClass extends PE54
{
public final void method1()
{
System.out.println("ChildClass");
}
public static void main(String [] args)
{
new ChildClass().method1();
}
}

What is the output of this program?
- ChildClass
- PE54
- ChildClass

PE54
- Compilation error
- Exception
A: ChildClass

Q: Which statement is true?
- Cohesion is the OO principle most closely associated with hiding implementation details
- Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through their APIs
- Cohesion is the OO principle most closely associated with making sure that a class is designed with a single, well-focused purpose
- Cohesion is the OO principle most closely associated with allowing a single object to be seen as having many types
A: Cohesion is the OO principle most closely associated with making sure that a class is designed with a single, well-focused purpose

Q: class C1
{
void do1() {}
}
class C2 extends C1
{
void do2() {}
}
class PE56
{
public static void main(String [] args)
{
C1 x1 = new C1();
C1 x2 = new C2();
C2 y1 = new C2();
<statement here>
}
}

Which line, added at <statement here>, will enable the code above to compile?
- x2.do2();
- (C2) x2.do2();
- ((C2) x2).do2();
- None of the statements.
A: ((C2) x2).do2();

Q: ClassA has a ClassD

Methods in ClassA use public methods in ClassB.

Methods in ClassC use public methods in ClassA.

Methods in ClassA use public variables in ClassB.

Which is most likely true given the above statements?
- ClassD has low cohesion
- ClassA has weak encapsulation
- ClassB has weak encapsulation
- ClassB has strong encapsulation
- ClassC is tightly coupled to ClassA
A: ClassB has weak encapsulation

Q: class Vehicle
{
public void drive()
{
System.out.print("reverse ");
}
}
class Car extends Vehicle
{
public void forward()
{
System.out.print("forward ");
}
public void drive()
{
System.out.print("neutral ");
}
}
public class PE58
{
public static void main(String[] args)
{
new PE58().go();
}
void go()
{
new Car().drive();
((Vehicle) new Car()).drive();
((Vehicle) new Car()).forward();
}
}

What is the output of this program?
- neutral neutral forward
- neutral reverse forward
- neutral neutral followed by an exception
- neutral reverse followed by an exception
- Compilation error
A: Compilation error

Q: public class Plant extends PE59
{
public static void main(String[] args)
{
new Plant().water();
}
void water()
{
water2(new PE59(), new Plant());
water2((Plant) new PE59(), new Plant());
}
void water2(PE59 t1, Plant r1)
{
Plant r2 = (Plant)t1;
PE59 t2 = (PE59)r1;
}
}
class PE59
{
}

What is the output of this program?
- No output
- Compilation error
- Exception
A: Exception

Q: public class Tenor extends PE60
{
public static String sing()
{
return "snow";
}
public static void main(String[] args)
{
Tenor t = new Tenor();
PE60 s = new Tenor();
System.out.println(t.sing() + " " + s.sing()); 9.   }
}
class PE60
{
public static String sing()
{
return "glow";
}
}

What is the output of this program?
- snow snow
- snow glow
- glow glow
- Compilaton error
- Exception
A: snow glow

Q: class PE61
{
static String s = " ";
protected PE61() { s += "alpha "; }
}
class SubAlpha extends PE61
{
private SubAlpha() { s += "sub "; }
}
public class SubSubAlpha extends PE61
{
private SubSubAlpha() { s += "subsub "; }
public static void main(String[] args)
{
new SubSubAlpha();
System.out.println(s);
}
}

What is the output of this program?
- subsub
- sub subsub
- alpha subsub
- alpha sub subsub
- Compilation error
- Exception error
A: alpha subsub

Q: class PE62
{
PE62()
{
System.out.print("b ");
}
PE62(String name)
{
this();
System.out.print("bn " + name);
}
}
public class House extends PE62
{
House()
{
System.out.print("h ");
}
House(String name)
{
this();
System.out.print("hn " + name);
}
public static void main(String[] args) { new House("x "); }
}

What is the output of this program?
- h hn x
- hn x h
- b h hn x
- b hn x h
- bn x h hn x
- b bn x h hn x
- bn x b h hn x
- Compilation error
A: b h hn x

Q: class Mammal
{
String name = "furry ";
String makeNoise() { return "generic noise"; }
}
class Zebra extends Mammal
{
String name = "stripes ";
String makeNoise() { return "bray"; }
}
public class PE63
{
public static void main(String[] args)
{
new PE63().go();
}
void go()
{
Mammal m = new Zebra();
System.out.println(m.name + m.makeNoise());
}
}

What is the output of this program?
- furry bray
- stripes bray
- furry generic noise
- stripes generic noise
- Compilation error
- Exception
A: furry bray

Q: There is a new online board game in which Floozels are a type of Jammers, Jammers can have Quizels, Quizels are a type of Klakker, and Floozels can have several Floozets.  Which of the following fragments represent this design?

(a)

import java.util.*;
interface Klakker { }
class Jammer { Set<Quizel> q; }
class Quizel implements Klakker { }
public class Floozel extends Jammer { List<Floozet> f; }
interface Floozet { }

(b)

import java.util.*;
class Klakker { Set<Quizel> q; }
class Quizel extends Klakker { }
class Jammer { List<Floozel> f; }
class Floozet extends Floozel { }
public class Floozel { Set<Klakker> k; }

(c)

import java.util.*;
interface Jammer extends Quizel { }
interface Klakker { }
interface Quizel extends Klakker { }
interface Floozel extends Jammer, Floozet { }
interface Floozet { }
- A
- B
- C
A: A

Q: class A { }
class B extends A { }
public class PE65
{
static String s = "-";
public static void main(String[] args)
{
A[] aa = new A[2];
B[] ba = new B[2];
screen(aa);
screen(ba);
screen(7);
System.out.println(s);
}
static void screen(A[]... a2) { s += "1"; }
static void screen(B[]... b1) { s += "2"; }
static void screen(B[] b1)    { s += "3"; }
static void screen(Object o)  { s += "4"; }
}

What is the output of this program?
- -124
- -134
- -424
- -434
- Compilation error
- Exception
A: -434

Q: class PE66
{
static String s = "-";
public static void main(String[] args)
{
new PE66().s1();
System.out.println(s);
}
void s1()
{
try
{
s2();
}
catch (Exception e)
{
s += "c";
}
}
void s2() throws Exception
{
s3(); s += "2";
s3(); s += "2b";
}
void s3() throws Exception
{
throw new Exception();
}
}

What is the output of this program?
- -
- -c
- -c2
- -2c
- -c22b
- -2c2b
- -2c2bc
- Compilation error
A: -c

Q: try { int x = Integer.parseInt("two"); }

Which could be used to create an appropriate catch block?
- ClassCastException
- IllegalStateException
- NumberFormatException
- ExceptionInInitializerError
- ArrayIndexOutOfBoundsException
A: NumberFormatException

Q: Which statement is incorrect?
- It is appropriate to use assertions to validate arguments to methods marked public.
- It is NOT appropriate to use assertions to validate command-line arguments.
- It is appropriate to use assertions to generate alerts when you reach code that should not be reachable.
- It is NOT appropriate for assertions to change a program’s state.
A: It is appropriate to use assertions to validate arguments to methods marked public.

Q: class PE69
{
public static void main(String[] args)
{
int[] x = {7,6,5,4,3,2,1};
// insert code here
System.out.print(y + " ");
}
}
}

When inserted where indicated, which statement causes a compilation error?
- for(int y : x) {
- for(x : int y) {
- for(int y=0, z=0; z<x.length; z++) { y = x[z];
- for(int y=0, int z=0; z<x.length; z++) { y = x[z];
- int y = 0; for(int z=0; z<x.length; z++) { y = x[z];
A: for(x : int y) {

Q: class PE70
{
static String s = "-";
public static void main(String[] args)
{
try
{
throw new Exception();
}
catch (Exception e)
{
try
{
try
{
throw new Exception();
}
catch (Exception ex)
{
s += "ic ";
}
throw new Exception();
}
catch (Exception x)
{
s += "mc ";
}
finally
{
s += "mf ";
}
}
finally
{
s += "of ";
}
System.out.println(s);
}
}

What is the output of this program?
- -ic of
- -mf of
- -mc mf
- -ic mf of
- -ic mc mf of
- -ic mc of mf
- Compilation error
A: -ic mc mf of

Q: class SubException extends Exception { }
class SubSubException extends SubException { }
public class PE71 { void doStuff() throws SubException { } }
class PE712 extends PE71 { void doStuff() throws SubSubException { } }
class PE713 extends PE71 { void doStuff() throws Exception { } }
class PE714 extends PE71 { void doStuff(int x) throws Exception { } }
class PE715 extends PE71 { void doStuff() { } }

What is the output of this program?
- Compilation succeeds
- Compilation error
A: Compilation error

Q: public class PE72
{
static int x = 7;
public static void main(String[] args)
{
String s = "";
for(int y = 0; y < 3; y++)
{
x++;
switch(x)
{
case 8: s += "8 ";
case 9: s += "9 ";
case 10: { s+= "10 "; break; }
default: s += "d ";
case 13: s+= "13 ";
}
}
System.out.println(s);
}
static { x++; }
}

What is the output of this program?
- 9 10 d
- 8 9 10 d
- 9 10 10 d
- 9 10 10 d 13
- 8 9 10 10 d 13
- 8 9 10 9 10 10 d 13
- Compilation error
A: 9 10 10 d 13

Q: class PE73 { }
public class Beyond extends PE73
{
static Integer i;
public static void main(String[] args)
{
int sw = (int)(Math.random() * 3);
switch(sw)
{
case 0:
{
for(int x = 10; x > 5; x++)
if(x > 10000000) x = 10;
break;
}
case 1:
{
int y = 7 * i; break;
}
case 2:
{
PE73 inf = new Beyond();
Beyond b = (Beyond)inf;
}
}
}
}

Which statement is correct?
- Compilation fails
- A ClassCastException might be thrown
- A StackOverflowError might be thrown
- A NullPointerException might be thrown
- An IllegalStateException might be thrown
- The program will always complete without exception
A: A NullPointerException might be thrown

Q: public class PE74
{
public static void main(String[] args)
{
int[] ia = {1,3,5,7,9};
for(int x : ia)
{
for(int j = 0; j < 3; j++)
{
if(x > 4 && x < 8) continue;
System.out.print(" " + x);
if(j == 1) break;
continue;
}
continue;
}
}
}

What is the output of this program?
- 1 3 9
- 5 5 7 7
- 1 3 3 9 9
- 1 1 3 3 9 9
- 1 1 1 3 3 3 9 9 9
- Compilation error
A: 1 3 9

Q: public class PE75
{
static String s = "";
public static void main(String[] args)
{
try
{
s += "1";
throw new Exception();
}
catch (Exception e)
{
s += "2";
}
finally
{
s += "3";
doStuff(); s += "4";
}
System.out.println(s);
}
static void doStuff()
{
int x = 0;
int y = 7/x;
}
}

What is the output of this program?
- 12
- 13
- 123
- 1234
- 123 followed by an exception
- 1234 followed by an exception
- Compilation error
- Exception
A: Exception

Q: public class PE76
{
public static void main(String[] args)
{
foreach:
for(int j=0; j<5; j++)
{
for(int k=0; k< 3; k++)
{
System.out.print(" " + j);
if(j==3 && k==1) break foreach;
if(j==0 || j==2) break;
}
}
}
}

What is the output of this program?
- 0 1 2 3
- 1 1 1 3 3
- 0 1 1 1 2 3 3
- 1 1 1 3 3 4 4 4
- 0 1 1 1 2 3 3 4 4 4
- Compilation error
A: 0 1 1 1 2 3 3

Q: public class PE77
{
public static void main(String[] args)
{
// insert code here
}
void go()
{
go();
}
}

And given the following three code fragments:

I.    new PE77().go();

II.   try
{
new PE77().go();
}
catch (Error e)
{
System.out.println("ouch");
}

III.  try
{
new PE77().go();
}
catch (Exception e)
{
System.out.println("ouch");
}

When fragments I - III are added, independently, where indicated, which statement is true?
- Some will not compile
- They will all compile
- All will complete normally
- None will complete normally
- Two of them will complete normally
A: They will all compile

Q: public class PE78
{
public static void main(String[] args)
{
int j = 7;
assert(++j > 7);
assert(++j > 8): "hi";
assert(j > 10): j=12;
assert(j==12): doStuff();
assert(j==12): new PE78();
}
static void doStuff() { }
}

What is the output of this program?
- Compilation succeeds
- Compilation error
A: Compilation error

Q: public class PE79
{
// insert code here
int x = 0;
System.out.println(7/x);
}
}

And given the following four code fragments:

I.    public static void main(String[] args) {

II.   public static void main(String[] args) throws Exception {

III.  public static void main(String[] args) throws IOException {

IV.   public static void main(String[] args) throws RuntimeException {

When fragments I - IV are added, independently, where indicated, which statement is true?
- All four will compile and execute without exception
- All four will compile and execute and throw an exception
- Some, but not all, will compile and execute without exception
- Some, but not all, will compile and execute and throw an exception
A: Some, but not all, will compile and execute and throw an exception

Q: class MyException extends Exception { }
class Tire
{
void doStuff() { }
}
public class PE80 extends Tire
{
public static void main(String[] args)
{
new PE80().doStuff();
}
// insert code here
System.out.println(7/0);
}
}

And given the following four code fragments:

I.    void doStuff() {

II.   void doStuff() throws MyException {

III.  void doStuff() throws RuntimeException {

IV.   void doStuff() throws ArithmeticException {

When fragments I - IV are added, independently, where indicated, which statement is true?
- None will compile
- Thyey will all compile
- Some, but not all, will compile
- None of those that compile will throw an exception at runtime
- Only some of those that compile will throw an exception at runtime
A: Some, but not all, will compile

Q: public static void main(String[] args)
{
// insert code here
for (int i = 0; i <= 10; i++)
{
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= 10; j++)
row.add(i * j);
table.add(row);
}
for (List<Integer> row : table)
System.out.println(row);
}

Which statement, added where indicated, makes the code compile?
- List<List<Integer>> table = new List<List<Integer>>();
- List<List<Integer>> table = new ArrayList<List<Integer>>();
- List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();
- List<List, Integer> table = new List<List, Integer>();
- List<List, Integer> table = new ArrayList<List, Integer>();
- List<List, Integer> table = new ArrayList<ArrayList, Integer>();
- None of the above
A: List<List<Integer>> table = new ArrayList<List<Integer>>();

Q: Which statement is true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden?
- If the equals() method returns true, the hashCode() comparison == might return false
- If the hashCode() comparison == returns true, the equals() method must return true
- If the hashCode() comparison == returns true, the equals() method might return true
- If the hashCode() comparison != returns true, the equals() method might return true
A: If the hashCode() comparison == returns true, the equals() method might return true

Q: public static void before()
{
Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}

Which statement is true?
- The before() method will print 1 2
- The before() method will print 1 2 3
- The before() method will print three numbers, but the order cannot be determined
- The before() method will not compile
- The before() method will throw an exception at runtime
A: The before() method will throw an exception at runtime

Q: import java.util.*;
class MapEQ
{
public static void main(String[] args)
{
Map<PE84, String> m = new HashMap<PE84, String>();
PE84 t1 = new PE84("Monday");
PE84 t2 = new PE84("Monday");
PE84 t3 = new PE84("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(m.size());
}
}
class PE84
{
String day;
PE84(String d) { day = d; }
public boolean equals(Object o)
{
return ((PE84)o).day == this.day;
}
// public int hashCode() { return 9; }
}

Which statement is correct?
- As the code stands it will not compile
- As the code stands the output will be 2
- As the code stands the output will be 3
- If the hashCode() method is uncommented the output will be 3
- If the hashCode() method is uncommented the code will not compile
A: As the code stands the output will be 3

Q: interface Hungry<E> { void munch(E x); }
interface Carnivore<E extends Animal> extends Hungry<E> {}
interface Herbivore<E extends Plant> extends Hungry<E> {}
abstract class Plant {}
class Grass extends Plant {}
abstract class Animal {}
class Sheep extends Animal implements Herbivore<Sheep>
{
public void munch(Sheep x) {}
}
class Wolf extends Animal implements Carnivore<Sheep>
{
public void munch(Sheep x) {}

Which of the following changes, implemented independetly, would allow this code to compile?

(a) Change the Carnivore interface to
interface Carnivore<E extends Plant> extends Hungry<E> {}

(b) Change the Herbivore interface to
interface Herbivore<E extends Animal> extends Hungry<E> {}

(c) Change the Sheep class to
class Sheep extends Animal implements Herbivore<Plant>
{

public void munch(Grass x) {}
}

(d) Change the Sheep class to
class Sheep extends Plant implements Carnivore<Wolf>
{
public void munch(Wolf x) {}
}

(e) Change the Wolf class to
class Wolf extends Animal implements Herbivore<Grass>
{
public void munch(Grass x) {}
}

(f) No changes are necessary
- A
- B
- C
- D
- E
- F
A: B

Q: Which class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not syncronized?
- java.util.HashSet
- java.util.LinkedHashSet
- java.util.List
- java.util.ArrayList
- java.util.Vector
- java.util.PriorityQueue
A: java.util.ArrayList

Q: public static <E extends Number> List<E> process(List<E> nums)

A programmer wants to call this method like this:

// insert declarations here
output = process(input);

Which declaration pair could be placed where indicated that allows the code to compile?

(a)  ArrayList<Integer> input = null;
ArrayList<Integer> output = null;

(b)  ArrayList<Integer> input = null;
List<Integer> output = null;

(c)  ArrayList<Integer> input = null;
List<Number> output = null;

(d)  List<Number> input = null;
ArrayList<Integer> output = null;

(e) None of the above
- A
- B
- C
- D
- E
A: B

Q: PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
System.out.print(pq.peek() + " ");
pq.offer("1");
pq.add("3");
pq.remove("1");
System.out.print(pq.poll() + " ");
if(pq.remove("2")) System.out.print(pq.poll() + " ");
System.out.println(pq.poll() + " " + pq.peek());

What is the output of this program?
- 2 2 3 3
- 2 2 3 4
- 4 3 3 4
- 2 2 3 3 3
- 4 3 3 3 3
- 2 2 3 3 4
- Compilation error
- Exception
A: 2 2 3 4

Q: import java.util.*;
public class Mixup
{
public static void main(String[] args)
{
Object o = new Object();
// insert code here
s.add("o");
s.add(o);
}
}

I)    Set s = new HashSet();
II)   TreeSet s = new TreeSet();
III   LinkedHashSet s = new LinkedHashSet();

When fragments I, II, or III are independently inserted where indicated, which statement is false?
- Fragment I compiles
- Fragment II compiles
- Fragment III compiles
- Fragment I executes without exception
- Fragment II executes without exception
- Fragment III executes without exception
A: Fragment II executes without exception

Q: import java.util.*;
class Turtle
{
int size;
public Turtle(int s) { size = s; }
public boolean equals(Object o)
{
return (this.size == ((Turtle)o).size);
}
// insert code here
}
public class TurtleTest
{
public static void main(String[] args)
{
LinkedHashSet<Turtle> t = new LinkedHashSet<Turtle>();
t.add(new Turtle(1));
t.add(new Turtle(2));
t.add(new Turtle(1));
System.out.println(t.size());
}
}

I)    public int hashCode() { return size/5; }
II)   // no hashCode method declared

When fragments I or II are independently inserted where indicated, which statement is true?
- If fragment I is inserted, the output is 2
- If fragment I is inserted, the output is 3
- If fragment II is inserted, the output is 2
- If fragment I is inserted, compilation fails
- If fragment II is inserted, compilation fails
A: If fragment I is inserted, the output is 2

Q: TreeSet<String> s = new TreeSet<String>();
TreeSet<String> subs = new TreeSet<String>();
s.add("a");
s.add("b");
s.add("c");
s.add("d");
s.add("e");
subs = (TreeSet)s.subSet("b", true, "d", true);
s.add("g");
s.pollFirst();
s.pollFirst();
s.add("c2");
System.out.println(s.size() +" "+ subs.size());

Which statement is true?
- The size of s is 4
- The size of s is 7
- The size of subs is 1
- The size of subs is 2
- The size of subs is 3
- The size of subs is 4
A: The size of subs is 3

Q: import java.util.*;
public class Magellan
{
public static void main(String[] args)
{
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("a", "apple");
myMap.put("d", "date");
myMap.put("f", "fig");
myMap.put("p", "pear");
System.out.println("1st after mango: " + // sop 1
myMap.higherKey("f"));
System.out.println("1st after mango: " + // sop 2
myMap.ceilingKey("f"));
System.out.println("1st after mango: " + // sop 3
myMap.floorKey("f"));
SortedMap<String, String> sub = new TreeMap<String, String>();
sub = myMap.tailMap("f");
System.out.println("1st after mango: " + // sop 4
sub.firstKey());
}
}

Which System.out.println statement will produce the following output?
1st after mango: p
- sop 1
- sop 2
- sop 3
- sop 4
- Compilation error
- Exception
A: sop 1

Q: class Business { }
class Hotel extends Business { }
class Inn extends Hotel { }
public class Travel
{
ArrayList<Hotel> go()
{
// insert code here
}
}

Which statement inserted independently where indicated will compile?
- return new ArrayList<Inn>();
- return new ArrayList<Hotel>();
- return new ArrayList<Object>();
- return new ArrayList<Business>();
A: return new ArrayList<Hotel>();

Q: class Dog { int size; Dog(int s) { size = s; } }
public class FirstGrade
{
public static void main(String[] args)
{
TreeSet<Integer> i = new TreeSet<Integer>();
TreeSet<Dog> d = new TreeSet<Dog>();
d.add(new Dog(1));
d.add(new Dog(2));
d.add(new Dog(1));
i.add(1);
i.add(2);

i.add(1);
System.out.println(d.size() + " " + i.size());
}
}

What is the output of this program?
- 1 2
- 2 2
- 2 3
- 3 2
- 3 3
- Compilation error
- Exception
A: Exception

Q: public class PE95
{
public static void main(String[] args)
{
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));
}
static class Othello implements Comparator<String>
{
public int compare(String a, String b) { return b.compareTo(a); }
}
}

Which statement is true?
- Compilation error
- The output will contain a 1
- The output will contain a 2
- The output will contain a –1
- The output will contain "key map marble pen"
- Exception
A: The output will contain a –1

Q: Which statement is true about a static nested class?
- You must have a reference to an instance of the enclosing class in order to instantiate it
- It does not have access to non-static members of the enclosing class
- Its variables and methods must be static
- It must extend the enclosing class
A: It does not have access to non-static members of the enclosing class

Q: class PE97
{
PE97(String s) { }
PE97() { }
}
class Bar extends PE97
{
Bar() { }
Bar(String s) {super(s);}
void zoo()
{
// insert code here
}
}

Which statement creates an anonymous inner class from within class Bar?
- PE97 f = new PE97(24) { };
- PE97 f = new PE97() {String s; };
- Bar f = new PE97(String s) { };
- PE97 f = new PE97.Bar(String s) { };
A: PE97 f = new PE97() {String s; };

Q: Which statement is true about a method-local inner class?
- It must be marked final
- It can be marked public
- It can be marked static
- It can access private members of the enclosing class
A: It can be marked static

Q: public class PE99
{
public static void main(String[] args)
{
Object o = new Object()
{
public boolean equals(Object obj)
{
return true;
}
}
System.out.println(o.equals("Fred"));
}
}

What is the output of this program?
- Exception
- true
- Fred
- Compilation error
A: Compilation error

Q: public class PE100
{
public static void main(String[] args)
{
class Horse
{
public String name;
public Horse(String s)
{
name = s;
}
}
Object obj = new Horse("Zippo");
System.out.println(obj.name);
}
}

What is the output of this program?
- Exception
- Zippo
- Compilation error
A: Compilation error

Q: public abstract class PE101
{
public int getNum() { return 45; }
public abstract class Bar
{
public int getNum() { return 38; }
}
public static void main(String[] args)
{
PE101 t = new PE101()
{
public int getNum() { return 22; }
};
PE101.Bar f = t.new Bar()
{
public int getNum() { return 57; }
};
System.out.println(f.getNum() + " " + t.getNum());
}
}

What is the output of this program?
- 57 22
- 45 38
- 45 57
- Compilation error
- Exception
A: 57 22

Q: public class PE102
{
public static void main(String[] args)
{
Cathedral c = new Cathedral();
// insert code here
s.go();
}
}
class Cathedral
{
class Sanctum
{
void go() { System.out.println("sacred"); }
}
}

Which statement, inserted independently where indicated, will produce output "sacred"?
- Sanctum s = c.new Sanctum();
- c.Sanctum s = c.new Sanctum();
- c.Sanctum s = Cathedral.new Sanctum();
- Cathedral.Sanctum s = c.new Sanctum();
- Cathedral.Sanctum s = Cathedral.new Sanctum();
A: Cathedral.Sanctum s = c.new Sanctum();

Q: class A
{
void m() { System.out.println("outer"); }
}
public class PE103
{
public static void main(String[] args)
{
new PE103().go();
}
void go()
{
new A().m();
class A { void m() { System.out.println("inner"); } }
}
class A
{
void m() { System.out.println("middle"); }
}
}

What is the output of this program?
- inner
- outer
- middle
- Compilatoin error
- Exception
A: middle

Q: public class PE104
{
class Engine
{
// insert code here
}
public static void main(String[] args)
{
new PE104().go();
}
void go() { new Engine(); }
void drive() { System.out.println("Go!"); }
}

Which statement, inserted independently where indicated, will produce output "Go!"?
- { PE104.drive(); }
- { this.drive(); }
- { PE104.this.drive(); }
- { this.PE104.this.drive(); }
- Engine() { PE104.drive(); }
- Engine() { this.drive(); }
A: { PE104.this.drive(); }

Q: public class PE105
{
class Manhattan
{
void doStuff() throws Exception { System.out.print("x "); }
}
class TimesSquare extends Manhattan
{
void doStuff() throws Exception { }
}
public static void main(String[] args) throws Exception
{
new PE105().go();
}
void go() throws Exception { new TimesSquare().doStuff(); }
}

What is the output of this program?
- x
- x x
- No output is produced
- Compilation error
- Exception
A: No output is produced

Q: public class PE106
{
private int size = 7;
private static int length = 3;
public static void main(String[] args)
{
new PE106().go();
}
void go()
{
int size = 5;
System.out.println(new Gazer().adder());
}
class Gazer
{
int adder() { return size * length; }
}
}

What is the output of this program?
- 15
- 21
- Compilation error
- Exception
A: 21

Q: public class PE107
{
public static void main(String[] args)
{
String[] sa = {"nickel", "button", "key", "lint"};
Sorter s = new Sorter();
for(String s2: sa) System.out.print(s2 + " ");
Arrays.sort(sa,s);
System.out.println();
for(String s2: sa) System.out.print(s2 + " ");
}
class Sorter implements Comparator<String>
{
public int compare(String a, String b)
{
return b.compareTo(a);
}
}
}

What is the output of this program?
- button key lint nickel
nickel lint key button
- nickel button key lint
button key lint nickel
- nickel button key lint
nickel button key lint
- nickel button key lint
nickel lint key button
- Compilation error
- Exception
A: Compilation error

Q: 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 may be used to create the target, so that the code compiles?
- public class MyRunnable extends Runnable{public void run(){}}
- public class MyRunnable extends Object{public void run(){}}
- public class MyRunnable implements Runnable{public void run(){}}
- public class MyRunnable implements Runnable{void run(){}}
- public class MyRunnable implements Runnable{public void start(){}}
A: public class MyRunnable implements Runnable{public void run(){}}

Q: class PE109 extends Thread
{
public static void main(String [] args)
{
PE109 t = new PE109();
Thread x = new Thread(t);
x.start();
}
public void run()
{
for(int i=0;i<3;++i)
{
System.out.print(i + "..");
}
}
}

What is the output of this program?
- 1..2..3..
- 0..1..2..3..
- 0..1..2..
- Compilation error
- Exception
A: 0..1..2..

Q: class PE110
{
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 output of this program?
- Each String in the array lines will output, with a 1-second pause between lines.
- Each String in the array lines will output, with no pause in between because this method is not executed in a Thread.
- Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.
- Each String in the lines array will print, with at least a one-second pause between lines.
- Compilation error
A: Compilation error

Q: Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class?
- public int read(){return a+b;}
public void set(int a, int b){this.a=a;this.b=b;}
- public synchronized int read(){return a+b;}
public synchronized void set(int a, int b){this.a=a;this.b=b;}
- public int read(){synchronized(a){return a+b;}}
public void set(int a, int b){synchronized(a){this.a=a;this.b=b;}
- public int read(){synchronized(a){return a+b;}}
public void set(int a, int b){synchronized(b){this.a=a;this.b=b;}}
- public synchronized(this) int read(){return a+b;}
public synchronized(this) void set(int a, int b){this.a=a;this.b=b;}
A: public synchronized int read(){return a+b;}
public synchronized void set(int a, int b){this.a=a;this.b=b;}

Q: public class WaitTest
{
public static void main(String [] args)
{
System.out.print("1 ");
synchronized(args)
{
System.out.print("2 ");
try
{
args.wait();
}
catch(InterruptedException e){}
}
System.out.print("3 ");
}
}

What is the output of this program?
- It fails to compile because the IllegalMonitorStateException of wait() is not dealt with.
- 1 2 3
- 1 3
- 1 2
- At runtime, it throws an IllegalMonitorStateException when trying to wait.
- It will fail to compile because it has to be synchronized on the this object.
A: 1 2

Q: 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?
- After object B is notified, or after two seconds
- After the lock on B is released, or after two seconds
- Two seconds after object B is notified
- Two seconds after lock B is released
A: After object B is notified, or after two seconds

Q: Which statement is true?
- The notifyAll() method must be called from a synchronized context
- To call wait(), an object must own the lock on the thread
- The notify() method is defined in class java.lang.Thread
- The notify() method causes a thread to immediately release its lock
- The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they're waiting on
A: The notifyAll() method must be called from a synchronized context

Q: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:

public class PE115
{
rivate StringBuilder contents = new StringBuilder();
public void log(String message)
{
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());
contents.append(message);
contents.append("\n");
}
public String getContents() { return contents.toString(); }
}

How do you insure that instances of this class can safely be used by multiple threads?
- This class is already thread-safe.
- Replacing StringBuilder with StringBuffer will make this class thread-safe.
- Synchronize the log() method only.
- Synchronize the getContents() method only.
- Synchronize both log() and getContents().
- This class cannot be made thread-safe.
A: Synchronize both log() and getContents().

Q: public static synchronized void main(String[] args)
throws InterruptedException
{
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}

What is the output of this program?
- It prints X and exits
- It prints X and never exits
- It prints XY and exits almost immeditately
- It prints XY with a 10-second delay between X and Y
- It prints XY with a 10000-second delay between X and Y
- Compilation error
- Exception
A: Exception

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

What is the output of this program?
- foo
- PE117 foo
- PE117 bar
- foo bar
- foo bar baz
- bar foo
- Compilation fails
- An exception is thrown at runtime
A: PE117 foo

Q: public class PE118
{
synchronized void a() { actBusy(); }
static synchronized void b() { actBusy(); }
static void actBusy()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {}
}
public static void main(String[] args)
{
final PE118 x = new PE118();
final PE118 y = new PE118();
Runnable runnable = new Runnable()
{
public void run()
{
int option = (int) (Math.random() * 4);
switch (option)
{
case 0: x.a(); break;
case 1: x.b(); break;
case 2: y.a(); break;
case 3: y.b(); break;
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}

Which of the following pairs of method invocations could NEVER be executing at the same time?
- x.a() in thread1, and x.b() in thread2
- x.a() in thread1, and y.a() in thread2
- x.a() in thread1, and y.b() in thread2
- x.b() in thread1, and x.a() in thread2
- x.b() in thread1, and y.a() in thread2
- x.b() in thread1, and y.b() in thread2
A: x.b() in thread1, and y.b() in thread2

Q: public class PE119
{
static Thread laurel, hardy;
public static void main(String[] args)
{
laurel = new Thread()
{
public void run()
{
System.out.println("A");
try
{
hardy.sleep(1000);
}
catch (Exception e)
{
System.out.println("B");
}
System.out.println("C");
}
};
hardy = new Thread()
{
public void run()
{
System.out.println("D");
try
{
laurel.wait();
}
catch (Exception e)
{
System.out.println("E");
}
System.out.println("F");
}
};
laurel.start();
hardy.start();
}
}

Which letter will eventually appear somewhere in the output?
- A
- B
- The answer cannot be reliably determined
- Compilation error
A: A

Q: public class Starter implements Runnable
{
void go(long id)
{
System.out.println(id);
}
public static void main(String[] args)
{
System.out.print(Thread.currentThread().getId() + " ");
// insert code here
}
public void run() { go(Thread.currentThread().getId()); }
}

And given the following five code fragments:

I)       new Starter().run();
II)      new Starter().start();
III)     new Thread(new Starter());
IV)    new Thread(new Starter()).run();
V)      new Thread(new Starter()).start();

When the five fragments are inserted independently, which statement is true?
- All five will compile
- Only one might produce the output 4 4
- Only one might produce the output 4 2
- Exactly two might produce the output 4 2
- Exactly three might produce the output 4 4
- Exactly three might produce the output 4 2
A: Only one might produce the output 4 2