Page 1 of 1

oracle java 6 certification exam mock questions

PostPosted: Wed Feb 22, 2012 4:49 pm
by tomrff
Question
1
Choose the option that can be inserted at line 2 below to make the code work correctly. (Choose one option)

/*1*/ String str = "April 19, 2005";
/*2*/
Choose one answer.
a. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str);
b. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str);
c. Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);
d. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str);
e. Date date = new DateFormat(DateFormat.LONG, Locale.US).format(str);
Explanation:
Choice C is the correct answer.

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner.

The DateFormat.parse(String source) method parses text from the beginning of the given string to produce a date. Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG, and FULL.

Option A, B are incorrect since there is no newInstance method in DateFormat
Option C is correct
Option D is incorrect since here parse method should be used to create a date object from string, format is used to format a string
Option E is incorrect since DateFormat constructor can't be called directly.

Check out the DateFormat API at
http://java.sun.com/j2se/1.4.2/docs/api ... ormat.html

Feedback to Author
Question
2
Choose the option that can be inserted below to extract the e-mail ids from the String "The e-mail ids are tom@abc.com and harry@xyz.com".


class Test
{
public static void main(String[] args)
{
String regex = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*";

String s = "The e-mail ids are tom@abc.com and harry@xyz.com";

//Insert here
}
Choose one answer.
a. Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
System.out.println("The e-mail id is: " + matcher.group());
}
b. Pattern pattern = Pattern.matcher(regex);
Matcher matcher = pattern.compile(s);
while (matcher.find()) {
System.out.println("The e-mail id is: " + matcher.group());
}
c. Pattern pattern = Pattern.matcher(regex);
Matcher matcher = pattern.compile(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
d. Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
e. Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.find());
}
Explanation :
Correct answer is choice A.

The compile method of the Pattern class compiles the given regular expression into a pattern, then the matcher method creates a matcher that will match the given input against this pattern. The find method scans the input sequence looking for the next sequence that matches the pattern. The group method returns the input subsequence matched by the previous match.
Based on above only option A is correct.

Now let us analyze how the given regular expression helps in extracting the e-mail ids. The (\w+) grouping looks for word characters, as denoted by the \w. The + indicates that one or more word characters must appear. This must be followed by a literal @ character. The (\w+\.) grouping is similar, but expects a period to follow in order to make a match. The period has been escaped using a backslash because the period character is itself a regex meta-character (a wildcard that matches any character).

The next (\w+) grouping is identical to the first grouping -- it looks for one or more word characters. Finally the expression (\.\w+)* asks to 'match a period followed by one or more word characters, and match that combination zero or more times'.


Feedback to Author
Question
3
Choose the option that will get compiled correctly.


Choose one answer.
a. String s=new String();
StringBuilder sb=new StringBuilder();
Formatter formatter=new Formatter(sb, Locale.US);
formatter.parse("PI=%12.10f",Math.PI);
b. String s=new String();
StringBuilder sb=new StringBuilder();
Formatter formatter=new Formatter(s, Locale.US);
formatter.format("PI=%12.10f",Math.PI);
c. String s=new String();
StringBuilder sb=new StringBuilder();
Formatter formatter=new Formatter(s, Locale.US);
formatter.format("PI=%12.10f",Math.PI);
d. String s=new String();
StringBuilder sb=new StringBuilder();
Formatter formatter=new Formatter(sb, Locale.US);
formatter.format("PI=%12.10f",Math.PI);
e. String s=new String();
StringBuilder sb=new StringBuilder();
Formatter formatter=new Formatter(Locale.US, s);
formatter.format("PI=%12.10f",Math.PI);
Explanation:
Correct answer is choice D.

The formatter class has a constructor which creates a new formatter with the specified destination and locale.
Formatter(Appendable a, Locale I)
The Appendable interface must be implemented by any class whose instances are intended to receive formatted output from a Formatter. This interface is implemented by StringBuilder and not by the String Class.
Based on above only option D is correct

Feedback to Author
Question
4
Choose the option that will get compiled correctly.

Choose one answer.
a. PrintWriter wr=new PrintWriter(new OutputStreamWriter(new FileWriter(fileName)));
b. BufferedWriter wr=new BufferedWriter(new PrintWriter(new FileWriter(fileName)));
c. PrintWriter wr=new PrintWriter(new FileWriter(new BufferedWriter(fileName)));
d. PrintWriter wr=new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
e. BufferedWriter wr=new BufferedWriter(new FileWriter(new PrintWriter(fileName)));
Explanation :
Correct answer is choice D.

The BufferedWriter is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. It is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as the FileWriter in this question statement. The BufferedWriter can then be passed a PrintWriter, which writes to the underlying stream using the println method.

More information here.
http://java.sun.com/j2se/1.5.0/docs/api ... riter.html

Feedback to Author
Question
5
Choose the option that will get compiled correctly.
Choose one answer.
a. Scanner scanner = new Scanner(new File("a.txt"));
scanner.useDelimiter("\n");
while (scanner.hasNext())
System.out.println(scanner.next());
b. Scanner scanner = new Scanner(new File("a.txt"));
scanner.setDelimiter("\n");
while (scanner.hasNextElement())
System.out.println(scanner.nextElement());
c. Scanner scanner = new Scanner(new File("a.txt"));
scanner.setDelimiter("\n");
while (scanner.hasNext())
System.out.println(scanner.next());
d. Scanner scanner = new Scanner(new File("a.txt"));
scanner.useDelimiter("\n");
while (scanner.hasNextElement())
System.out.println(scanner.nextElement());
Explanation:
Correct answer is choice A.

The java.util.Scanner class makes it easier to read and parse strings and primitive types using regular expressions. In this program, the Scanner breaks the contents of the File into tokens using a delimiter pattern. You can change the delimiter that is used to tokenize the input through the useDelimiter() method of the Scanner class. You can pass in a String or a java.util.regex.Pattern to the method. You can read the input one line at a time by using the newline character (\n) as a delimiter.

The hasNext() method in the Scanner class returns true if another token exists in the Scanner's input, which is the case until it reaches the end of the file. The next() method returns a String that represents the next token. So until it reaches the end of the file, TextScanner prints all String objects returned by next() on a separate line.

Want to know more ?

Refer to the following links:
http://java.sun.com/j2se/1.5.0/docs/api ... anner.html
http://java.sun.com/developer/JDCTechTi ... 201.html#1

Feedback to Author
Question
6
Choose the option that will give the following output.
Dog
is
man's
friend
Choose one answer.
a. public static void main (String[] args[])
{ Pattern p=Pattern.compile("\\s");
String[] words=p.split("Dog5is6man's78friend");
for ( String word : words)
System.out.println (word);
}
b. public static void main (String[] args[])
{ Pattern p=Pattern.compile("\\d");
String[] words=p.split("Dog5is6man's78friend");
for ( String word : words)
System.out.println (word);
}
c. public static void main (String[] args[])
{ Pattern p=Pattern.compile("\\d");
List words=p.split("Dog5is6man's78friend");
for ( String word : words)
System.out.println (word);
}
d. public static void main (String[] args[])
{ Pattern p=Pattern.compile("\\d");
String[] words=p.parse("Dog5is6man's78friend");
for ( String word : words)
System.out.println (word);
}
Explanation:
Correct answer is choice B.

The split method is defined by both Pattern and String classes. It splits the given input sequence around matches of a delimiter pattern.

public String[] split(String regex)

In using a regular expression as a delimiter, the split() method basically starts at the start of the string and finds the first occurrence of the regular expression. The regular expression "\\d" will find a match with a numeric digit. So the tokens returned by p.split ("Dog5is6man's78friend") would be "Dog", "is", "man’s", "friend".

Want to know more? Please refer to
http://download.oracle.com/javase/1.4.2 ... ttern.html


Feedback to Author
Question
7
Which of the following methods of the Pattern class have equivalent methods in the String class?
Select two choices.
Choose at least one answer.
a. split
b. matches
c. compile
d. group
Choices A and B are the correct answers.

Regular expression support has also been introduced in the java.lang.String class through several methods that mimic the behavior of java.util.regex.Pattern.
public boolean matches(String regex): Tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).
public String[] split(String regex, int limit): Splits this string around matches of the given regular expression. An invocation of this method of the form str.split(regex, n) yields the same result as the expression Pattern.compile(regex).split(str, n).
public String[] split(String regex): Splits this string around matches of the given regular expression. This method works the same as if you invoked the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are not included in the resulting array.
Want to know more? Check out
http://docs.oracle.com/javase/6/docs/ap ... ttern.html
http://docs.oracle.com/javase/1.5.0/doc ... tring.html

Feedback to Author
Question
8
Which of the following statements will compile without errors and print "5 + 6 = 11" when inserted at line 6 independently?

class Test
{
public static void main(String[] args)
{
int x = 5;
int y = 6;
int sum = x + y;
// line 6
}
}
Choose one answer.
a. System.out.format("%d + %d = %d\n", x, y, sum);
b. System.out.printf("%d + %d = %d\n", x, y, sum);
c. System.out.println(x + " + " + y + " = " + sum);
d. All of the above
Choice D is the correct answer.

Starting with Java 5, you can use System.out.printf() to send formatted numerical output to the console. It uses a java.util.Formatter object internally.

printf (String format, Object... args)

The format argument is a String object in which you embed specifier substrings that indicate how the arguments should be formatted in the output.

You can get more information about the printf method at http://java.sun.com/j2se/5.0/docs/api/j ... tream.html

Feedback to Author
Question
9
In the class Prop, how do you read the value of the system property 'FOO' set using the command 'java -DFOO=bar Prop FOO'? Select two choices.
Choose at least one answer.
a. System.getProperty("FOO");
b. System.property("FOO");
c. System.getProperties().get("FOO");
d. System.getPropertyValue("FOO");
e. System.findProperty("FOO");
Choices A and C are the correct answers.

You can read the value of a system property that has been set using the -D command-line switch in two ways.

public static String getProperty(String key)

This method returns the property value corresponding to the key passed.

public static Properties getProperties()

This method returns a Properties object containing all the system properties.

Then we can call the get(String) method on the Properties object to get a particular property value.

Note that the difference between the two methods is that the former one returns a String object while the later one returns an Object that has to be cast to String before use as the Properties class is a subclass of the Hashtable class.

For more information, refer to
http://docs.oracle.com/javase/tutorial/ ... sprop.html

Feedback to Author
Question
10
Given the following code :

File f = new File("myfile.txt");

What method will cause the file "myfile.txt" to be created in the underlying operating system?
Choose one answer.
a. f.write();
b. f.close();
c. f.flush();
d. None of the above
Choice D is the correct answer.

The File class mainly describes a file that might exist. To actually create it in the underlying file system, you need to pass the instance of the File class to an instance of one of the OutputStream or Writer classes. For example,

File f = new File("test.txt");
FileOutputStream fos = new FileOutputStream(f);

Read about the File class at
http://java.sun.com/j2se/1.5/docs/api/java/io/File.html

Feedback to Author
Question
11
In a thread, the wait() method must be called within which of the following?
Choose one answer.
a. A while loop
b. The run() method
c. synchronized code
d. The constructor
e. It doesn't matter where the wait()method is called from
Choice C is the correct answer.

The wait() method is defined in the Object class. The wait() method can only be called from within synchronized code, also it should be invoked only by the thread which currently owns the lock of the object on which wait() is invoked. The thread releases the lock and goes into the waiting state when this method is invoked.

Feedback to Author
Question
12
What will be the output when compiling and running the following code?

public class MyThread implements Runnable
{
String myString = "Yes ";
public void run()
{
this.myString = "No ";
}
public static void main(String[] args)
{
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}
Choose one answer.
a. Compilation error.
b. Prints: Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on.
c. Prints: No No No No No No No No No No and so on.
d. Prints: Yes No Yes No Yes No Yes No Yes No and so on.
e. The output cannot be determined.
Choice E is the correct answer.

Please note that there will not be any compilation error when the above code is compiled. Also note that calling the start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be scheduled for execution.

Depending on the operating system and on the other running threads, the thread on which start() is called will get executed.

In the above case, it is not guaranteed that the thread will be executed (i.e., that its run() method will be called), always before the "for" loop is executed. Thus the output cannot be determined.


Feedback to Author
Question
13
What will happen when you attempt to compile and run the following code?

public class Test
{
int i = 0;

public static void main(String[] argv)
{
Test t = new Test();
t.myMethod();
}

public void myMethod()
{
while(true)
{
try
{
wait();
}
catch (InterruptedException e) { }
i++;
}
}
}
Choose one answer.
a. Compile-time error, no matching notify method
b. Compiles and runs in an infinite loop
c. Compiles and runs without producing any output
d. IllegalMonitorStateException is thrown
Choice D is the correct answer.

The wait()/notify() methods can only be used within a code segment that is synchronized. Only a thread which owns the lock of the object can invoke these methods. In this case, the calling code is not synchronized and will thus cause an IllegalMonitorStateException at runtime. Since the code compiles fine, choice A is incorrect.

Since an exception is thrown, choices B and C are incorrect.

Check out the API for more about the wait and notify methods http://java.sun.com/j2se/1.5.0/docs/api ... bject.html

Feedback to Author
Question
14
What will happen when you attempt to compile and run the following code?

1. public class RecurThread extends Thread
2. {
3. public void run()
4. {
5. System.out.println("Java Threads");
6. start();
7. }
8.
9. public static void main(String[] args)
10. {
11. RecurThread t1 = new RecurThread();
12. t1.start();
13. }
14. }
Choose one answer.
a. It will repetitively print - Java Threads.
b. The code will not compile.
c. It will throw IllegalThreadStateException at runtime.
d. It will throw StackOverflowError at runtime.
Choice C is the correct answer.

The code will compile without any error, but it will throw an IllegalThreadStateException at runtime. At line 12, the t1.start() invocation schedules the thread for execution.

When the run() method of this thread is executed, the statement at line 5 prints "Java Threads". But at line 6, the start() invocation is encountered, since the thread has been already started (at line 12). This invocation results in an IllegalThreadStateException being thrown at runtime. Thus, the invocation at line 6 effectively becomes the second invocation after line 12 to start the same thread. It does not become a recursive call, as it might seem apparently.

It is important to understand that you can invoke the start() method only once for each thread, invoking it again results in an IllegalThreadStateException being thrown at runtime.

Want to know more? The following article discusses important concepts about multithreading - http://www.developerlife.com/lessons/th ... efault.htm

Feedback to Author
Question
15
What will be the result of compiling and running the following program?

class TestThread extends Thread
{
private int i;

public void run()
{
i++;
}

public static void main(String[] args)
{
TestThread a = new TestThread();
a.run();
System.out.print(a.i);
a.start();
System.out.print(a.i);
}
}
Choose one answer.
a. Compiler error
b. IllegalThreadStateException is thrown
c. Prints "11"
d. Prints "12"
e. Prints "00"
f. Prints "01"
g. Prints "11" or "12"
h. Prints "00" or "01"
Choice G is the correct answer.

Here, first the run() method of the object refered to by a is directly invoked. When the run() method of a Thread is invoked instead of the start() method, it is executed by the same thread as a conventional method. So it increments i to 1, now the output is 1. After this, the invocation of the start() method schedules a new thread of execution.

Now it is impossible to predict whether the new thread will run first or the second print statement will be executed by the main thread first. So the result of the second print statement can be 1 or 2 depending on the scheduling of the 2 threads.

Refer to http://java.sun.com/j2se/1.4.2/docs/api ... hread.html

Feedback to Author
Question
16
What will happen when you attempt to compile and run the following code?

1. public class ThreadDemo
2. {
3. private int count = 1;
4.
5. public synchronized void doSomething()
6. {
7. for(int i=0; i < 10; i++)
8. System.out.println(count++);
9. }
10.
11. public static void main(String[] args)
12. {
13. ThreadDemo demo = new ThreadDemo();
14. Thread a1 = new A(demo);
15. Thread a2 = new A(demo);
16. a1.start();
17. a2.start();
18. }
19. }
20.
21. class A extends Thread
22. {
23. ThreadDemo demo;
24. public A(ThreadDemo td)
25. {
26. demo = td;
27. }
28. public void run()
29. {
30. demo.doSomething();
31. }
32. }
Choose one answer.
a. It will print the numbers 0 to 19 sequentially.
b. It will print the numbers 1 to 20 sequentially.
c. It will print the numbers 1 to 20, but the order cannot be determined.
d. It will print the numbers 0 to 19, but the order cannot be determined.
e. The code will not compile.
Choice B is the correct answer.

The code will compile without any error and it will print the numbers 1 to 20 sequentially.

The doSomething() method is a synchronized method, hence when one thread is executing this method; the other threads must wait to obtain the lock of this object. When two thread objects a1 and a2 are created, and their start() methods are invoked, any one of these two threads will obtain the lock on the ThreadDemo instance, and its run() method will invoke the doSomething() method, printing values 1 to 10 (note that count is 1 initially). Once the first thread completes its execution, the second thread will start executing, starting from 11 (since value of the variable 'count' is now 11). The other thread will print values from 11 to 20.

Note that the doSomething() method prints the value of the variable 'count', which starts from 1; and not the local variable 'i', which starts from 0.

Want to know more? The following article discusses important concepts about multithreading - http://www.developerlife.com/lessons/th ... efault.htm

Feedback to Author
Question
17
What will be the result of compiling and running the following program code?

class TestThread extends Thread
{
public void restart()
{
startMe();
}

public static void startMe()
{
synchronized(TestThread.class)
{
TestThread.class.notifyAll();
System.out.println("Trying to Notify");
}
}

public void run()
{
try
{
synchronized(this)
{
wait();
System.out.println("Notified");
}
}
catch(InterruptedException e) {}
}

public static void main(String[] args)
{
TestThread t1 = new TestThread();
t1.start();
t1.restart();
}
}
Choose one answer.
a. "Trying to Notify" is printed followed by "Notified"
b. Only "Trying to Notify" is printed
c. No output
d. Compiler error
e. Throws an exception at runtime
Choice B is the correct answer.

Here, we first start the thread t1, which locks the object t1 and goes into the waiting state. The main thread then invokes the restart() method on t1, which invokes the static method startMe(). The startMe()method gets the lock on the class object TestThread.class, then it calls notifyAll().

Here note that the lock on object t1 is different from the lock on the class TestThread. Both are independent of each other. So this notifyAll() cannot bring the waiting thread t1 out of the waiting state. So it keeps waiting indefinitely. So the output is just "Trying to notify".


Feedback to Author
Question
18
Choose the option that will give the following output.
Book
Choose one answer.
a. enum Grade{A ,B, C, D};
public class EnumTest{
public static void main(String[] args){
Grade grade= Grade.A;
switch(grade){
case A: System.out.println(grade); break;
default : System.out.println("Default"); } } }
b. class Grade{A {public String toString(){return "Book";}},B, C, D};
public class EnumTest{
public static void main(String[] args){
Grade grade= Grade.A;
switch(grade){
case A: System.out.rintln(grade); break;
default : System.out.println("Default"); } } }
c. enum Grade{A {public String toString(){return "Book";}},B, C, D};
public class EnumTest{
public static void main(String[] args){
Grade grade= Grade.A;
switch(grade){
case A: System.out.println(grade); break;
default : System.out.println("Default"); } } }
d. enum Grade{A {public String toString(){return "Book";}},B, C, D};
public class EnumTest{
public static void main(String[] args){
Grade grade= Grade.A;
switch(grade){
case Grade.A: System.out.println(grade); break;
default : System.out.println("Default"); } } }
Explanation:
Correct answer is choice C.

Enumerated types are declared using the enum keyword.

Here Grade is an enumerated type and A, B, and C are the values for that type. You can add methods to an Enum type just as you would add methods to a Java class. The toString() method on an enumerated type returns the name of the value.

In this case, the name given for the value A is "Book". The switch statement now supports the use of enum values. You must not prefix each enumerated type with the enum class name, in the case statement. So it is 'case A' and not 'case Grade.A'. Want to know more about enums?

Check out :
http://java.sun.com/docs/books/jls/thir ... s.html#8.9


Feedback to Author
Question
19
Choose the option that provides correct import statements for the following code:

public class Test
{public static void main(String[] args){
for(String s:args)
out.println(s);
}}
Choose at least one answer.
a. static import java.lang.System.out;
b. static import java.lang.System.*;
c. import static java.lang.System;
d. import static java.lang.System.out;
e. import static java.lang.System.*;
Explanation:
Correct answer are choice D and E.

To be able to use the System.out.println by simply mentioning out.println, the static out variable in the System class needs to be imported using static imports. However, the println method cannot be imported this way, since it is not static. Also, the System class cannot be imported by static import.

To know more about static imports, refer to
http://java.sun.com/docs/books/jls/thir ... html#7.5.3

Feedback to Author
Question
20
Which of the following statements about StringBuilder are true? Select two choices.
Choose at least one answer.
a. It has inherent thread protection.
b. It is faster than StringBuffer.
c. It defines the append and insert methods.
d. It is immutable.
Choices B and C are the correct answers.

StringBuilder represents a mutable sequence of characters. Even though it is similar to StringBuffer in most aspects, they both differ on the thread protection aspect.

StringBuilder instances are not safe for use by multiple threads, while StringBuffer instances have inherent thread protection. This makes StringBuilder faster than StringBuffer. So choice A is incorrect while choice B is correct.

Both StringBuilder and StringBuffer classes define the append and insert methods, so choice C is also correct.

Since StringBuilder is mutable, choice D is incorrect.
For more information, you may refer to http://java.sun.com/j2se/1.5.0/docs/api ... ilder.html

Feedback to Author
Question
21
What is the result of compiling and running the following program?

class First
{
public Object method1()
{
System.out.println("Calling super class method");
return new String("Base");
}
}

class Second extends First
{
public String method1()
{
System.out.println("Calling sub class method");
return new String("Derived");
}
}

public class CovariantTest2
{
public static void main(String[] args)
{
First o = new Second();
String s=o.method1();
System.out.println(s);
}
}
Choose one answer.
a. Does not compile because the return type must be the same for the overriding method
b. Compiles but throws runtime exception
c. Prints "Base"
d. Prints "Derived"
e. None of these
Choice E is the correct answer.

This program does not compile, the reason is that the object reference used to invoke the method is of the super class type, so the return type must match the return type declared by the super class version of the method. Here the super class version declares Object as the return type, so you need to cast the result to the String type, when the method is invoked.

Choice A is incorrect because the covariant return types feature in Java allows a method in a subclass to return an object whose type is a subclass of the type returned by the method with the same signature in the super class.

Choices B, C, and D are incorrect since compilation fails, as explained above.

For more information, refer to http://java.sun.com/docs/books/jls/thir ... html#8.4.5

Feedback to Author
Question
22
What is the result of compiling and running the following program?

class First
{
public Object method1()
{
return new String("Base");
}
}

class Second extends First
{
public String method1()
{
return new String("Derived");
}
}

public class CovariantTest2
{
public static void main(String[] args)
{
First o = new Second();
String s=(String)o.method1();
System.out.println(s);
}
}
Choose one answer.
a. Prints "Base"
b. Prints "Derived"
c. Does not compile
d. Throws exception at runtime
Choice B is the correct answer.

The program compiles fine and prints "Derived" when run. Though the object reference used for invoking the method is of super class type, the actual object is of type subclass. So the method called is the one declared in the subclass, which prints "Derived". There are no compilation or casting errors, because it is a valid way of overriding using covariant return types. So choices C and D are incorrect.

Re: oracle java 6 certification exam mock questions

PostPosted: Wed Feb 22, 2012 4:51 pm
by tomrff
Feedback to Author
Question
23
Which of the following choices is the correct set of methods for getting and setting the value of a boolean property 'done' according to Java Bean naming standards? Select two choices.
Choose at least one answer.
a. public void setDone(boolean done)
public boolean getDone()
b. public void setDone(boolean done)
public boolean isDone()
c. public void setdone(boolean done)
public boolean getdone()
d. public void setdone(boolean done)
public boolean isdone()
e. public void getDone(boolean done)
public boolean setDone()
Choices A and B are the correct answers.

According to the JavaBean naming standards, if the property name is 'x' and the type is Type, the accessor method is of the form:
public Type getX()
and the mutator method is of the form:
public void setX(Type newValue)

So choice A is correct.

For boolean properties, the accessor method can have the prefix 'is' or 'get'. So the following form is also allowed.
public boolean isX()
public void setX(boolean newValue)

So choice E is incorrect, while choice B is correct.

Please note that the starting letter of the property name is capitalized in the accessor and mutator methods. So choices C and D also incorrect.

Feedback to Author
Question
24
What will be the result of compiling and executing the following code?

public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = x / 0;
if (x >= 100) y = x * 0;
System.out.println("The value of y is: " + y);
}
Choose one answer.
a. Compiler Error
b. Prints "The value of y is: 0"
c. Throws ArithmeticException
d. None of these
Choice A is the correct answer.

The code will not compile raising an error that the local variable y might not have been initialized. Unlike member variables, local variables are not automatically initialized to the default values for their declared type. The compiler reports an error if you attempt to use a local variable which has not been initialized under every circumstances. Since the code does not compile, all the other choices are automatically incorrect.

For more information, refer to http://java.sun.com/docs/books/jls/thir ... tml#4.12.5

Feedback to Author
Question
25
What will happen when the following code is compiled and run?

1. public class MyClass
2. {
3. int maxElements;
4. void MyClass()
5. {
6. maxElements = 100;
7. System.out.println(maxElements);
8. }
9. public MyClass(int i)
10. {
11. maxElements = i;
12. System.out.println(maxElements);
13. }
14. public static void main(String[] args)
15. {
16. MyClass a = new MyClass();
17. MyClass b = new MyClass(999);
18. }
19. }
Choose one answer.
a. Prints 100 followed by 999 on different lines
b. Prints 999 followed by 100 on different lines
c. Compilation error at line 4
d. Compilation error at line 16
Choice D is the correct answer.

Upon instantiation of MyClass on line 16, the compiler looks for a paramaterless constructor. As there is an overloaded constructor defined, the default constructor (with no arguments) will not be provided by the compiler. Since there is no matching constructor, the code does not compile here.

void MyClass() is a normal method and not a constructor since constructors do not have a return value. Since it is a legal method definition, there are no compiler errors at line 4. So choice C is incorrect.

Choices A and B are incorrect since the code does not compile.

To learn about constructors, refer to http://java.sun.com/docs/books/tutorial ... ctors.html

Feedback to Author
Question
26
What is the result of compiling and running the following program? (Assume that the command line arguments 0, 1, and 2 are passed to it)

class VarArgTest
{
public static void f(String... a)
{
for(String i : a)
System.out.print("A"+i);
}
public static void f(String[] a)
{
for(String i : a)
System.out.print("B"+i);
}
public static void main(String[] args)
{
f(args);
}
}
Choose one answer.
a. Compiler Error
b. Exception at runtime
c. Prints "A0A1A2"
d. Prints "B0B1B2"
e. None of these
Choice A is the correct answer.

The code does not compile because the method call made matches with both the methods in the class. Variable arguments (varargs) allow you to specify that a method can take multiple arguments of the same type and don't require that the number of arguments be predetermined.

A method can have at most one parameter that is a vararg, it must be the last parameter taken by the method, and it is denoted by the object type, a set of ellipses ( ... ), and the name of the variable.

When you specify a variable-length argument list, it is read as "create an array of type <type of varargs>". So the two methods in this class are equivalent, which causes ambiguity for the compiler. Since the program does not compile, the other choices are automatically incorrect.

Refer to http://java.sun.com/j2se/1.5.0/docs/gui ... rargs.html for more on how to use varargs.

Feedback to Author
Question
27
Choose the matching class definitions for following:
1. Subclass of IllegalArgumentException
2. Thrown when an assertion fails
3. Thrown when an application recurses too deeply
4. Thrown when an unexpected exception has occurred in a static initializer
Choose one answer.
a. 1.) NumberFormatException
2.) AssertionException
3.) StackOverflowError
4.) ExceptionInInitializerError
b. 1.) NumberFormatException
2.) AssertionError
3.) StackOverflowError
4.) ExceptionInInitializerError
c. 1.) NumberFormatException
2.) AssertionError
3.) RecursionError
4.) StaticInitializerError
d. 1.) NullPointerException
2.) AssertionError
3.) StackOverflowError
4.) StaticInitializerError
e. 1.) NullPointerException
2.) AssertionError
3.) StackOverflowError
4.) ExceptionInInitializerError
ANSWER: B

Explanation:
NumberFormatException is thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. It is a subclass of IllegalArgumentException.

AssertionError is thrown to indicate that an assertion has failed. StackOverflowError is thrown when a stack overflow occurs because an application recurses too deeply.

An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

Feedback to Author
Question
28
What is the output when following code is run.

class Test
{
void f()
{
throw new RuntimeException();
}
public static void main (String[ ] args) throws Exception
{
Test t=new Test();
try
{
t.f();
}
catch (Throwable e)
{
try
{
throw new Exception();
}
catch(Exception ex)
{
System.out.print("catch1");
throw ex;
}
finally
{
System.out.print("finally1");
}
}
finally
{
System.out.print("finally2");
}
}
}
Choose one answer.
a. Compilation error.
b. "catch1finally1finally2" followed by Exception.
c. "catch1finally1finally2".
d. "catch1" followed by Exception.
e. "catch1".
f. "catch1finally1".
ANSWER: B

Explanation:
The code demonstrates the use of nested try/catch blocks for exception handling. The method f() throws RuntimeException, which is caught by the catch block with a Throwable argument. This is possible because RuntimeException is a subclass of Exception which inherits from Throwable.

Within the catch block, there is a nested try block. Here the code prints "catch1", then rethrows the exception, which is again caught by its corresponding catch. From the catch block, the exception is rethrown again.

Before the exception propagates outside, the control moves to the finally block, where "finally1" is printed. Now the control reaches the enclosing finally block producing the output "finally2".

Want to know more about exceptions?

Check out
http://java.sun.com/docs/books/jls/thir ... tions.html
http://java.sun.com/docs/books/tutorial ... dling.html

Feedback to Author
Question
29
Which of the following choices is the last line of output, when the code below is executed?

public class Test
{
public static void main(String[] args)
{
int counter = 0;
outer: for(int i = 0; i < 4; ++i)
middle: for(int j = 0; j < 4; ++j)
inner: for(int k = 0; k < 4; ++k)
{
System.out.println("Hello - " + ++counter);
if((k % 4) == 0) break outer;
}
}
}
Choose one answer.
a. Hello - 1
b. Hello - 4
c. Hello - 0
d. None of the above
Choice A is the correct answer.

Since 0 mod 4 is 0, the inner loop is executed only once and then the break statement will be called, which completes the main method, and thus, the final line of output would be Hello - 1.

Want to know more about the for and break statements?

Check out the following links
http://java.sun.com/docs/books/jls/thir ... ml#14.14.1
http://java.sun.com/docs/books/jls/thir ... html#14.15

Feedback to Author
Question
30
What will be the result of executing the following code?

public static void main(String[] args)
{
char digit = 'a';
for (int i = 0; i < 10; i++)
{
switch (digit)
{
case 'x' :
{
int j = 0;
System.out.println(j);
}
default :
{
int j = 100;
System.out.println(j);
}
}
}
int i = j;
System.out.println(i);
}
Choose one answer.
a. 100 will be printed 11 times.
b. 100 will be printed 10 times and then there will be a runtime exception.
c. The code will not compile because the variable i cannot be declared twice within the main() method.
d. The code will not compile because the variable j cannot be declared twice within the switch statement.
e. None of these.
Choice E is the correct answer.

The code will not compile. There is no problem with the declaration of another variable i as both variables are in disjoint blocks (the first one is inside the for loop and its scope is limited to the for loop, whereas the second is outside the for loop) and, therefore, in different scopes. The problem is with the variable j. The two declarations of the variable j are perfectly valid as they are in disjoint blocks and, therefore, different scopes. The error is that both declarations of j are not available outside the case or default statements, whereas we are trying to assign it to the variable i. Therefore, the compiler complains and reports that the variable j cannot be found.

You can read more about the switch statement at http://java.sun.com/docs/books/jls/thir ... html#14.11

Feedback to Author
Question
31
What will be the result of compiling and running the following code? Assume that assertions are enabled at compile time as well as at runtime.

class Test
{
String f(int i)
{
switch (i)
{
case 0: return "A";
case 1: return "B";
case 2: return "C";
default: assert false;
}
}
public static void main(String[] args)
{
Test t = new Test();
for (int i = 0; i < 4; i++)
{
System.out.print(t.f(i));
}
}
}
Choose one answer.
a. Prints "ABC" and throws AssertionError
b. Prints "ABC" and throws AssertionException
c. Prints "ABC" and exits without any error
d. Compilation error
e. None of the above
Choice D is the correct answer.

This code does not compile because if the method containing the switch statement is declared with a non void return type and if no return statement appears after the switch statement, then each case of the switch must have a return statement or a throw statement. Here there is no return statement after the switch statement, so all the cases should have had a return or throw statement.

The default case has no return statement here, so the compiler will complain because assertions might not always be enabled. Here, instead of assert false, you can use throw AssertionError which will be executed even if assertions are disabled.

To know more about the assert statement, refer to http://java.sun.com/docs/books/jls/thir ... html#14.10

Feedback to Author
Question
32
What is the result of compiling and running the following code?

class Test
{
public static void main(String[] args)
{
int i=0;
try
{
for ( ; true ; i++ ) //1
{
if( i/i++ > 0)
break; // 2
}
}
catch(RuntimeException e)
{
System.out.println("RuntimeException");
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException");
}
catch(Exception e)
{
System.out.println("Exception");
}
finally
{
System.out.println("finally");
}
}
}
Choose one answer.
a. Compiles and runs, no exceptions are thrown. Prints "finally"
b. Compiler error at line 1
c. Compiler error at line 2
d. Compiles and runs, prints "Arithmetic Exception" and "finally"
e. Compiles and runs, prints "RuntimeException", "ArithmeticException", and "finally"
f. Compiles and runs, prints "RuntimeException" and "finally"
g. Compiles and runs, prints "Exception" and "finally"
h. None of the above
Choice H is the correct answer.

The program does not compile, but not because of errors in lines 1 and 2. Thus, choices B and C are incorrect.

ArithmeticException is the subclass of RuntimeException. Notice that the catch clause for RuntimeException is above that of ArithmeticException. It means that if ArithmeticException occurs, it will be caught by the first catch itself and control will never reach the second catch. Compiler sees this and complains that ArithmeticException has already been handled once, and that it cannot be handled again.

The rule to understand here is that the more specific exceptions should always be handled first. Here ArithmeticException is more specific than RuntimeException, so its catch clause should come first. Thus, choice H is correct while the remaining choices are incorrect.

Learn more about exceptions at http://java.sun.com/docs/books/jls/thir ... .html#11.5"

Feedback to Author
Question
33
What will be the result of attempting to compile and run the following program?
class Test
{
void f()
{
throw new RuntimeException();
}
public static void main (String[] args) throws Exception
{
Test t=new Test();
try
{
t.f();
}
catch (Throwable e)
{
try
{
throw (Exception)e;
}
catch(Exception ex)
{
System.out.print("catch1 "); return;
}
finally
{
System.out.print("finally1 "); return;
}
}
finally
{
System.out.print("finally2 ");
}
}
}
Choose one answer.
a. Compiler error
b. Prints "catch1 finally1"
c. Prints "catch1 finally1 finally2"
d. Prints "finally2"
e. None of the above
Choice C is the correct answer.

There are no errors in this program. It has two try/catch/finally blocks, one is nested inside the other. If the Throwable object had not been cast to the Exception type, the program wouldn't have compiled because the inner catch block only handles Exception and the main method also does not declare to throw Throwable.

Now when the program runs, the control moves to the main catch block where it is thrown again and handled by the inner catch block. Then the inner finally block is executed, followed by the outer one. So the output is "catch1 finally1 finally2". Note that even though there is a return statement in the catch block, the code inside the inally block will still be executed.

Feedback to Author
Question
34
What will appear in the standard output if tryThis() throws an IOException at runtime?

1. try
2. {
3. tryThis();
4. return;
5. }
6. catch(IOException x1)
7. {
8. System.out.println("exception 1");
9. return;
10. }
11. catch(Exception x2)
12. {
13. System.out.println("exception 2");
14. return;
15. }
16. finally
17. {
18. System.out.println("finally");
19. }
Choose one answer.
a. "exception 1" followed by "finally"
b. "exception 2" followed by "finally"
c. "exception 1"
d. "exception 2"
Choice A is the correct answer.

Regardless of whether or not an exception occurred, or whether or not it was handled, execution proceeds next to the finally block associated with the try block. Here the exception gets handled in lines 6 to 9 and then the execution proceeds to the finally block at line 16. Hence the output is "exception 1" followed by "finally".

Feedback to Author
Question
35
You would like to print the message "No Errors" if the String reference variable s is neither null nor referring to a zero length String. Select the correct choices to achieve this goal?
Choose one answer.
a. if(s != null & s.length() > 0)
System.out.println("No Errors");
b. if(s.length() > 0 && s != null)
System.out.println("No Errors");
c. if(s != null && s.length() > 0)
System.out.println("No Errors");
d. if(s.length() > 0 & s != null)
System.out.println("No Errors");
ANSWER: C

Explanation:
The length() method of the String class returns the length of the String. Here if s is null, the statement s.length()>0, will throw NullPointerException. So this statement must not be executed if s is null.

The & operator always evaluates both operands, so s.length() will be executed under all circumstances if & is used. && is a short circuit operator. If the left hand operand is evaluated to false, the right hand operand will not be evaluated and thus no exception will be thrown. So the statement s.length() > 0 will be executed only if s !=null is true. If both cases are satisfied, the message "No Errors" will be printed.

Feedback to Author
Question
36
Choose the right option so that i var becomes 12.
Choose one answer.
a. int i=4;
i*=i--;
b. int i=4;
i*=++i;
c. int i=4;
i/=--i;
d. int i=4;
i*=--i;
e. int i=4;
i*=i;
ANSWER: D

Explanation:
The code demonstrates the use of the overloaded assignment operators. The statement i*=--i; is the same as i=i*(--i);

The result of the expression --i is 4-1=3. So the expression i*(--i) can be evaluated as 4*3=12. The other expressions listed in the choices, do not evaluate to a result of 12.

Read more about assignment operators at
http://java.sun.com/docs/books/jls/thir ... .html#5281

Feedback to Author
Question
37
Choose the correct descriptions for finalize() and System.gc() methods.
Choose at least one answer.
a. May cause the garbage collector to run .
b. Causes the garbage collector to run immediately.
c. Can be used to resurrect an object.
d. Will be always called just before garbage collection happens.
e. May or maynot be called just before garbage collection happens.
ANSWER: A,C,E

Explanation:
It is possible to create new live references to the object on which the finalize() method is invoked. This puts the object back into a reachable state. This practice is known as resurrection, however it is worth mentioning that this is not recommended.

The finalize() method of an object will be definitely called before garbage collection happens, though it is not guaranteed that an object will be garbage collected or not, during its life time.

The System.gc() statement merely *suggests* that the Java Virtual Machine expend effort toward recycling unused objects in order to free the memory they currently occupy. So it may cause the garbage collector to run but there is absolutely no guarantee.

Want to know more? You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Also, the API documentation of the Object class contains the necessary information about the finalize() method -
http://java.sun.com/j2se/1.4/docs/api/j ... bject.html

Feedback to Author
Question
38
How many object references will be referring to the object created at line 7, after the execution of line 11 in the following code?

1. public class TestGC
2. {
3. public static void main(String[] args)
4. {
5. Object x = new Integer(10);
6. Object y = new Long(100);
7. Object z = new StringBuffer("Garbage");
8. Object obj = x;
9. x = z;
10. z = y;
11. y = x;
// Remaining code here
}
}
Choose one answer.
a. 0
b. 1
c. 2
d. 3
Choice C is the correct answer.

There will be two object references, 'x' and 'y' referring to the object created at line 7, after the execution of line 11.

Now let us look at the execution of the code. Lines 5, 6, and 7 create three objects - Integer, Long, and StringBuffer referred to by three object references x, y, and z respectively. After the execution of line 8, the object reference 'obj' refers to the Integer object referred to by 'x'. At line 9, 'x' starts referring to the StringBuffer object referred to by 'z'. At line 10, 'z' starts referring to the Long object referred to by 'y'. At line 11, 'y' starts referring to the StringBuffer object, which is also being referred to by 'x'.

Thus, after execution of line 11, the Integer object is referred to by 'obj' (assigned at line 8), the Long object is referred to by 'z' (assigned at line 10), and the StringBuffer object is referred to by 'x' and 'y' (assigned at line 9 and line 11). Hence, there will be two object references referring to the StringBuffer object created at line 7, after the execution of line 11.

It is important to understand and track the object references to a particular object in the given code. An object with 0 (zero) references is a candidate for garbage collection.

Want to know more?

You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Feedback to Author
Question
39
What will happen when you attempt to compile and run the following code?

public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String[] args)
{
x--;
myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod()
{
y = x++ + ++x;
}
}
Choose one answer.
a. Compiler error
b. prints : 1
c. prints : 2
d. prints : 3
e. prints : 7
f. prints : 8
Choice D is the correct answer.

The above code will not give any compilation error. Note that "Static" is a valid class name. Thus, choice A is incorrect.

When executing the above code, the static variables (x and y) will be first initialized to 0. Then, the static block will be called and finally the main() method will be called. The execution of the static block will have no effect on the output as it declares a new variable (int x). The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1. In case the statement is "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1.

Finally, when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which results in 3 as given in the output. Thus choice D is correct.


Feedback to Author
Question
40
What will be the result of executing the following code?

// Filename; SuperclassX.java

package packageX;
public class SuperclassX
{
protected void superclassMethodX() { }
int superclassVarX;
}

// Filename SubclassY.java
1. package packageX.packageY;
2. import packageX.*;
3. public class SubclassY extends SuperclassX
4. {
5. SuperclassX objX = new SubclassY();
6. SubclassY objY = new SubclassY();
7. void subclassMethodY()
8. {
9. objY.superclassMethodX();
10. int i;
11. i = objY.superclassVarX;
12. }
13. }
Choose one answer.
a. Compilation error at line 5
b. Compilation error at line 9
c. Runtime exception at line 11
d. None of these
Choice D is the correct answer.

When no access modifier is specified for a member, the latter is only accessible by other classes defined in the same package. Even if its class is visible in another package, the member is not accessible there.

In the question above, the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the SuperclassX class is visible and the protected method superclassMethodX()is accessible. Thus the compiler will raise an error at line 11.

Check out access control rules at http://java.sun.com/docs/books/jls/thir ... s.html#6.6

Feedback to Author
Question
41
You want to execute a class named My.class in the package whiz.utilities.myapp. The path to that directory is /java/MyPackages/whiz/utilities/myapp
Which command would you use to run the class?
Choose one answer.
a. java -classpath . /java/MyPackages/whiz/utilities/myapp My
b. java -classpath /java/MyPackages whiz.utilities.myapp.My
c. java -classpath . java.MyPackages.whiz.utilities.myapp.My
d. java -classpath . /java/MyPackages/whiz/utilities/myapp/My
Choice B is the correct answer.

Java classes are organized into packages which are mapped to directories in the file system. When classes are stored in a directory (folder), like /java/MyPackages/whiz/utilities/myapp, then the class path entry points to the directory that contains the first element of the package name. (in this case, /java/MyPackages, since the package name is whiz.utilities.myapp.)

Want to know more about setting classpaths? Check out
http://java.sun.com/j2se/1.5.0/docs/too ... spath.html

Feedback to Author
Question
42
What will happen when you attempt to compile and run the following code?

public class MyArray
{
public static void arrange(int[] array)
{
int length = array.length;
int half = length/2;
while( half>= 1)
{
for(int i=half;i<length;i++)
{
int temp=array[i];
int test=i;
while(test>= half && temp < array[test - half])
{
array[test] = array[test - half];
test -= half;
}
array[test] = temp;
}
half/=2;
}
}

public static void main(String[] args)
{
int[] array = {2,3,1};
arrange(array);
for(int i=0; i<array.length;i++)
{
System.out.print(array[i]);
}
}
}
Choose one answer.
a. Compiler error
b. Exception at runtime
c. No output
d. Prints : 231
e. Prints : 123
f. Prints : 012
Choice E is the correct answer.

Arrays can be used as arguments of a user-defined method exactly as any other type. However, since arrays in Java are actually hidden references, the method can change the elements in the array.

In the above code, there will not be any compile-time or runtime error. Inside the main method, first an array is initialized and then it is passed to the arrange method and finally the array is printed.

The arrange method performs sorting (shell sort) on the array passed to it as an input. After the execution of the arrange() method, the array is sorted. As stated earlier, since arrays in Java are actually hidden references, the method can change the elements in the array.

Thus finally when the array is printed, the sorted array will be printed which will have its elements as 1, 2, and 3 in that order. Thus "123" will be the output of the above code.

Feedback to Author
Question
43
Which of the following code snippets can be inserted at line 10, so that the object created at line 5 becomes eligible for garbage collection?

1. public class TestGC
2. {
3. public static void main(String[] args)
4. {
5. Object a = new Integer(7);
6. Object b = new StringBuffer("Java");
7. Object c = a;
8. a = b;
9. b = null;
10. // What can be inserted here?
11. }
12. }
Choose one answer.
a. a = null;
b. b = c;
c. a = c;
d. c = null;
e. None of these
Choice D is the correct answer.

The code snippet c = null; can be inserted at line 10, so that there is no reference to the Integer object created at line 5, and thus it becomes eligible for garbage collection.

Now let us look at the execution of the code. At line 5, an Integer object is created and it is assigned to the object reference 'a'. Line 6 creates a StringBuffer object. At line 7, the object reference 'c' also refers to whatever 'a' is referring to at that time. Thus, after the execution of line 7, the Integer object (created at line 5) has two references pointing to it. But at line 8, 'a' starts referring to whatever 'b' is referring to at that time. Hence after the execution of line 8, there is only one object reference 'c' referring to the original Integer object created at line 5. This object reference 'c' must be made "null" so that there are no more references to the Integer object, and it would become eligible for garbage collection. Thus, only choice D is correct.

Choices A, B, and C are incorrect because none of them affects the object reference 'c', which is referring to the Integer object created at line 5.

Want to know more?

You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Feedback to Author
Question
44
Which of the following statements will compile when inserted independently within the main method? Select three choices.

import java.util.*;
class Shape{}
class Rectangle extends Shape{}
class Generics1
{
public static void main(String[] args)
{
//insert statement here
}
}
Choose at least one answer.
a. Vector v1 = new Vector<Shape>();
b. Vector<?> v2 = new Vector<Rectangle>();
c. Vector<Shape> v3 = new Vector<Shape>();
d. Vector<Rectangle> v4 = new Vector<Shape>();
e. Vector<Shape> v5 = new Vector<Rectangle>();
f. Vector<Object> v6 = new Vector<Shape>();
g. Vector<Rectangle> v7 = new Vector<?>();
Choices A, B, and C are the correct answers.

It is legal to assign a generic type to a raw type. So choice A is correct. The wild card type of Vector (Vector<?>) is the supertype of all kinds of Vectors, so the assignment in choice B is legal and correct.

Choice C is also correct because it is legal to instantiate a generic type.

Choices D, E, and F are incorrect because the declared type is not the supertype of the instantiated type.

Choice G is incorrect because you cannot instantiate a wild card type since its actual type is unknown at compile time.

Note: Please note that Vector<Shape> is not the super type of Vector<Rectangle>.

From the generics tutorial:
"In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions."
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
45
What is the result of compiling and running the following program?

import java.util.*;
1. class Shape{}
2. class Rect extends Shape{}
3. class Circle extends Shape{}
4. class ShadedRect extends Rect{}
5. class Generics2{
6.public static void add(List <? extends Shape >l,int pos,Rect r){
7. l.add(pos,r);
8. }
9. public static void main(String[] args){
10. List<ShadedRect> l=new LinkedList<ShadedRect>();
11. add(l,0,new ShadedRect());
12. }
13. }
Choose one answer.
a. Compiler error at line 6
b. Compiler error at line 11
c. Compiler error at line 7
d. ClassCastException is thrown
e. Compiles and runs without errors
Choice C is the correct answer.

The code does not compile at line 7, since you cannot add objects to a collection of an unknown type. The wild card notation List <? extends Shape> indicates a list which can accept any kind of Shape. However, you cannot add to such a collection since the actual type is unknown at compile time.

There are no compiler errors at lines 6 and 11 because ShadedRect, is a subclass of Rect, which is a subclass of Shape. So it is legal to pass List <ShadedRect> as List <? extends Shape>. So choices A and B are incorrect.

Choices D and E are incorrect because the code does not even compile.

Check out this comprehensive tutorial on generics to learn more,
http://java.sun.com/docs/books/tutorial ... cards.html

Feedback to Author
Question
46
Insert the correct code at #1 & #2 so that the following compiles:

class X implements Comparable
{
String name;
X(String name)
{
this.name=name;
}

#1
{
X x=(X)o;
return name. (x.name);
}

public String toString()
{
return name;
}
}

public final class Generics12
{
public static void main(String[] argv)
{
#2
tree.put(new X("Tom"),1);
tree.put(new X("Huck"),2);
tree.put(new X("Jack"),3);
}
}
Choose at least one answer.
a. 1# public int compareTo(Object o)
b. 2# TreeMap <X,int> tree = new TreeMap <X,int> ();
c. 1# public int compare(Object o)
d. 2# TreeMap <X> tree = new TreeMap <X> ();
e. 1# public boolean compareTo(Object o)
f. 2# TreeMap <X,Integer> tree = new TreeMap <X,Integer> ();
ANSWER: A,F

Explanation:
The TreeMap sorts its contents in the ascending order of its keys. So the class to which the key objects belong, must implement the Comparable interface. The Comparable interface defines the method int compareTo(Object o) which compares this object with the specified object for order. It returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

If you try to add key objects which do not implement the compareTo method, to the TreeMap, then a ClassCastException is thrown. In the given code, the class X implements Comparable interface and defines the compareTo method. The method defines the sorting order for the objects, by comparing the name instance variable of the class.

B is incorrect as int can't be a generic parameter
D is incorrect way to declare a generic a TreeMap

Feedback to Author
Question
47
Insert the correct code at #1 & #2 so that the following compiles and the output is sorted by name and age of the employee.

import java.util.*;

class Employee
{
String name;
int age;
Employee(String name,int age)
{
this.name=name;
this.age=age;
}

String getName()
{
return name;
}

int getAge()
{
return age;
}

public String toString()
{
return name+" of age "+age;
}
}

class MyComparator < T extends Employee > implements Comparator < T >
{
#1
{
String name1=obj1.getName();
String name2=obj2.getName();
if(!name1.equals(name2))
return name1. (name2);
else
return obj1.age-obj2.age;
}
}

class Generics3
{
public static void main(String[] args)
{
#2
set.add(new Employee("Jacob",30));
set.add(new Employee("George",29));
set.add(new Employee("Daisy",40));
set.add(new Employee("Daisy",22));
for ( e: set)
{
System.out.println(e);
}
}
}
Choose at least one answer.
a. 2# Set<Employee> set=new Set <Employee> (new MyComparator<Employee>());
b. 1# public int compareTo( T obj1, T obj2)
c. 2# Set<Employee> set=new TreeSet <Employee> ();
d. 1# public boolean compareTo( T obj1, T obj2)
e. 2# Set<Employee> set=new TreeSet <Employee> (new MyComparator<Employee>());
f. 1# public int compare( T obj1, T obj2)
ANSWER: E,F

Explanation:
The java.lang.Comparator interface defines the compare method whose signature is
int compare(Object o1, Object o2). A comparator can be used to define total ordering of objects in a collection based on the result of the compare method. The TreeSet class guarantees that the set will be sorted according to the natural order of the elements (if the elements implement Comparable interface), or by the comparator provided at set creation time, if the constructor used takes the Comparator as the argument. Here the Comparator provides sorting according to the order of the name and age instance variables in the Employee class. The objects in the TreeSet can be iterated using the enhanced for loop.

Read more about the comparator at
http://java.sun.com/j2se/1.4.2/docs/api ... rator.html

Feedback to Author
Question
48
What is the result of compiling and running the following code?

import java.util.*;

public class Test
{
public static void main(String[] args)
{
TreeMap myMap = new TreeMap();
myMap.put("ab", 10);
myMap.put("cd", 5);
myMap.put("ca", 30);
myMap.put("az", 20);

NavigableMap myMap2 = myMap.headMap("cd", true);
myMap.put("bl", 100);
myMap.put("hi", 100);
myMap2.put("bi", 100);
System.out.println(myMap.size() + " " + myMap2.size());
}
}

Choose one answer.
a. Code will not compile.
b. Throws an exception at runtime.
c. Prints 7 6
d. Prints 7 5
Choice C is the correct answer.

This code compiles fine and prints the output shown below.

7 6

The TreeMap is a NavigableMap that is ordered according to the natural ordering of its keys. The headMap(toKey,inclusive) method of this class returns a view of the portion of this Map whose keys are less than (or equal to, if inclusive is true) toKey.

In this program, the value of toKey is "cd". All the keys added; "ab", "cd", "ca", "az" are within the range of "cd", so all are included in the map, myMap2, returned by the headMap method. After the method call to headMap(), two more entries are made into the original map. But only "b1" is included in myMap2 because "h1" is not less than or equal to "cd".

Finally one more entry is myMap2, for key "bi". So myMap contains the keys; "ab", "cd", "ca", "az", "b1", "h1", "bi" and myMap2 contains all of these except "h1". So the sizes of these maps are printed as 7 6.

You can read more about the NavigableMap at
http://www.devx.com/Java/Article/33872
http://java.sun.com/javase/6/docs/api/j ... leMap.html

Feedback to Author
Question
49
Which of the following statements about the implementation of the hashCode() method of Object class as shown in the following code is true?
1. public class CorrectHashCode
2. {
3. private int number;
4.
5. public CorrectHashCode(int i)
6. {
7. number = i;
8. }
9.
10. public int hashCode()
11. {
12. int i = (int)(Math.random() * 100);
13. return i * number;
14. }
15.
16. // other methods
17. }
Choose one answer.
a. The code implements hashCode() method correctly.
b. The code does not implement hashCode() method correctly.
c. This implementation of hashCode() method is correct if only if the equals() method is not overridden.
d. The given code does not contain enough information to comment on the correctness of the hashCode() method implementation.
e. None of these.
Choice B is the correct answer.

There is enough information available in this code itself to judge its correctness. The presence of the overridden equals(Object o) method is not required to determine this. The code does not implement the hashCode() method correctly. This code returns a hash code that is a product of a random number and an int member variable named "number".

The general contract of the hashCode() method mentions the following:-
If the method is invoked on the same object more than once during an execution of a Java application, the method must consistently return the same integer value, provided no information used in equals comparisons on the object is modified. The absolute integer value need not remain consistent from one execution of an application to another execution of the same application.

Since this code returns a hash code that involves a multiplication with a random number, it is improbable that it will consistently return the same integer whenever it is invoked on the same object more than once. Moreover, no matter how the equals() method is overridden, it is highly unlikely that the hash code returned by this method will be the same for two objects of this class which are equal according to the equals method.

This code does not abide by the general contract of the hashCode() method, and hence this implementation of the hashCode() method is essentially incorrect; no matter how the equals() method is implemented/overridden.

More information is available at
http://java.sun.com/j2se/1.3/docs/api/j ... bject.html

Feedback to Author
Question
50
Which of the following statements regarding the java.util.Set interface are true? Select three choices.
Choose at least one answer.
a. java.util.Set extends the java.util.Collection interface.
b. java.util.Set maintains a set of key-value pairs.
c. java.util.Set does not allow duplicate elements.
d. java.util.Set maintains its elements in a sorted order.
e. All methods defined in java.util.Set are also defined in java.util.Collection.
f. java.util.Set does not allow a null element.
Choices A, C, and E are the correct answers.

The java.util.Set extends the java.util.Collection interface and all its methods are also defined in java.util.Collection. java.util.Set does not contain any additional methods; it only imposes an additional restriction that prohibits duplicate elements. A Map maintains key-value pairs hence choice B is incorrect.

java.util.Set itself does not impose any order; hence choice D is incorrect.

It is very important to understand that even though some implementations of the Set interface may prohibit the addition of a null element, the Set interface itself does allow at most one null element.

Set : A collection that contains no duplicate elements.

More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Read about java.util.Set at
http://java.sun.com/j2se/1.5.0/docs/api ... l/Set.html

Feedback to Author
Question
51
Which collection class offers constant-time performance for the basic operations -add(), remove(), contains(), and size()?
Choose one answer.
a. TreeSet
b. HashSet
c. BitSet
d. None of these
Choice B is the correct answer.

HashSet offers constant time performance for the basic operations (add, remove, contains, and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it is very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

The constant time performance for basic operation means operations do not take significantly longer as the size of Set increases. Thus, making it is faster. Also, note that the constant time performance is a "near" constant time performance.

TreeSet, on the other hand, provides guaranteed log( n ) time cost for the basic operations, that is, the time increases with the log of the size of the set. Hence choice A is incorrect.

BitSet has nothing to do with collections or Set, so choice C is also incorrect.

Also, note that JDK 1.4 has added a new class java.util.LinkedHashSet that extends HashSet; this class also provides constant-time performance for the basic operations add, contains, and remove.

Read more about HashSet at
http://java.sun.com/j2se/1.5.0/docs/api ... shSet.html

Feedback to Author
Question
52
What will be the result of compiling and running the following code?

import java.util.*;
public class Generics8
{
public static void main(String[] args)
{
ArrayList<String> arr = new ArrayList<String>();
arr.add("B");
arr.add("A");
List <Object> list = new ArrayList <Object>();
list = arr;
System.out.print(list);
}
}
Choose one answer.
a. Compiler error
b. Throws ClassCastException
c. Prints [A,B]
d. Prints [B,A]
Choice A is the correct answer.

List <Object> is not the supertype of all List types, instead it must be List<?>. So assigning an object of type ArrayList <String> to List <Object> is not allowed by the compiler. Since the code does not compile, all the other choices are automatically incorrect.

For more information, check out http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
53
What is the result of compiling and running the following code?

import java.util.*;

public class Test1
{
public static void main(String[] args)
{
Set<String> hashSet = new HashSet<String>();
hashSet.add("gh");
hashSet.add("ab");
hashSet.add("A");
hashSet.add("X");
TreeSet<String> treeSet = new TreeSet<String>(hashSet);
Set<String> treeSet1 = treeSet.descendingSet();
for(String s : treeSet1)
{
System.out.print(s + " ");
}
}

}
Choose one answer.
a. Code will not compile.
b. Throws an exception at runtime.
c. Prints X A gh ab
d. Prints gh ab X A
e. Prints A X gh ab
Choice D is the correct answer.

The HashSet is a collection that does not maintain any ordering for its elements. However, the TreeSet maintains the natural order of sorting for its elements.

For String objects, the alphabetical order is considered. So the TreeSet treeSet maintains the elements in the order "A", "X", "ab", "gh".

ConcurrentSkipListSet and TreeSet implement the NavigableSet interface. Navigable interfaces are useful wherever you have in-memory cached data and you want to perform range-based queries upon keys of a map or entries of a set. The descendingSet() returns the reverse order view of the elements contained in the set. Hence the elements in treeSet1 are arranged in the order "gh", "ab", "X", "A".

You can read more about the TreeSet at http://java.sun.com/javase/6/docs/api/j ... eeSet.html

Feedback to Author
Question
54
What is the result of compiling and running the following program?

import java.util.*;
class Shape{}
class Circle extends Shape{}
class Rectangle extends Shape{}
class Generics4
{
public static void main(String[] args)
{
ArrayList<Circle> a=new ArrayList<Circle>();
a.add(new Circle());
ArrayList b=a;
ArrayList<Rectangle> c=(ArrayList<Rectangle>)b;
c.add(new Rectangle());
for(Object o:b)
System.out.println(o);
}
}
Choose one answer.
a. Compiler error
b. ClassCastException is thrown at runtime
c. Compiles with warnings, prints some output at runtime
d. Compiles with no errors or warnings, prints some output at runtime
Choice C is the correct answer.

When a generic type is used without a type parameter, it is called a raw type. Since you can insert all type of objects into these raw types, it is not possible to check their correctness. So assigning generic types to raw types generates an unchecked warning.

In this program, you assign the generic types to the raw type variable, and then insert different types of objects into it. The raw type is not type-checked, hence there are no compiler errors. So choice A is incorrect.

ClassCastException only arises when you try to cast an object to a subclass of which it is not an instance, There is no such case here, so choice B is also incorrect.

Choice D is incorrect because warnings are generated.

Feedback to Author
Question
55
You have a HashMap whose keys need to be retrieved in a sorted manner. Which of the following will help you achieve this? Select two choices.
Choose at least one answer.
a. Copy the contents of the HashMap into a TreeMap.
b. Add the keys of the HashMap to a TreeSet.
c. Pass the HashMap to the Arrays.sort() method.
d. Pass the HashMap to the Collections().sort() method.
Choices A and B are the correct answers.

Both HashMap and TreeMap are implementations of the Map interface, however HashMap does not maintain any ordering for its elements. TreeMap sorts its elements in the ascending order of the keys, so copying the HashMap contents to the TreeMap allows the keys to be retrieved in a sorted manner. TreeSet is a class which implements the Set interface, it allows sorting of its elements, so copying the HashMap keys into a TreeSet also is a solution.

Choice C is incorrect because the Arrays.sort() methods take only the array type as argument.

Choice D is incorrect because the Collections.sort() method takes java.util.List as the argument.

Feedback to Author
Question
56
Choose the correct class definitions corresponding to the relationships defined below:

Bar IS-A Object
Foo IS-A Bar
Foo HAS-A Bar
Choose at least one answer.
a. class Foo extends Bar{}.
b. class Bar extends Foo{}
c. class Bar{}
d. class Foo extends Bar{Bar bar;}
ANSWER: C,D

Explanation:
Two things, X and Y are in the IS-A relationship if the phrases "X is a Y" or "all Xs are Ys" are true. Objects in an IS-A relationship use inheritance as in class X extends Y.

For example, A Car is Vehicle, so a Car class might inherit from a Vehicle class. Two things, X and Y are in a HAS-A relationship if Y is a property or component of X, as in the phrases "X has a Y", or "Y is a component of X". If X HAS-A Y, than Y will be an instance variable in class X.

In Java, inheritance is marked with the keyword 'extends'. Since every Java class implicitly extends Object, Bar IS-A Object is given by class Bar{}. Foo IS-A Bar AND Foo HAS-A Bar is given by class Foo extends Bar{ Bar b;} so that the Bar b is an instance variable of the class Foo and class Foo also extends Bar.

Feedback to Author
Question
57
Insert the correct code at #1 so that following code compiles and runs fine.

interface IFace{}

class CFace implements IFace{}
class Base{}
class DFace extends CFace{}
public class ObRef extends Base
{
public static void main(String argv[])
{
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace i2 = new CFace();
o1=new ObRef();
#1
}
}
Choose one answer.
a. ob = (ObRef) o1;
o1 = i2;
b = ob;
o1 = b;
b. ob = o1;
o1 = i2;
b = ob;
o1 = b;
c. ob = (ObRef) o1;
o1 = i2;
b = ob;
ob = b;
d. ob = (ObRef) o1;
o1 = i2;
b = o1;
o1 = b;
ANSWER: A

Explanation:
A super class / interface type reference variable can refer to an object of the subclass type, but the opposite is not true. So i2 can be assigned to o1, ob can be assigned to b, b can be assigned to o1. Even though o1 refers to an object of the same type as ob, o1 needs to be cast down to the ObRef type before being assigned. This is because o1 is declared as of type Object.

Want to know more about assignment conversions ? Check out this link.
http://java.sun.com/docs/books/jls/thir ... s.html#5.2

Feedback to Author
Question
58
Given the following code, in which order will the output be produced?

class C extends A
{
public C()
{
System.out.println("C");
}
}

class A
{
public A()
{
System.out.println("A");
}
}

class B extends C
{
public B()
{
System.out.println("B");
}
}

public class ABC
{
public static void main(String[] args)
{
System.out.println("Main");
B c = new B();
}
}
Choose one answer.
a. C, B, B, Main
b. Main, A, C, B
c. Main, A, B, C
d. Main, A, B, A
Choice B is the correct answer.

All constructors implicitly call the no argument constructor of the immediate superclass using super(); if no explicit call is made to the superclass constructor. So in this case, when you instantiate B, its constructor calls the constructor of C.

C's constructor calls the constructor of its superclass A. Thus, the order of printing would be Main, A, C, B.

Read more about invoking superclass constructors at http://www.javaworld.com/jw-10-2000/jw- ... ctors.html

Feedback to Author
Question
59
What will happen when you attempt to compile and run the following code?

class MyParent
{
int x, y;

MyParent(int x, int y)
{
this.x = x;
this.y = y;
}

public int addMe(int x, int y)
{
return this.x + x + y + this.y;
}

public int addMe(MyParent myPar)
{
return addMe(myPar.x, myPar.y);
}
}

class MyChild extends MyParent
{
int z;

MyChild (int x, int y, int z)
{
super(x,y);
this.z = z;
}
public int addMe(int x, int y, int z)
{
return this.x + x + this.y + y + this.z + z;
}
public int addMe(MyChild myChi)
{
return addMe(myChi.x, myChi.y, myChi.z);
}
public int addMe(int x, int y)
{
return this.x + x + this.y + y;
}
}

public class MySomeOne
{
public static void main(String[] args)
{
MyChild myChi = new MyChild(10, 20, 30);
MyParent myPar = new MyParent(10, 20);
int x = myChi.addMe(10, 20, 30);
int y = myChi.addMe(myChi);
int z = myPar.addMe(myPar);
System.out.println(x + y + z);
}
}
Choose one answer.
a. 300
b. 240
c. 120
d. 180
e. Compilation error
f. None of the above
Choice A is the correct answer.

In the above code, the MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both MyChild and MyParent classes, the addMe() method is overloaded. There is no compilation error anywhere in the above code. When executing, the object of the MyChild class will first be created. Please note that there is a super() call from the constructor of the MyChild class, which will call the constructor of the MyParent class. This will cause the value of the z member variable of the MyChild class to be 30 and the x, y member variables of the MyParent class will become 10 and 20, respectively.

The next statement will again call the constructor of the MyParent class with the same x and y values. This is followed by the execution of the addMe() method of the MyChild class with x as 10, y as 20, and z as 30. Also x and y are inherited by the MyChild class from the MyParent class. Thus, in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20, and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus, x will become 120. This is followed by the invocation of the other addMe() method which takes an object reference to an instance of the MyChild class.

From this method, the method which was called earlier (the addMe method which takes the 3 int arguments) is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120, like x. Now, the addMe() method of the MyParent class is invoked. This method invokes another addMe() method declared in the same class. It's equivalent to the invocation of the addMe(int x, int y) method with x as 10 and y as 20. Also the values of the instance variables x and y of MyParent class are 10 and 20, respectively.

The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y, and z after all the invocations will be 120, 120, and 60, respectively. As a result of this, finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus choice A is the correct answer.

Feedback to Author
Question
60
What are the benefits of high cohesion? Select three choices.
Choose at least one answer.
a. Cohesion helps understand what a class or method does
b. Cohesion helps understand one class without studying others
c. Cohesion minimizes changes in other classes when one class is changed
d. Cohesion allows the use of descriptive names
e. Cohesion promotes reuse of classes or methods
Choices A, D, and E are the correct answers.

Cohesion refers to the number and diversity of tasks that a single unit is responsible for. If each unit is responsible for one single logical task, we say it has high cohesion. Cohesion applies to classes and methods. A well-designed unit will have high cohesion.

High cohesion makes it easier to:
understand what a class or method does
use descriptive names
reuse classes or methods
Choices B and C are incorrect because cohesion is not about the dependencies between classes. Choices B and C refer to the advantages of loose coupling.

Re: oracle java 6 certification exam mock questions

PostPosted: Wed Feb 22, 2012 4:57 pm
by tomrff
Question
1
What is the output when the following code is run ?

class PrintfTest1
{
public static void main(String[] args)
{
double x=123.456;
char c=65;
int i=65;
System.out.printf("%s", x);
System.out.printf("%b", x);
System.out.printf("%c", c);
System.out.printf( "%5.0f",x);
System.out.printf("%d", i);
}
}
Choose one answer.
a. 123.456 true A 45 123 65
b. 123.456 123.456 A 123 65
c. 123.456 true A 123 65
d. 123.456 true 65 123.45 65
e. 123.456 123.456 65 123 65
f. Compilation Error
ANSWER : C

Explanation:
The %s modifier formats an object by calling its toString() method. Here the value 123.456 is converted to a string and printed as such. The %b modifier is used to print boolean values, so "true" is printed next.

When the %c modifier is used, the char value of a variable is printed, which is 'A' for the ASCII code of 65. This is printed next. The modifier "5.0 f" specifies an overall field width of 5, with 0 digits to the right of the decimal point. So the value 123.456 is now printed as 123.

The %d modifier is used to print a formatted integer, thus 65 is printed as the value of i.

You can get more information about the printf method at
http://java.sun.com/j2se/5.0/docs/api/j ... tream.html

Feedback to Author
Question
2
What is the output when the following code is run ?

import java.util.regex.*;

public class Pattern1
{
public static void main(String[] args) throws Exception
{
Pattern p = Pattern.compile("My");
Matcher m = p.matcher("My dad And My mom");
StringBuffer s = new StringBuffer();
boolean found = m.find();
while(found)
{
m.appendReplacement(s, "Our");
found = m.find();
}
m.appendTail(s);
System.out.println(s);
}
}
Choose one answer.
a. My dad And My mom
b. Our dad and Our mom
c. dad And mom
d. Compilation error
e. No output
ANSWER : B

Explanation:
The compile() method of the Pattern class compiles the given regular expression into a pattern.

Then the matcher() method creates a matcher that will match the given input against this pattern.

The find() method scans the input sequence looking for the next sequence that matches the pattern.

The appendReplacement() method appends everything up to the next match and the replacement for that match.

The appendTail() method reads characters from the input sequence, starting at the append position, and appends them to the given string buffer. It is intended to be invoked after one or more invocations of the appendReplacement() method in order to copy the remainder of the input sequence.

Want to know more? Check out
http://java.sun.com/docs/books/tutorial ... ttern.html

Feedback to Author
Question
3
You want to append some more data to the abc.txt file which already contains information. Insert the appropriate code excerpts at #1 in the given code in order to achieve the given objective.

import java.util.regex.*;

public class Pattern1
{
public static void main(String[] args) throws Exception
{
import java.io.*;

class IOStream1
{
public static void main(String[] args)
{
try
{
#1
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Choose one answer.
a. BufferedWriter out = new BufferedWriter(new FileWriter("abc.txt", true));
out.append("world);
b. BufferedWriter out = new BufferedWriter(new FileWriter("abc.txt"));
out.write("world);
c. BufferedWriter out = new BufferedWriter(new FileWriter("abc.txt", true));
out.write("world);
d. FileWriter out = new FileWriter(new BufferedWriter("abc.txt", true));
out.write("world);
ANSWER : C

Explanation:
The FileWriter class is useful for writing into character files. Unless a prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

public FileWriter(String fileName, boolean append) throws IOException.

This constructs a FileWriter object, given a File object. If the second argument is true, then the written bytes will be appended to the end of the file rather than at the beginning. So, we pass true as the second argument to the FileWriter constructor, in order to enable the append mode.

Refer to the FileWriter API at http://java.sun.com/j2se/1.5.0/docs/api ... riter.html

Feedback to Author
Question
4
Select the options that will compile.
Choose at least one answer.
a. NumberFormat i = NumberFormat.getInstance(Locale.ITALY);
b. NumberFormat i = new NumberFormat();
c. NumberFormat i = new NumberFormat(Locale.ITALY);
d. NumberFormat i = NumberFormat.getInstance();
ANSWER : A,D

Explanation:
The NumberFormat class helps you format and parse numbers for any locale. You can't directly use the "new" keyword to instantiate this class, since it is abstract.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... ormat.html

Feedback to Author
Question
5
Select the correct Locale constructors.
Choose at least one answer.
a. Locale()
b. Locale(String language)
c. Locale(String language, String country)
d. Locale(String language, String country, String variant)
ANSWER : B,C,D

Explanation:
A Locale object represents a specific geographical, political, or cultural region.

The available constructors of Locale class are

Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String variant)

More information about Locale class is available at
http://java.sun.com/j2se/1.5.0/docs/api ... ocale.html
http://java.sun.com/docs/books/tutorial/i18n/

Feedback to Author
Question
6
What will be the output when following code is run.

import java.util.*;
import java.util.regex.*;

class ScannerTest
{
public static void main(String[ ] args)
{
String input = "1 done 2 done all done";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) done (\\d+) done (\\w+) done");
MatchResult result = s.match();
for (int i=1; i <=result.groupCount(); i++)
System.out.print(result.group(i)+" ");
s.close();
}
}
Choose one answer.
a. Compilation error
b. No output
c. 1 done 2 done all done
d. 1 2 all
Correct answer is choice D.

Explanation:
A Scanner breaks its input into tokens using a delimiter pattern, which, by default, matches white spaces. The findInLine() method attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. The code here uses a regular expression to parse all the four tokens at once.

References:
http://java.sun.com/j2se/1.5.0/docs/api ... anner.html
http://java.sun.com/developer/JDCTechTi ... t1201.html

Feedback to Author
Question
7
Which of the following statements about the given code are true?

class StringBuilderTest
{
public static void main(String[] args)
{
StringBuilder result = new StringBuilder("a");
for (int i=1; i<5; i++)
result.append("a");
result.insert(4,"123");
System.out.println(result);
}
}
Choose one answer.
a. If StringBuilder is replaced by StringBuffer, the only change is that thread synchronization is removed.
b. It does not compile.
c. It throws StringIndexOutOfBoundsException at runtime.
d. It prints "aaaa123a".
e. It prints "aaaaa123".
Choice D is the correct answer.

There are no errors in the given code; it compiles fine and prints "aaaa123a". First, the StringBuilder object is initialized to "a", then "a" is appended to it 4 times; thus, the result is "aaaaa". Then, we insert "123" at the 4th position, thus the result is "aaaa123a".

Choice A is incorrect because StringBuilder does not have support for thread synchronization. If StringBuilder is replaced by StringBuffer in this code, synchronization support is added, not removed.

Choice B is incorrect because there are no compilation errors.

Choice C is incorrect because there is no reason for StringIndexOutOfBoundsException to be thrown. You can refer to the StringBuilder API for more information.

Feedback to Author
Question
8
What is the result of compiling and running the following code? ( Assume that a console is available for the current JVM)

public class Test6
{
public static void main(String[] args)
{
int i = 200;
double d = 100.00;
System.console().format("%d * %1.1f", i, d);
}
}
Choose one answer.
a. Code will not compile.
b. Prints 200 * 100.0
c. Throws an exception at runtime.
d. Prints 20000.0
e. None of these
Choice B is the correct answer.

The System.console() method returns the Console object for the current JVM. The format() method of the Console class writes a formatted string to this console's output stream using the specified format string and arguments.

The format argument %d is used to format as a decimal integer. To format as a floating point value with one place after decimal point, we have the %1.1f argument. Since the arguments are not actually multiplied, choice C is incorrect. The other choices are also automatically incorrect.

You can read more about the System.console() method here.
http://java.sun.com/javase/6/docs/api/j ... l#console()

Feedback to Author
Question
9
What is the result of compiling and running the following code?
1. class BoolTest{
2. public static void main(String[] args){
3. Boolean b=new Boolean("TRue");
4. Boolean c=new Boolean("Null");
5. boolean d=true;
6. Boolean e=(b || c) && d;
7. System.out.println(e);
8. }
9. }
Choose one answer.
a. Compiler error at line 3
b. Compiler error at line 4
c. Compiler error at line 6
d. Prints "true"
e. Prints "false"
Choice D is the correct answer.
The Boolean constructor, which takes a String argument, allocates a Boolean object representing the value true if the value of the string argument is "true" (characters in the string may be lowercase or uppercase).
So, line 3 results in a Boolean object of value true and line 4, in a Boolean object of value false. If you have an expression that uses the logical operators like && and ||, Boolean types are unboxed to boolean primitive values and evaluated accordingly. In line 6, b || c yields true since b is true, which when ANDed with true yields true as well. The boolean result of the expression is autoboxed to the Boolean object type.
So choices C and E are also incorrect.

Check out Boolean class API here http://java.sun.com/j2se/1.4.2/docs/api ... olean.html
To know more about autoboxing and unboxing, please refer to http://java.sun.com/docs/books/jls/thir ... html#5.1.7

Feedback to Author
Question
10
Which of the following lines will print false?

1.public class MyClass
2.{
3. static String s1 = "I am unique!";
4. public static void main(String[] args)
5. {
6. String s2 = "I am unique!";
7. String s3 = new String(s1);
8. System.out.println(s1 == s2);
9. System.out.println(s1.equals(s2));
10. System.out.println(s3 == s1);
11. System.out.println(s3.equals(s1));
12. }
13.}
Choose one answer.
a. Line 8
b. Line 9
c. Line 10
d. Line 11
e. None of these
Choice C is the correct answer.

Line 10 will print false. If you construct multiple Strings using the same String literal without the new keyword, then Java creates only one String object. Hence, in the above code, the string references s1 and s2 refer to the same anonymous string object, initialized with the character string: "I am unique!"

Thus s1 == s2 will return true and obviously, s1.equals(s2) will return true. But creating string objects using the String(String s) constructor creates a new string, hence s3 == s1 will return false even though s3.equals(s1) will return true. This is because s1 and s3 are referring to two different string objects whose contents are same.

More information is available at
http://java.sun.com/j2se/1.3/docs/api/j ... bject.html
http://java.sun.com/docs/books/jls/thir ... html#12104

Feedback to Author
Question
11
What will be the output when following code is run.

import java.util.*;

public class Test
{
public static void main(String[] args)
{
Map<String, String > fruit = new LinkedHashMap<String, String> ();
fruit.put("Apple", "red");
fruit.put("Mango", "yellow");
fruit.put("Guava", "green");
fruit.put("Cherry", "red");
fruit.put("Mango", "red");
for (String key : fruit.keySet())
{
System.out.println(key + ": " + fruit.get(key));
}
}
}
Choose one answer.
a. Compilation error
b. Can't be determined
c. Apple: red
Mango: red
Guava: green
Cherry: red

d. Apple: red
Mango: yellow
Guava: green
Cherry: red

e. Apple: red
Mango: yellow
Mango: red
Guava: green
Cherry: red
Correct answer is choice C.

Explanation:
A Map is an object that maps keys to values.

LinkedHashMap is a map which maintains a doubly-linked list of its entries. It defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Note that the insertion order is not affected if a key is re-inserted into the map. In the given code, "Mango" is inserted twice, so the value "yellow" is replaced by "red".

The keySet() method returns a Set of the keys contained in this map. Invoking the get() method on this Set returns the corresponding value.

Feedback to Author
Question
12
Insert the correct code at #1 so that the code compiles and runs without errors.

class Shape{}
class Circle extends Shape{}
class Rectangle extends Shape{}
class Generics16
{
public static void main(String[] args)
{
#1
picture.add(new Circle());
picture.add(new Rectangle());
Rectangle rect = (Rectangle)picture.get(1);
}
}
Choose one answer.
a. Vector picture = new Vector < Shape > ();
b. Vector picture = new Vector < ? > ();
c. Vector picture = new Vector <? extends Shape >();
Explanation:
Correct answer is choice A.

The wildcard character (?) indicates unknown types, so the compiler does not allow adding or inserting into such types. So Vector<?> and Vector<? extends Shape> cannot be used here.

It is allowed to assign generic types to raw types, so Vector<Shape> can be assigned to Vector type. However, since we use a generic class without specifying the type of its element, the compiled code is not type-safe and the compiler will issue a warning.

Feedback to Author
Question
13
Insert the correct code at #1 so that the code compiles and runs without errors.

#1
l.add(4);
l.add("helo");
l.add(false);
Choose one answer.
a. List l = new LinkedList();
b. List <Object> l = new LinkedList<Object>();
c. List <? extends Object> l = new LinkedList<? extends Object>();
d. List <Object> l = new List<Object>();
e. List l = new List();
ANSWER : B

Explanation:
List<E> can take any object of type E, LinkedList<E> implements List<E>.

Here, all the types being added are of type Object. The primitive int 4 is autoboxed to the Integer object of value 4. LinkedList and List are raw types which do not guarantee type safety, so they will cause the compiler to generate warnings. Wild card types like List<? extends Object> is of unknown type, so adding to it will cause compiler errors.

For more information, check out
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
14
Select the option containing the correct order of the interfaces corresponding to the implementing classes given below.

Vector
LinkedList
Hashtable
HashMap
TreeSet
Choose one answer.
a. List
List
Map
Map
Map

b. List
List
Table
Map
Set

c. List
List
Map
Map
SortedSet

Correct answer is choice C.

Explanation:
The List interface represents an indexed and ordered collection. The Vector class implements the List interface. The LinkedList class implements both the List and the Queue interfaces. The Hashtable and HashMap classes are both Map implementations, the difference being that the Hashtable class is synchronized while the HashMap class is not.

Collections is a class, not an interface. The Collection interface is extended by both the Set interface and the List interface, but not by the Map interface.

Feedback to Author
Question
15
What is the output when the following code is run.

class Arrays1
{
public static void main(String[] args)
{
Integer a[]={12,5,333,5,221,0,00};
Arrays.sort(a);
List l=Arrays.asList(a);
int in=Arrays.binarySearch(a, 12);
System.out.println(in);
}
}
Choose one answer.
a. Compilation error.
b. 4
c. -1
d. Can not be determined.
e. Exception at runtime.
Correct answer is choice B.

Explanation:
The java.util.Arrays class contains various methods for manipulating arrays (such as sorting and searching).

The Arrays.asList() method returns a fixed-size list backed by the specified array. This method acts as bridge between array-based and collection-based APIs, in combination with Collections.toArray().

The sort() method can be used to sort the array passed in argument. In the code, the array is sorted as {0, 0, 5, 5, 12, 221, 333}.

The binarySearch() method searches the specified array for the specified value using the binary search algorithm. The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined. Searching for the number 12 in this array using the binarySearch() method, returns the index of the number, which is 4.

Reference: http://java.sun.com/j2se/1.5.0/docs/api ... rrays.html

Feedback to Author
Question
16
Which Java collection class can be used to maintain the entries in the order in which they were last accessed?
Choose one answer.
a. java.util.HashSet
b. java.util.LinkedHashMap
c. java.util.Hashtable
d. java.util.Vector
e. None of these
Choice B is the correct answer.

The java.util.LinkedHashMap class (since JDK 1.4) can be used for maintaining the entries in the order in which they were last accessed. This class, by default, maintains the entries in the order in which they were inserted and also provides a special constructor that allows you to specify that the entries should be maintained in the order in which they were last accessed, from least-recently accessed to most-recently accessed. The constructor is -

public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

The last parameter accessOrder specifies the way in which the entries will be maintained. If accessOrder is true, the entries (key-value pairs) will be maintained in an order in which they were last accessed. If accessOrder is false, the entries will be maintained in the order in which they were inserted.

This is what the API documentation says -

A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently accessed (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map.

None of the other classes given in the above choices can be used for this purpose; hence they are all incorrect.

Want to know more?

You can read more about the new collection class LinkedHashMap and its usage at -
http://www-106.ibm.com/developerworks/j ... j-mer0821/

Feedback to Author
Question
17
What is the result of compiling and running the following code?

import java.util.*;
public class TestSet
{
public static void main(String[] args)
{
Collection<String> set=new TreeSet<String>();
set.add("Java");
set.add("XML");
set.add("Swing");
set.add("JSP");
set.add("Java");
for(Object o : set)
{
System.out.print(o + " ");
}
}
}
Choose one answer.
a. Does not compile
b. Throws ClassCastException
c. Prints "Java XML Swing JSP"
d. Prints "Java XML Swing JSP Java"
e. Prints "JSP Java Swing XML"
f. Prints "Java JSP Swing XML"
Choice E is the correct answer.

TreeSet is a collection which stores its elements sorted by their natural order. So the strings are printed out in the ASCII order of their characters. Thus, "JSP Java Swing XML" is printed. Since TreeSet does not allow duplicates, "Java" is not printed twice. So choices C, D, and F are incorrect.

Since TreeSet indirectly implements Collection, the assignment Collection<String> set=new TreeSet<String>() is allowed. Assigning the strings into the variable of type Object, while iterating using the for-each loop is also allowed, since Object is the super type of all classes.

Choices A and B are incorrect since the code compiles and runs without errors.

Check out this comprehensive tutorial on generics to learn more
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
18
We have the following organization of classes.

class Parent { }
class DerivedOne extends Parent { }
class DerivedTwo extends Parent { }

Which of the following statements is correct for the following expression?

Parent p = new Parent();
DerivedOne d1 = new DerivedOne();
DerivedTwo d2 = new DerivedTwo();
d1 = (DerivedOne)d2;
Choose one answer.
a. Compiler error
b. Compiles fine but throws RuntimeException
c. Compiles and runs without error
d. Compiles fine but throws ClassCastException
Choice A is the correct answer.

Here, DerivedOne and DerivedTwo classes inherit from the same superclass, so they are sibling objects. You cannot assign an object reference to a sibling reference, even with casting.

It is possible to assign an object to a reference variable, the variable has to be the super type of this object. So they must be part of the same inheritance hierarchy. Since the program does not even compile, the other choices are automatically incorrect.

Feedback to Author
Question
19
What is the result of compiling and running the following code?

import java.util.*;
class Generics13
{
public static void main(String[] args)
{
List<Integer> list=new LinkedList<Integer>();
list.add(1);
list.add(4);
list.add(-4);
for(Iterator i=list.iterator(); i.hasNext();)
{
Integer in=i.next();
System.out.println(in);
}
}
}
Choose one answer.
a. Prints 1,4,-4
b. Prints -4,1,4
c. Compiler error: You can't pass primitives to the add() method
d. None of these
Choice D is the correct answer.

The code does not compile because the next() method of the Iterator interface returns an object of type Object. It needs to be cast down to Integer. If we had used Iterator<Integer> instead of Iterator, this casting would not have been necessary.

Choices A and B are incorrect since the code does not compile.

Choice C is incorrect because the new autoboxing feature allows primitives to be passed to methods that expect object arguments.

For more information, check out
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
20
What is the result of compiling and running the following code?

import java.util.*;
class Shape{}
class Circle extends Shape{}
class Rectangle extends Shape{}
class Generics15
{
public static void main(String[] args)
{
Vector<Shape> picture = new Vector<Shape>(); // 1
picture.add(new Circle()); // 2
picture.add(new Rectangle()); // 3
Rectangle rect = picture.get(1); // 4
}
}
Choose one answer.
a. Compiler error
b. ClassCastException
c. Compiles without warnings and runs without errors
d. Compiles with warnings and runs without errors
Choice A is the correct answer.

The code causes compiler error at line 4 because the get() method returns an object of type Shape, which cannot be assigned to a variable of type Rectangle. The return value needs to be cast down to Rectangle for this code to compile and run without errors.

More information is available at
http://java.sun.com/j2se/1.5/docs/api/j ... ector.html
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
21
In the following code, which is the first statement, where the object originally held in m, may be garbage collected?

(Assume that MyObject is a properly defined class.)
1. public class Test
2. {
3. public static void main (String[] args)
4. {
5. MyObject m = new MyObject("Sun", 48);
6. m.myMethod();
7. System.out.println("Working");
8. m = null;
9. m = new MyObject("Moon", 36);
10. m.yourMethod();
11. System.out.println("Testing");
12. }
13. }
Choose one answer.
a. Line 12
b. Line 13
c. Line 9
d. Line 10
Choice C is the correct answer.

Please note that you can't force garbage collection, but you can increase the chances of an object being garbage collected by making it null. The object is available for garbage collection only after the execution of line 8, i.e., after m has been assigned a null value. Hence the statement at which the object is available is line 9, and not 8.

You can read more about garbage collection at - http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Feedback to Author
Question
22
Which of the following statements are true about the HashMap and the Hashtable classes? Select two choices.
Choose at least one answer.
a. A HashMap is synchronized, while a Hashtable is not.
b. A Hashtable is synchronized, while a HashMap is not.
c. A HashMap can have null values, but not null keys.
d. A Hashtable cannot have null values or null keys.
e. A Hashtable maintains object references in the order in which they were added, while the HashMap does not.
Choices B and D are the correct answers.

A Hashtable is synchronized, while a HashMap is not. A Hashtable cannot have null keys or values.

Choice A is incorrect because choice B is correct.

Choice C is incorrect because key or values can be null for a HashMap. Both Hashtable and HashMap do not maintain the object references in the order in which they were added. They use the hashcodes of objects for ordering. So choice E is false.

References: http://java.sun.com/j2se/1.5.0/docs/api ... shMap.html
http://java.sun.com/j2se/1.5.0/docs/api ... table.html

Feedback to Author
Question
23
What is the result of compiling and running the following code?

import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
public class Test3
{
public static void main(String[] args)
{
ConcurrentSkipListSet<String> mySet = new ConcurrentSkipListSet<String>();
mySet.add("me");
mySet.add("you");
mySet.add("they");
mySet.add("she");
String newElement = mySet.ceiling("your");
System.out.println(newElement);
}
}
Choose one answer.
a. Code will not compile.
b. Throws an exception at runtime.
c. Prints you
d. Prints you they she me
e. Prints null
Choice E is the correct answer.

Executing this code causes "null" to be printed to the console. ConcurrentSkipListSet and TreeSet classes implement the NavigableSet interface. The elements are maintained in the alphabetical order, since that is the natural order in which String objects are sorted.

The ceiling method of ConcurrentSkipListSet returns the least element in this set greater than or equal to the given element, or null if there is no such element. The given element is "your" and there is no element that is greater than or equal to this. Hence null is returned and printed.

Since choice E is correct, all the other choices are automatically incorrect.

You can read more about the ConcurrentSkipListSet here.
http://java.sun.com/javase/6/docs/api/j ... stSet.html

Feedback to Author
Question
24
Which of the following will compile if inserted within the given class?

class MyGenericClass<T>{ }
Choose one answer.
a. static T obj2;
b. static T getObj() { return new T() }
c. static void showObj(){ T obj=new T(); obj.show(); }
d. All of these
e. None of these
Choice E is the correct answer.

None of these will compile because no static member can use a type parameter declared by the enclosing class. However, static generic methods can be used which define their own type parameters.

For more information, check out
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Feedback to Author
Question
25
What will be the result of attempting to compile and run the following program?

class MyThread extends Thread
{
String sa;
public MyThread(String sa)
{
this.sa = sa;
}
public void run()
{
synchronized (sa)
{
while (!sa.equals("Done"))
{
try
{
sa.wait();
}
catch (InterruptedException ie){}
}
}
System.out.print(sa);
}
}
class Test
{
private static String sa = new String("Not Done");
public static void main (String[] args)
{
Thread t1 = new MyThread(sa);
t1.start();
synchronized (sa)
{
sa= new String("Done");
sa.notify();
}
}
}
Choose one answer.
a. Does not compile
b. Throws exception at runtime
c. Prints "Done"
d. Prints "Not Done"
e. May print "Done" or "Not Done"
f. None of the above
Choice B is the correct answer.

Here, the thread t1 synchronizes on the object referred to by sa. It goes into the waiting state because the String is equal to "Not Done". Now the main method attempts to synchronize on the same object referred to by sa. Then comes the tricky part; sa is made to refer to a new String object and the notify() method is invoked on that object.

Note that the main thread has the lock of the old String which was referred to by sa. So it is not the owner of the lock of the new String object.

If the notify() method is invoked on an object by a thread which is not the owner of the lock to that object, it throws IllegalMonitorStateException. Thus B is correct.

Also note that even if the object had the lock, it would not be possible to influence the sa variable in the MyThread class, i.e. changing the referenced String in the Test class does not change the String in the MyThread class. Thus, the thread would wait forever.

Check out the API for more about the wait and notify methods http://java.sun.com/j2se/1.5.0/docs/api ... bject.html

Feedback to Author
Question
26
What will be the result of attempting to compile and run the following program?

class MyThread extends Thread
{
public void run()
{
m1();
}
MyThread(String threadName)
{
super(threadName);
}
public synchronized void m1()
{
System.out.print(Thread.currentThread().getName());
}
public static void main (String[] args)
{
MyThread a = new MyThread("A");
MyThread b = new MyThread("B");
b.start();
Thread.yield();
a.run();
}
}
Choose one answer.
a. Prints "BA"
b. Prints "AB"
c. Prints "Bmain"
d. Prints "mainB"
e. Output can be "Bmain" or "mainB"
f. Output can be "BA" or "AB"
g. Code does not compile
Choice E is the correct answer.

Here, two new Thread objects are created, but only thread B is started in a separate thread of execution.

When the run() method is invoked directly on a Thread object, it does not start a new thread of execution. So in this case, the run() method is run for the main thread and the thread B. So the output will contain "B" and "main", but the order in which these appear cannot be predicted because it is dependent on the Thread Scheduler. So the output can be "Bmain" or "mainB".

Re: oracle java 6 certification exam mock questions

PostPosted: Wed Feb 22, 2012 4:57 pm
by tomrff
Feedback to Author
Question
27
Before which of the following can the "synchronized" keyword be placed, without causing a compilation error? Select three choices.
Choose at least one answer.
a. class methods
b. instance methods
c. any block of code within a method
d. variables
e. a class
Choices A, B, and C are the correct answers.

Synchronization is performed to protect critical code from being accessed by multiple threads simultaneously. When a thread enters synchronized code, the thread obtains the lock of the object or class depending on whether the code is non-static or static. So, both the class methods and the instance methods may be marked synchronized. Any code block within a method can be synchronized by enclosing it in {}, so choice C is correct.

Variables and classes cannot be synchronized, so choices D and E are incorrect.

Feedback to Author
Question
28
What will be the result of attempting to compile and run the following program?

class Test implements Runnable
{
public void run()
{
String str = "hello";
synchronized (str)
{
try
{
System.out.print(Thread.currentThread().getName());
Thread.sleep(500);
System.out.print(Thread.currentThread().getName());
}
catch(InterruptedException e) { }
}
}
public static void main (String[] args)
{
new Thread(new Test(), "A").start();
new Thread(new Test(), "B").start();
}
}
Choose one answer.
a. Prints "ABAB" or "BABA"
b. Prints "AABB" or "BBAA"
c. Result cannot be predicted
d. Compiler Error
e. An exception is thrown
Choice B is the correct answer.

Here the str string is a String literal. Java holds the String literals in a pool and shares them. So the same String object is shared between both threads. Now the thread which starts first gets the lock of the String object and goes to sleep.

Here, the lock is not released till the thread finishes executing its run() method. The second thread can only enter the synchronized code when the first thread completes its execution.

Hence, the output is either "AABB" or "BBAA", depending on which thread starts first.

Feedback to Author
Question
29
What will be the result of compiling and running the following program?

class TestThread extends Thread
{
private int i;
static String s=new String("hi");

TestThread(String s)
{
super(s);
}
public String getObj()
{
return s;
}
public void run()
{
try
{
synchronized(this.getObj())
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
}
}
catch(InterruptedException e) {}
}
public static void main(String[] args)
{
TestThread t1 = new TestThread("A");
TestThread t2 = new TestThread("B");
t1.start();
t2.start();
}
}
Choose one answer.
a. Prints "AABB" or "BBAA"
b. Prints "ABAB" or "BABA"
c. Prints nothing
d. Compiler error
e. Exception at runtime
Choice A is the correct answer.

The String object reference s is static, so it is shared by both threads t1 and t2.

Now, the hread which starts first gets the lock of the String object and goes to sleep. Here, the lock is not released till the thread finishes its run() method, so the thread which starts second can only enter the synchronized code when the first thread completes its execution. So the output is either "AABB" or "BBAA" depending on which thread starts first.

References: http://java.sun.com/Series/Tutorial/jav ... eaded.html

Feedback to Author
Question
30
What is the output when the following code is run ?

enum Operator {
PLUSONE {
int operate(int x) {
return ++x;
}
},
MINUSONE {
int operate(int x) {
return --x;
}
},
ABS {
int operate(int x) {
return Math.abs(x);
}
};
abstract int operate(int x);
}

public class T {
public static void main(String[] args) {
int x = -10;
for (Operator o : Operator.values()) {
System.out.println(o + " of " + x + " = " + o.operate(x));
}
}
}
Choose one answer.
a. Compilation error
b. Exception at run time
c. PLUSONE of -10 = -9
MINUSONE of -10 = -11
ABS of -10 = 10
d. PLUSONE of -10 = -10
MINUSONE of -10 = -10
ABS of -10 = 10
e. None of the above
Correct answer is choice C.

Explanation :
You can give each enum constant a different behavior for some method by declaring the method abstract in the enum type and overriding it with a concrete method in each constant. Such methods are known as constant-specific methods. Here, the method called operate has been overridden by each Operator constant.

Each enum constant is followed by an opening curly brace, one or more methods and then a closing curly brace. It is important to remember that a semi-colon is required after the last enum constant.

Invoking the values() method on an enum returns an array of all the values in that type. Here, we iterate through the array using the enhanced for loop.

Want to know more about enums?
http://java.sun.com/docs/books/jls/thir ... s.html#8.9
http://java.sun.com/j2se/1.5.0/docs/gui ... enums.html

Feedback to Author
Question
31
What is the output when the following code is run.

class Test
{
public static void main(String[] args)
{
String s1=new String("123");
StringBuffer s2=new StringBuffer("456");
Integer i=add(s1,s2);
System.out.println(i);
}
private static int add(Object... values)
{
int i=0;
for (Object s : values)
{
i+= Integer.parseInt(s.toString());
}
return i;
}
}
Choose one answer.
a. Compilation error
b. 579
c. 123456
d. 456
e. 123
f. Exception at runtime
Correct answer is choice B.

Explanation:
Variable arguments (varargs) allow you to specify that a method can take multiple arguments of the same type and don't require that the number of arguments be predetermined.

A method can have at most one parameter that is a vararg, it must be the last parameter taken by the method, and it is denoted by the object type, a set of ellipses (... ), and the name of the variable.

When you specify a variable-length argument list, it is read as "create an array of type <type of varargs>". Here, the add() method takes a vararg of Object type, so you can pass any object(s) to this method. We pass the String and StringBuffer objects as the arguments, so they are received in the Object array called values. We iterate through this array, using the enhanced for loop. Invoking toString() on the array elements yields the String equivalents, "123" and "456". These strings are then converted into the int primitives 123 and 456 by calling the Integer.parseInt() method. The sum of 123 and 456 is calculated as 579 and returned to the main method. The value is then printed out in the main method.

Refer to http://java.sun.com/j2se/1.5.0/docs/gui ... rargs.html for more information on how to use varargs

Feedback to Author
Question
32
Which of the following statements is true about the Animal and the Lion classes below?

class Animal
{
protected static int refCount = 0;
public Animal()
{
refCount++;
}
void runFast() { }
static int getRefCount()
{
return refCount;
}
}

class Lion extends Animal
{
public void runFast() throws RuntimeException { } //line A
public int getRefCount() // line B
{
return refCount;
}
}
Choose one answer.
a. Compilation error at line A.
b. Compilation error at line B.
c. Compilation succeeds, but a runtime exception is thrown if the runFast() method is ever called on an instance of the Lion class.
d. Compilation succeeds, but a runtime exception is thrown if the getRefCount() method is ever called on an instance of the Lion class.
Choice B is the correct answer.

Static methods may not be overridden to be non-static, and vice versa. So, compilation fails at line B.

Choice A is incorrect because there is no compiler error at line A. A method with no access modifier may be overridden to be protected or public; also, there is no restriction in throwing unchecked exceptions from overriding methods.

Choices C and D are incorrect because they are not valid statements; the code does not even compile.

More information is available at http://java.sun.com/docs/books/jls/thir ... ml#8.4.8.1

Feedback to Author
Question
33
What will be the result of attempting to compile and run the following program?

class Test
{
public static void main(String[] args)
{
int[] i = {1,2,3,4,5};
float[] j = new float[5];
for (int k=0;k < j.length(); k++)
{
i[k] = (char)j[k];
System.out.println(i[k]);
}
}
}
Choose one answer.
a. Compiler error - char cannot be assigned to int
b. Compiler error - Array j is not initialized
c. ArrayIndexOutOfBoundsException at runtime
d. Prints 0 five times
e. Prints 0.0 five times
f. None of the above
Choice F is the correct answer.

This program does cause a compiler error. The reason for the error is that you are invoking a length() method on an array. Arrays have an instance variable named length, but no method by that name. Apart from this, there are no other errors in this program. char can be assigned to int, the ASCII value of a character variable can be assigned to an integer variable.

The elements of array j are initialized to 0.0, once it is created. Thus, choices A and B do not apply.

If length had been accessed as an instance variable instead of a method, it would have printed 0 five times.

More information about arrays is available at http://java.sun.com/docs/books/jls/thir ... rrays.html

Feedback to Author
Question
34
What is the result of compiling and running the following program?

class A
{
int x=5;
}
class B extends A
{
int x=6;
}

public class CovariantTest
{
public A getObject()
{
return new A();
}
public static void main(String[] args)
{
CovariantTest c1=new SubCovariantTest();
System.out.println(c1.getObject().x);
}
}
class SubCovariantTest extends CovariantTest
{
public B getObject()
{
return new B();
}
}
Choose one answer.
a. Does not compile
b. Throws ClassCastException
c. Prints 5
d. Prints 6
Choice C is the correct answer.

Overriding is only for methods, not for variables. Variables are always chosen at compilation time, depending on the declared type of the invoking object. Here, the return type of c1.getObject() is class A, so the variable accessed will be of class A, and not of class B.

There are no compiler errors or exceptions here, since it is a perfectly legal example of Covariant return types, i.e., the return type of the overriding method is a subclass of the return type of the overridden method.

To know more about the covariant return types feature, refer to http://java.sun.com/developer/JDCTechTi ... t1201.html

Feedback to Author
Question
35
Given the following enum definition.

package pack1;
public class EnumClass
{
public enum MyEnum { A, B, C };
}

Which of the following code excerpts must be (independently) inserted above the following class definition so that it compiles and runs without errors? Select four choices.

class Test
{
public static void main(String[] args)
{
for(MyEnum o : MyEnum.values())
System.out.println(o);
}
}
Choose at least one answer.
a. import static pack1.EnumClass.MyEnum;
b. import pack1.EnumClass.MyEnum;
c. import pack1.EnumClass.*;
d. import static pack1.EnumClass.MyEnum.*;
e. import pack1.EnumClass.MyEnum.*;
f. import static pack1.EnumClass.*;
Choices A, B, C and F are the correct answers.

Enumerated values are public, static, and final. So they can be statically imported.

Since the MyEnum enum is declared inline within a class, it is the static member of the EnumClass class. To import the static members of a class, we can use the import static packagename.classname.*; statement, so choice F is correct.

To import a particular static member x, we can use the import static packagename.classname.x; statement, so choice A is also correct.

Choices B and C are correct because you can use the normal import statement on the class containing the enums, to import them.

Choices D and E are incorrect because they are using the enum.* syntax, which is incorrect.

To know more about static imports, refer to

http://java.sun.com/docs/books/jls/thir ... html#7.5.3
http://java.sun.com/j2se/1.5.0/docs/gui ... mport.html

Feedback to Author
Question
36
What will be the result of compiling and running the following code?

class A
{
int i;
A(){}
}

class B extends A
{
B(short i)
{
this.i=i;
System.out.print("short");
}

B(float j)
{
i=(int)j;
System.out.print("float");
}
}

public class Test extends B
{
Test()
{
super(4);
}
public static void main(String[] args)
{
System.out.print(new Test().i); //line 1
}
}
Choose one answer.
a. Code does not compile
b. Code throws Exception at runtime
c. Prints "float4"
d. Prints "short4"
e. Prints "0"
Choice C is the correct answer.

The super call made from the Test constructor looks for a constructor with an int argument in the superclass because an integer literal is, by default, of type int. There is no such constructor in the superclass, so it calls the constructor which matches the best.

Since short cannot hold an int, the constructor with the short argument is not called. The constructor with the float argument is called because float can hold an int.

Read more about invoking superclass constructors at http://www.javaworld.com/jw-10-2000/jw- ... ctors.html

Feedback to Author
Question
37
What will be the result of compiling and running the following code?

abstract class a
{
final void f() {}
abstract synchronized void g();
static void h(){}
a(){}
public static void main(String[] args)
{
a obj;
}
}
Choose one answer.
a. Compiler error - Abstract classes cannot have final methods.
b. Compiler error - Abstract classes cannot have constructors.
c. Compiler error - Abstract classes cannot have static methods.
d. Compiler error - Abstract methods cannot be synchronized.
e. Compiler error - Abstract classes cannot be instantiated.
f. The code compiles and runs without errors.
Choice D is the correct answer.

The combination of the "abstract" and "synchronized" modifiers is not allowed. So the code does not compile.

Abstract classes are allowed to have final methods.Methods cannot be declared abstract and final at the same time, though. Abstract classes can have static methods and constructors. Here, obj is declared as a variable of type a, but no object has been created. So choice E is also not true.

Reference: http://java.sun.com/docs/books/jls/thir ... html#35674

Feedback to Author
Question
38
What will be the result of compiling and running the following code?

import java.util.*;
public class Test
{
public abstract class InnerTest
{
abstract void f();
}
public static void main(String[] args)
{
Test t=new Test();
Test.InnerTest test=t.new InnerTest()
{
public void f()
{
System.out.println("Inner f");
}
};
}
}
Choose one answer.
a. Does not compile
b. Prints "Inner f"
c. Throws an exception at runtime
d. Compiles and runs, but produces no output
e. None of the above
Choice D is the correct answer.

This code compiles fine as it is allowed to declare an inner class as abstract. Note that you can only instantiate concrete subclasses of the abstract inner class. Here, the concrete anonymous subclass of the InnerTest class implements the f() method, so we can instantiate the subclass. However, there is no output produced since the f() method is not invoked anywhere.

Feedback to Author
Question
39
What is the output when the following code is run.

class ETest
{
public static void main(String[] args)
{
int i=1;
try
{
for ( ; true ; i-- )
{ //1
if(i /--i <=0)break;//2
}
}
catch(ArithmeticException a)
{
System.out.println("1");
}
catch(RuntimeException r)
{
System.out.println("2");
}
catch(Exception e)
{
System.out.println("3");
}
finally
{
System.out.println("4");
}
}
}
Choose one answer.
a. 4
b. 2
4
c. 1
4
d. 3
4
e. Compilation error
f. No output
Correct answer is choice C.

Explanation:
When an integer is divided by zero, it causes ArithmeticException to be thrown which gets caught by the first catch block itself. "1" is printed.

RuntimeException is the superclass of ArithmeticException and Exception is the superclass of RuntimeException.

Catch blocks must be ordered from the specific one towards the general ones (for the code to compile without errors), so the catch block for ArithmeticException must be followed by the catch block for RuntimeException, which in turn would be followed by that for Exception. The finally block appears after all the catch blocks. So "4" would be printed after "1"

Feedback to Author
Question
40
What will be the result of attempting to compile and run the following code?

class MyException extends Exception{}

class Test
{
void f() throws MyException
{
throw new MyException();
}
public static void main (String[] args) throws MyException
{
MyException e1=null;
Test t=new Test();
try
{
t.f();
}
catch (MyException e)
{
e1=e;
System.out.print("catch");
}
finally
{
System.out.print("finally");
throw e1;
}
System.out.print("End");
}
}
Choose one answer.
a. Prints "catch"
b. Prints "catch finally"
c. Does not compile
d. The program terminates without any output
e. Prints "catch finally end"
f. None of the above
Choice C is the correct answer.

This program does not compile because the compiler finds that the "System.out.print("End")" statement is unreachable.

The exception thrown from the f() method propagates to the main method, where it is handled by the catch block, and then it moves to the finally block. Here you are rethrowing the exception, which means the next statement after finally block will never be executed. So the compiler gives the error - Unreachable statement. There are no other errors in this program. The main and f() methods correctly declare that they throw MyException. However, since the code does not compile, all other choices are incorrect.

Want to know more about exceptions?
Check out http://java.sun.com/docs/books/jls/thir ... tions.html
http://java.sun.com/docs/books/tutorial ... dling.html

Feedback to Author
Question
41
What will be the result of attempting to compile and run the following code?

class Test
{
void f() throws MyException
{
throw new MyException();
}

public static void main (String[] args) throws MyException
{
MyException e1;
Test t=new Test();
try
{
t.f();
}
catch (MyException e)
{
e1=e;
System.out.print("catch1 ");
}
finally
{
try
{
throw e1;
}
catch(Exception ex)
{
System.out.print("catch2 ");
}
}
System.out.print("End");
}
}
Choose one answer.
a. Prints "catch1 catch2"
b. Prints "catch1"
c. Prints "catch1 catch2 End"
d. Prints "catch1 End"
e. Does not compile
f. None of the above
Choice E is the correct answer.

The code does not compile because the compiler complains that the variable e1 may not be initialized. This is a tricky question which tries to confuse you with a nested try/catch, but the real problem is elsewhere. Remember that the local variables are not initialized, by default. Here, if you initialize e1 to null or any other valid value, the code compiles and prints "catch1 catch2 End".

Want to know more about exceptions?
Check out http://java.sun.com/docs/books/jls/thir ... tions.html
http://java.sun.com/docs/books/tutorial ... dling.html

Feedback to Author
Question
42
What is displayed when the following code is compiled and executed?

long val = 2;
switch(val)
{
default: System.out.println("default");
case 1: System.out.println("1");
case 2: System.out.println("2");
}
Choose one answer.
a. Prints - default
b. Prints - 2
c. Fails to compile because there are no break statements in the case clauses
d. Fails to compile because the default clause cannot appear before the cases
e. None of the above
Choice E is the correct answer.

Only the following data types are valid arguments for switch statement- byte, short, char, int, and enum constants. Thus, passing the long variable as the switch argument causes a compiler error. Therefore, choices A and B are incorrect.

Choice C is incorrect because break statements are not mandatory after cases. The default statement can appear before the case statements, so choice D is also incorrect.

More information is available at http://java.sun.com/docs/books/jls/thir ... html#14.11

Feedback to Author
Question
43
How many times will "Test" be printed, when the following loop is executed?

for (int k = 1; k < 10; k++)
{
if (k % 2 == 1)
continue;
System.out.println("Test");
}
Choose one answer.
a. 0
b. 4
c. 5
d. 6
Choice B is the correct answer.

The value of k will start from 1 and go up to 9. Whenever the continue statement is encountered, the loop will start again without printing "Test". k%2 will be 1, whenever k will be odd. Thus "Test" will be printed for the following values of k: 2, 4, 6, and 8. Hence, "Test" will be printed four times.

Reference: http://java.sun.com/docs/books/jls/thir ... html#14.16

Feedback to Author
Question
44
What will be the result of compiling and running the following code? (Assume that assertions are enabled at compile time as well as at runtime.)

class Test
{
String f(int i)
{
switch (i)
{
case 0: return "A";
case 1: return "B";
case 2: return "C";
default: assert false;
}
}
public static void main(String[] args)
{
Test t = new Test();
for (int i = 0; i < 4; i++)
{
System.out.print(t.f(i));
}
}
}
Choose one answer.
a. Prints "ABC" and throws AssertionError
b. Prints "ABC" and throws AssertionException
c. Prints "ABC" and exits without any error
d. Compilation error
e. None of the above
Choice D is the correct answer.

This code does not compile because if the method containing the switch statement is declared with a non void return type and if no return statement appears after the switch statement, then each case of the switch must have a return statement or a throw statement.

Here, there is no return statement after the switch statement, so all the cases should have had a return or throw statement. The default case has no return statement here, so the compiler will complain because assertions might not always be enabled.

Here, instead of assert false, you can use throw AssertionError which will be executed even if assertions are disabled.

Feedback to Author
Question
45
Given the code below, which access modifiers (public, protected, or private) can legally be placed before the myMethod() method on line 3, if no other changes are made to the code? If line 3 is left as it is, which keywords can legally be placed before the myMethod method on line 8?

1. class HumptyDumpty
2. {
3. void myMethod() {}
4. }
5.
6. class HankyPanky extends HumptyDumpty
7. {
8. void myMethod() {}
9. }
Choose one answer.
a. private or nothing (default) on line 3. Nothing (default) or protected or public on line 8.
b. public or protected on line 3. private or nothing (default) on line 8.
c. Nothing (default) or protected or public on line 3. private or nothing (default) on line 8.
d. public on line 3 and private on line8.
Choice A is the correct answer.

The basic principle is that a method cannot be overridden to be more private. Since the method is being overridden to be friendly (default access / no modifier), it can only be private or friendly in the superclass. Secondly, if the method in superclass is left as it is (i.e., friendly access), the method in subclass can be friendly, protected, or public.

Learn more about overriding at
http://java.sun.com/docs/books/jls/thir ... html#8.4.8

Feedback to Author
Question
46
How many objects will be eligible for garbage collection after the execution of line 9 in the following code?

1. public class GCTest
2. {
3. public static void main(String[] args)
4. {
5. Double x = new Double(0);
6. for(int i=0; i < 5; i++)
7. for(int j=0; j < 3; j++)
8. x = new Double(i+j);
9. int a = x.intValue();
10. System.out.println("a = " + a);
11. }
12. }
Choose one answer.
a. 8
b. 14
c. 15
d. 16
Choice C is the correct answer.

There will be 15 objects eligible for garbage collection after the execution of line 9.

This code creates 16 objects of type Double. Out of which, 15 Double objects are created by the iterations of the nested for loops at lines 6 and 7, and one more Double object is created at line 5. The very first iteration of the loop makes the object created at line 5 eligible for garbage collection. With each iteration of the loop, a new object is created and assigned to 'x', and the old (or previously created) object becomes eligible for garbage collection. Only the most recently created object (for i=4 and j=2) is not eligible for garbage collection.

Thus, out of the created 16 objects (including the one created at line 5), a total of 15 objects have become eligible for garbage collection after the execution of line 9.

Actually, as explained in the earlier paragraph, each iteration of the loop (line 8) makes the previously created object eligible for garbage collection. Thus, by the time both nested loops finish their execution (before execution of line 9), a total of 15 objects have become eligible for garbage collection. The execution of line 9 itself does not affect garbage collection in any way. Want to know more?

You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Feedback to Author
Question
47
What will be the result of compiling the following programs and executing it using the following command - java Child?

Parent.java
-----------

package p;

public class Parent
{
protected int x=9;
}

Child.java
----------

package other;
import p.*;

1. class Child extends Parent
2. {
3. public static void main(String[] args)
4. {
5. p.Parent p=new p.Parent();
6. System.out.println(p.x);
7. }
8. }
Choose one answer.
a. Prints 9
b. Compiler error at line 5
c. Compiler error at line 6
d. None of the above
Choice C is the correct answer.

You cannot access the protected variable in the Parent class from the Child class using the parent class reference. The Child class does inherit the variable x, but it can be accessed only by an object reference of the Child class. There is no error at line 5. It is legal to refer to a class as packagename.classname even if the package is already imported. So choice B is incorrect.

Check out access control rules at
http://java.sun.com/docs/books/jls/thir ... s.html#6.6

Feedback to Author
Question
48
Which of the following is the most appropriate code snippet that can be inserted at line 3?

1. public void setFrequency(int frequency)
2. {
3. // What should be inserted here?
4. this.frequency = frequency;
5. }
Choose one answer.
a. assert ((0 < frequency) && (frequency <=60));
b. assert ((0 < frequency) && (frequency <=60)) : "Frequency out of range";
c. if(frequency <= 0 || frequency > 60)
throw new IllegalArgumentException("Frequency out of range");
d. if(frequency <= 0 || frequency > 60)
throw new Exception("Frequency out of range");
e. None of these
Choice C is the correct answer.

The setFrequency method is a public method. Java insists that the assertion mechanism should not be used for checking parameters of a public method. Checking validity of the passed parameters must be done by the method under all conditions. This is known as checking preconditions. The assertion mechanism is inappropriate for such preconditions, as the enclosing method guarantees that it will enforce the argument checks, whether or not assertions are enabled. Hence, both choices A and B are inappropriate.

Choice D is incorrect because if a method throws a checked exception (Exception, in this case), it must be caught or declared in the throws clause of the method. The given example does not provide for either of these.

IllegalArgumentException is a RuntimeException and is unchecked. Hence, choice C is the most appropriate code snippet that can be inserted at line 3.

Want to know more?

Correct and effective usage of assertions is not only important for the SCJP exam, but also while writing code in real life applications.

You can read more about usage of assertions with dos and don'ts at- http://java.sun.com/j2se/1.4/docs/guide ... ssert.html

Feedback to Author
Question
49
Which is the most appropriate way to handle invalid method arguments passed to a public method?
Choose one answer.
a. Throw AssertionError
b. Throw IllegalStateException
c. Throw IllegalArgumentException
d. Throw InvalidArgumentException
Choice C is the correct answer.

IllegalArgumentException is thrown to indicate that a method has been passed an illegal or inappropriate argument. A is incorrect because it is inappropriate to use assertions to check preconditions in a public method. Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled.

public precondition checking should still be performed by checks inside methods that result in particular, documented exceptions, such as IllegalArgumentException and IllegalStateException.

B is incorrect here because IllegalStateException signals that a method has been invoked at an illegal or inappropriate time, it is not used to indicate that the arguments are invalid.

D is incorrect because there is no exception called InvalidArgumentException.

More information is available at http://java.sun.com/j2se/1.4.2/docs/gui ... ssert.html
http://java.sun.com/j2se/1.4.2/docs/api ... ption.html

Feedback to Author
Question
50
What will be printed on standard output if the following class is executed using the command "java Test 1 two 3" ?

public class Test
{
static public void main(String[] args)
{
try
{
int k = Integer.parseInt(args[1]);
System.out.println(args[k]);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Choose one answer.
a. 1
b. two
c. NumberFormatException
d. ArrayIndexOutOfBoundsException
e. Code does not compile
Choice C is the correct answer.

In Java, command line arguments are stored in the args array which is an argument to the main method. The index of the args array starts with 0 and the first command line argument is the word after the class name. Thus, args[0] will be 1 and args[1] will be "two".

The parseInt() method of the Integer class parses the String argument to the int type. The String passed to the parseInt() method should have only digits, with an exception that it can start with '-' to indicate a negative number. Otherwise, NumberFormatException will be thrown. Thus, when "two" is passed to the parseInt() method, NumberFormatException will be thrown.

Please note that there is nothing wrong with the definition of main, the static word can come after or before public keyword.

For more information, refer to
http://java.sun.com/j2se/1.5/docs/api/j ... teger.html

Feedback to Author
Question
51
What value is printed out by executing the following code?

class MyClass
{
public static void main(String[] args)
{
double d = 2.7;
Box b = new Box();
b.doMinus(d);
System.out.println(d);
}
}
class Box
{
public double d;
public void doMinus(double d)
{
d = d - 1.0;
}
}
Choose one answer.
a. 2.7
b. 1.7
c. 0.0
d. -1.0
Choice A is the correct answer.

In Java, all parameters are passed by value. In case of primitives, the copy of the variable is passed, while in case of object references, it's the copy of the reference that is passed.

When the argument is a primitive type, pass-by-value means that the method can change the value of the passed argument (in the method scope) but, the called method cannot change the value of the variable in the calling method.

When the argument is of reference type, pass-by-value means that the method cannot change the object reference, but can invoke the object's methods and modify the accessible variables within the object.

In the example above, d is passed as value, hence the change done in the doMinus() method doesn't reflect on d outside the doMinus() method. Thus, the value printed is 2.7.

Feedback to Author
Question
52
What will happen when you attempt to compile and run the following code? (Assume that the code is compiled and run with assertions enabled.)

1. public class AssertTest
2. {
3. public static void main(String[] args)
4. {
5. for(int i=0;i <10;i++)
6. {
7. try
8. {
9. assert i%2==0 : i--;
10. System.out.println("Even number : " + i);
11. }
12. catch(AssertionError ae)
13. {
14. System.out.println("Odd number : " + ++i);
15. }
16. }
17. }
18. }
Choose one answer.
a. It will print odd and even numbers from 0 to 9 correctly (0 even and 1 odd).
b. It will print odd and even numbers from 0 to 9 incorrectly (0 odd and 1 even).
c. Compilation error at line 9.
d. Compilation error at line 10.
e. It will result in an infinite loop.
Choice A is the correct answer.

The code will compile successfully and it will print odd and even numbers from 0 to 9 correctly, without reversing even and odd.

Let's look at the execution of the code. The assert statement at line 9 asserts that "i%2==0" must be true, which will be true for all the even numbers in the range 0 to 9 (0, 2, 4, 6, and 8), and false for all the odd numbers in the range 0 to 9 (1, 3, 5, 7, and 9). When the assert statement is evaluated to true, the second expression on the right hand side of the colon is not evaluated. On the other hand, when the assert statement is evaluated to false, the expression on the right hand side of the colon is evaluated and an AssertionError is thrown.

When the for loop starts with i=0, the assert condition at line 9 is evaluated to true, hence the other expression i-- is not evaluated, the value of i (0 here) is printed at line 10. Next, i is incremented to 1 in the next iteration of the for loop. The assert condition at line 9 is false in this case, hence the expression i--is evaluated (i becomes 0) and an AssertionError is thrown. The print statement at line 10 is not executed in this case. The catch statement at line 12 catches this error and the print statement at line 14 increments i with ++i and prints its value (which is 1 in this case). The same process is repeated for all the numbers, thus effectively printing all the even and odd number correctly.

The key here lies in understanding when the right-hand side expression of an assert statement gets evaluated. It gets evaluated *only* when the boolean left-hand side expression is evaluated to false. Hence, the loop will not result in an infinite loop.

To know more about the assert statement, refer to http://java.sun.com/docs/books/jls/thir ... html#14.10

Feedback to Author
Question
53
In the following code, which lines do not use assertions appropriately? Select two choices.

1. public class AssertDemo
2. {
3. public static Boolean message()
4. {
5. System.out.println("Error!!!");
6. return new Boolean("true");
7. }
8. public static void main(String[] args)
9. {
10. boolean b = false;
11. assert b : message();
12. int x = -5;
13. assert (x+1) > 0;
14. assert x > 0 : (x = x * -1);
15. assert !b;
16. while(true)
17. {
18. System.out.println(x);
19. assert x-- > 0;
20. }
21. }
22. }
Choose at least one answer.
a. Line 11
b. Line 13
c. Line 14
d. Line 15
e. Line 19
Choices C and E are the correct answers.

The lines 14 and 19 do not use assertions appropriately. Note that all these assertions are legal as far as syntax is concerned, and they will all compile without any error.

The assert statement should not have any side effect; they should not alter value of any variable, as it is possible to disable assertions. At line 14 the assert statement -

assert x > 0 : (x = x * -1);

alters the value of the variable x, and hence it causes an undesired side effect and thus it is an inappropriate use of assertions. Hence, choice C is correct.

Likewise, the assert statement at line 19 -

assert x-- > 0;

also alters the value of the variable x.

Moreover, it tries to alter the control flow of the execution. Both these are inappropriate usages of assertions. Hence, choice E is correct.

None of the statements at line 11, 13 or 15 change the value of any of the variables. Hence, none of them is inappropriate. Also, note that it is perfectly legal to call a method which returns a value (anything except void) on the right hand side of the colon of an assert statement. Note that void does not denote a value but the absence of a value.

Besides knowing the correct syntax for assertions, it is important to understand what is appropriate and inappropriate use of assertions.

Want to know more?

You can read more about assertions at -
http://java.sun.com/j2se/1.4/docs/guide ... ssert.html

Feedback to Author
Question
54
What will happen when you attempt to compile and run the following code?

int Output = 10;
boolean b1 = false;
if((b1 == true) && ((Output += 10) == 20))
{
System.out.println("We are equal " + Output);
}
else
{
System.out.println("Not equal! " + Output);
}
Choose one answer.
a. Compilation error
b. Prints "We are equal 10"
c. Prints "Not equal! 20"
d. Prints "Not equal! 10"
Choice D is the correct answer.

The output will be "Not equal! 10".

Please note that && is short-circuit logical AND operator. If the first operand (before &&) is false (or evaluated to false), then the other operand will not be evaluated.

This illustrates that the Output += 10 expression calculation was never performed because the processing stopped after the first operand was evaluated to false.

If you change the value of b1 to true, processing occurs as you would expect and the output is "We are equal 20".

More information is available at http://java.sun.com/docs/books/jls/thir ... .html#5247

Feedback to Author
Question
55
What will happen if you compile and run the following code?

public class MyClass
{
public static void main(String[] args)
{
int i = 10;
int j = 10;
boolean b = false;
if( b = i == j)
System.out.println("True");
else
System.out.println("False");
}
}
Choose one answer.
a. Compilation error
b. Throws an exception
c. Prints "True"
d. Prints "False"
Choice C is the correct answer.

Please note that the conditional operators have higher precedence than assignment operators. Thus, first, i == j will be compared, which will return true. Then b will be assigned true and if(true) will be called. This will print "True".

There is no compiler error or exceptions caused, hence choices 1 and 2 are incorrect.

Feedback to Author
Question
56
Which of the following statements are true? Select two choices.
Choose at least one answer.
a. As soon as the reference count for an object reaches zero, it will be immediately garbage collected.
b. The finalize() method will not be invoked more than once by the JVM on the same object.
c. The finalize() method cannot be overloaded.
d. The garbage collection implementation is JVM-dependent.
e. If the finalize() method is overridden, a call to the super class's finalize() method is inserted automatically by the compiler.
Choices B and D are the correct answers.

As specified by the Java API documentation, the finalize() method is never invoked more than once by a Java virtual machine for any given object. Also, the garbage collection indeed is implementation-dependent. This is what the Java Virtual Machine Specification (JVMS) has to say about memory management -

"The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements."

Choice A is incorrect because when the reference count for an object reaches zero, it becomes eligible for garbage collection but that *does not* necessarily mean that it will be immediately garbage collected.

It is perfectly legal to overload the finalize() method like any other method. However, the JVM will always invoke the default, no arguments finalize() method. Hence choice C is incorrect.

Choice E is incorrect because if you override the finalize() method, you must explicitly call the superclass' finalize() method. The compiler *does not* automatically insert this call. Want to know more?

You can read more about garbage collection at - http://java.sun.com/docs/books/performa ... GC.fm.html
Also, the API documentation of the Object class contains the necessary information about the finalize() method -
http://java.sun.com/j2se/1.4/docs/api/j ... bject.html

Feedback to Author
Question
57
Insert the correct code at #1 so that follwoing code compiles and runs fine.

public class MyClass
{
public static void main(String[] argv) { }
void amethod(int i) { }
}
class MySubclass extends MyClass
{
#1
}
Choose at least one answer.
a. protected void amethod(int i) throws Exception {}
b. int amethod(float i){return 0;}
c. void amethod(int i) throws RuntimeException {}
d. public int amethod(int i) {return 0;}
Correct answer are choice B and C.

Explanation:
For valid overloading, the argument list of the methods must be different, the return type may or may not differ. So choice B is a valid way to overload the amethod method in the MyClass class. The access modifier does not matter in overloading.

Choice C is a valid way to override the amethod method, since the return type and arguments match. Access modifier is allowed to be the same or more public in overriding, so that is also not a problem. Though it is not allowed to throw new checked exceptions, throwing unchecked exceptions is not a problem in overriding. Thus, choice C is correct.

Choice A is not a valid way to override since it throws Exception which is not thrown by the original method in the MyClass class.

Choice D is not a valid override or overload since the arguments match and only the return type is different.

More information about overloading is available at
http://java.sun.com/docs/books/jls/thir ... tml#236017

Feedback to Author
Question
58
Choose the option that has the following classes arranged in descending order of tight coupling.

1# class BillGenerator{public void print(Customer c,Bill b){}}

2# class BillGenerator{public void print(String custName, String address, String[] billDetails){} }

3# class BillGenerator{Bill b;Customer c;public void print(String custNo, String billNo){}}

4# class BillGenerator{Bill b; public void print(Customer c, String billNo)}
Choose one answer.
a. 1#
2#
3#
4#
b. 2#
1#
4#
3#
c. 3#
4#
1#
2#
d. 4#
3#
1#
2#
Correct answer is choice C.

Explanation:
Coupling indicates the degree of dependence among components. Higher coupling tends to indicate poor design of classes, since it makes modifying parts of the system difficult, as modifying a component affects all the components to which the component is connected.

Here, #3 indicates the highest level of coupling, since the Bill and the Customer components have been made part of the BillGenerator component. The BillGenerator component only needs to receive the information that it needs to print. Knowledge of the other data structures must not be part of the BillGenerator component.

#4 comes next in the order of high coupling, since the Bill module is still a part of the BillGenerator module.

#1 comes next, since the Customer and Bill modules are no longer part of the BillGenerator module, but the latter is still dependent on the data structure of the other two components, since the information to be printed needs to be passed.

#2 indicates the lowest coupling and hence the best design of all, since only the required information is passed to the print method.

More information about coupling and other related concepts is available at
http://satc.gsfc.nasa.gov/support/STC_A ... ly_oo.html

Feedback to Author
Question
59
What will be the result of attempting to compile and run the following program?

interface Inter{}
class Base implements Inter {}
class Derived extends Base{}
public class Test
{
public static void main(String[] args)
{
Base b=new Base();
Derived d=new Derived();
Inter i=(Base)b; //1
i=(Base)d; //2
Derived bd=(Derived)b; //3
b=(Base)i; //4
}
}
Choose one answer.
a. Compiler error at line 1
b. Compiler error at line 2
c. Compiler error at line 3
d. Compiler error at line 4
e. ClassCastException at runtime
f. Compiles and runs without errors
Choice E is the correct answer.

Line 3 causes ClassCastException to be thrown at runtime, since here we are trying to cast a Base class object to a Derived class type. At compile time, this will not cause an error because the casting tells the compiler that the programmer knows what he/she is doing.

There are no errors at lines 1 and 2 because a subclass object reference can be assigned to its super class/interface type variable.

Line 4 will compile because the interface type variable has been cast as Base type. Without the casting, this line would not have compiled.

Reference: http://java.sun.com/docs/books/jls/thir ... s.html#5.5

Feedback to Author
Question
60
Which of the following statements about the following code fragment are true? Select two choices.

1. public class Test
2. {
3. public static void main(String [] args)
4. {
5. print();
6. }
7.
8. public static void print()
9. {
10. System.out.println("Test");
11. }
12.
13. public void print()
14. {
15. System.out.println("Another Test");
16. }
17. }
Choose at least one answer.
a. The code compiles successfully and displays "Test".
b. Changing the code at line 13 to "public void print(int x)" will allow the code to compile correctly.
c. The code fails to compile. The compiler complains about duplicate methods.
d. Changing the return type on line 13 from 'void' to 'int' will allow the code to compile correctly.
Choices B and C are the correct answers.

The code appears to be attempting to overload the print() method.

However, the only differentiating feature between the methods is the static keyword. This is insufficient for overloading. Therefore, choice C is correct and choice A is incorrect because the code fails to compile due to duplicate methods.

Choice B is correct because the methods are different overloaded versions of the print() methods.

Choice D is incorrect because the return parameters are not sufficient to differentiate between the overloaded methods.

More about overloading is available at http://java.sun.com/docs/books/jls/thir ... html#8.4.9

Re: oracle java 6 certification exam mock questions

PostPosted: Fri Mar 02, 2012 11:01 am
by tomrff
Question
1
Choose the correct option when the following code is compiled and run.

import java.io.*;

class Test implements Serializable { }

class SerializeTest
{
public static void main(String[] args)
{
try
{
Test t=new Test();
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("Test"));
out.writeObject(t);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("Test"));
Test newt= in.readObject();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Choose one answer.
a. Compilation error.
b. Exception at runtime .
c. Compiles and run without any error.
ANSWER : A

Explanation:
An ObjectOutputStream writes primitive data types and Java objects to an OutputStream using the writeObject() method. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream.

In the given code, we create a FileOutputStream, which is the destination stream for the ObjectOutputStream. Later the object is read back using the readObject() method of ObjectInputStream.

Since the return type of this method is of Object type, it must be cast down to type Test which is not done in the above code.

More information is available at:
http://java.sun.com/developer/technical ... alization/
Incorrect

Question
2
Choose the option that has correct method name and its description.
Choose one answer.
a. Check if the file is a directory. -> isDir()
Delete a directory. -> delete()
Get an array of strings naming the files and directories in a directory. -> list()
Test whether the application can read the file. -> canRead()
b. Check if the file is a directory. -> isDirectory()
Delete a directory. -> delete()
Get an array of strings naming the files and directories in a directory. -> list()
Test whether the application can read the file. -> canRead()
c. Check if the file is a directory. -> isDirectory()
Delete a directory. -> delete()
Get an array of strings naming the files and directories in a directory. -> listFiles()
Test whether the application can read the file. -> canRead()
d. Check if the file is a directory. -> isDirectory()
Delete a directory. -> removeDir()
Get an array of strings naming the files and directories in a directory. -> list()
Test whether the application can read the file. -> canRead()
ANSWER : B

Explanation:
The isDirectory() method tests whether the file denoted by this abstract pathname is a directory.

The list() method returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

The delete() method deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

The canRead() method tests whether the application can read the file denoted by this abstract pathname.

Read about the File class at:
http://java.sun.com/j2se/1.5/docs/api/java/io/File.html
Incorrect

Question
3
Choose the option that compiles and runs fine.
Choose one answer.
a. NumberFormat currencyFormat = NumberFormat.getInstance("US");
Number number = currencyFormat.parse("$5,000.56");
b. NumberFormat currencyFormat = NumberFormat.getCurrencyInstance("US");
Number number = currencyFormat.parse("$5,000.56");
c. NumberFormat currencyFormat = NumberFormat.getInstance(Locale.US);
Number number = currencyFormat.parse("$5,000.56");
d. NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
Number number = currencyFormat.parse("$5,000.56");
ANSWER : D

Explanation:
NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers.

You can use the getCurrencyInstance(Locale) method to get the currency number format for a specific Locale. Here we need to parse the currency string for the Locale for the United States, which is given by Locale.US.

To the parse method, we need to pass the currency string in the US currency format, which is "$5,000.56". The parse method returns the extracted currency value as a Number.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... ormat.html
Incorrect

Question
4
What is the result of compiling and running the following program?

import java.util.*;
import java.util.regex.*;

class ScannerTest2
{
public static void main(String[] args)
{
String input = "10 apples 20 oranges 33 pears";
Scanner s = new Scanner(input).useDelimiter("\\d\\d\\s");
while(s.hasNext())
System.out.print(s.next());
s.close();
}
}
Choose one answer.
a. Compiler error
b. Prints 10 20 33
c. Prints apples oranges pears
d. None of these
Choice C is the correct answer.

The java.util.Scanner class makes it easier to read and parse strings and primitive types using regular expressions. In this program, the Scanner breaks the contents of a String into tokens using a delimiter pattern. You can change the delimiter that is used to tokenize the input using the useDelimiter() method of Scanner. You can pass in a String or a java.util.regex.Pattern to the method.

The hasNext() method in Scanner returns true if another token exists in the Scanner's input, which is the case until it reaches the end of the String. The next() method returns a String that represents the next token.

The regular expression "\\d\\d\\s" will find a match with any two numeric digits followed by a white space. So the tokens returned would be "apples", "oranges", and "pears". So choice C is correct while choice B is incorrect.

Choice A is incorrect because the program compiles fine.

Want to know more? Refer to the following links:
http://java.sun.com/j2se/1.5.0/docs/api ... anner.html
http://java.sun.com/developer/JDCTechTi ... 01.html#|1
Incorrect

Question
5
What is the result of compiling and running the following code ?

1. StringBuffer s1=new StringBuffer("hello");
2. StringBuffer s2=new StringBuffer("hello");
3. Float f1=9.0F;
4. Double f2=9.0;
5. System.out.print(f1.equals(f2));
6. System.out.print(s1==s2);
7. System.out.print(s1.equals(s2));
Choose one answer.
a. Prints "truetruetrue"
b. Prints "falsefalsetrue"
c. Prints "falsefalsefalse"
d. Compiler error on line 5
e. Compiler error on line 7
Choice C is the correct answer.

Even though both the Float and Double objects encapsulate the same value, the equals method returns false on line 5. This is because the equals method is overridden to return true only if the objects being compared belong to the same wrapper class, in addition to wrapping the same primitive values.

The == operator returns true only if the object references being compared refer to the same object, so line 6 results in false as the output . The StringBuffer class does not override the equals method and the default implementation of the equals method in the Object class uses the == operator for comparison. So line 7 also prints false. Since choice C is correct, all the other choices are automatically incorrect.
Incorrect

Question
6
What is the result of compiling and running the following code?

public class IntegerTest
{
public static void main(String[] argv)
{
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
Integer i3 = Integer.valueOf("3");
int i4 = i1 + i2 + i3;
System.out.println(i4);
}
}
Choose one answer.
a. Compiler error: Integer class has no constructors which take a String argument
b. Compiler error: Incorrect argument passed to the valueOf method
c. Compiler error: Integer objects cannot work with + operator
d. Prints 6
e. Prints 123
Choice D is the correct answer.

The Integer objects are unboxed to the equivalent primitive values, then added together. The result of 6 is unboxed into the Integer object referred to by i4.

Choice A is incorrect because the Integer class has a constructor that takes a String argument.

Choice B is incorrect because the argument passed to the valueOf method is correct. Since 6 is printed, choice E is incorrect.

To know more about autoboxing and unboxing, please refer to:
http://java.sun.com/docs/books/jls/thir ... tml#|5.1.7
Incorrect

Question
7
What is the result of compiling and running the following code?

class Test
{
public static void main(String[] args)
{
Character c=65; // line 1
Character d=new Character('A');
if(c>d) // line 3
System.out.println("True");
else
System.out.println("False");
}
}
Choose one answer.
a. Compiler error at line 1
b. Compiler error at line 3
c. Prints "True"
d. Prints "False"
Choice D is the correct answer.

65 is the ASCII value of the character 'A', so both c and d represent Character objects encapsulating the same char value of 'A'. So c > d is false, hence the else part is executed, which results in the output "False". Thus choice C is incorrect.

Autoboxing allows a primitive type to be automatically encapsulated into the corresponding wrapper object. So the assignment and comparison in lines 1 and 3 are perfectly valid. Thus, choices A and B are incorrect.

More about autoboxing is available at:
http://java.sun.com/developer/JDCTechTi ... 05.html#|1
Incorrect

Question
8
Which of the following expressions will evaluate to true if preceded by the following code? Select two choices.

String a = new String("hello");
String b = new String(a);
String c = a;
char[] d = { 'h', 'e', 'l', 'l', 'o' };
Choose at least one answer.
a. (a == "hello")
b. (a == b)
c. (a == c)
d. a.equals(b)
e. a.equals(d)
Choices C and D are the correct answers.

String objects can be made up of identical sequences of characters. The == operator, when used on String object references, will just compare the references and will only return true when both references refer to the same object, i.e. are aliases. So choices A and B are incorrect, while choice C is correct.

The equals() method will return true whenever the contents of the String objects are identical. So choice D is also correct. An array of char and a String are two totally different types and cannot be compared using the equals() method of the String class. So choice E is incorrect.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... tring.html
Incorrect

Question
9
What is the result of compiling and running the following program?

import java.util.Arrays;

class Split2
{
public static void main(String[] args)
{
String str = "She sells sea shells";
System.out.println(Arrays.toString(str.split("\\s")));
}
}
Choose one answer.
a. Compiler error
b. An exception is thrown at runtime.
c. Prints [She, sells, sea, shells]
d. Prints [he, ells, ea, hells]
e. Prints []
Choice C is the correct answer.

The split() method of the String class splits a string around matches of the given regular expression. The return value is a String array containing the tokens. In this case we split on the expression "\\s" and the tokens are stored in the array s.

The expression "\\s" matches whitespace and hence the tokens are "She", "sells", "sea", "shells". Thus choices D and E are incorrect.

This code compiles and runs without errors, so choices A and B are also incorrect.

public String[] split(String regex): Splits this string around matches of the given regular expression. This method works the same as if you invoked the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are not included in the resulting array. Want to know more?

Check out:
http://java.sun.com/docs/books/tutorial ... ttern.html
http://java.sun.com/j2se/1.5.0/docs/api ... tring.html
Incorrect

Question
10
What is printed when the following code is executed?

class PrintfTest
{
public static void main(String[] args)
{
double val1 = 3.91;
double val2 = 3.97;
System.out.printf("%.1f %.1f",val1,val2);
}
}
Choose one answer.
a. 3.0 3.0
b. 3.9 4.0
c. 3.9 3.9
d. 0.9 0.9
Choice B is the correct answer.

The output will be 3.9 4.0, so choices A, C and D are incorrect.

The %f specifier determines the number of decimal places displayed in the number. 0.1f would display only one decimal place. The number is rounded to the closest value. Hence the number 3.91 is displayed as 3.9 and the number 3.97 is displayed as 4.0.

You can get more information about the printf method at:
http://java.sun.com/j2se/5.0/docs/api/j ... tream.html
Incorrect

Question
11
What is the output when the following code is run.

ArrayList a=new ArrayList();
a.add("1");
a.add("2");
a.add("1");
String[] s=(String[])a.toArray(new String[0]);
for(String str:s) System.out.print(str);
Choose one answer.
a. Compilation error.
b. Exception at runtime .
c. 121 .
d. 1
ANSWER : C

Explanation:
The toArray method defined in the Collection interface is used to convert a collection to an array. The overloaded version of toArray method used in this code takes an argument, which is the type of array to which the return type is to be cast.

String[] s=a.toArray(new String[0]); The contents of the String array are then printed.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... ction.html
Incorrect

Question
12
Choose the option which when inserted at #1 makes the code compile and run.

import java.util.*;

public class Sorter
{
public static void main(String[] argv)
{
ArrayList aList = new ArrayList();
aList.add("USA");
aList.add("Russia");
aList.add("UK");
#1
}
}
Choose one answer.
a. Collections.sort(aList);
b. Collection.sort(aList);
c. aList.sort();
d. List.sort(aList);
ANSWER : A

Explanation:
The sort method in the Collections utility class can be used to sort objects of any class implementing the List interface.

public static void sort(List list)

The method sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... tions.html
Incorrect

Question
13
Choose the options which contain the correct mapping of collection type.
Choose at least one answer.
a. A dictionary (TreeMap).
b. A sorted collection of country names (HashSet).
c. An unsorted group of phone numbers (ArrayList).
d. An unsorted frequency table (HashMap).
ANSWER : A, C, D

Explanation:
A dictionary can be represented well using the TreeMap type. The dictionary has unique words in a sorted order, mapped to meanings/descriptions which may be non unique.

Map is a collection that implements key-value mappings and TreeMap gives the keys in a sorted order.

A sorted group of country names can be implemented using a TreeSet and not HashSet since TreeSet gives unique elements in a sorted order. A frequency table can be implemented using a HashMap, since it does not require sorting.

ArrayList gives an unsorted list, so it can be used to implement an unsorted group of phone numbers.
Incorrect

Question
14
What is the result of compiling and running the following code?

ConcurrentSkipListSet<String> mySet = new ConcurrentSkipListSet<String>();
mySet.add("me");
mySet.add("you");
mySet.add("your");
mySet.add("they");
mySet.add("she");
NavigableSet<String> mySet1 = mySet.headSet("m");
System.out.print(mySet1.size());
Choose one answer.
a. Prints 1
b. Prints 0
c. Prints 4
d. Compiler error
Choice B is correct.

The headset(toElement) method of NavigableSet returns a view of the portion of the set whose elements are less than toElement. There is no element in the set that is less than "m". Hence the set is empty and the size() method prints 0. Since 0 is printed all the other choices are incorrect.
Incorrect

Question
15
Which of the following must be true for the following code? Select three choices.

StringBuffer s1=new StringBuffer("test");
StringBuffer s2=s1;
StringBuffer s3=new StringBuffer("test");
Choose at least one answer.
a. s1.equals(s2)
b. s2==s1
c. s1.hashCode()==s2.hashCode()
d. s3==s1
e. s3.hashCode()!=s1.hashCode()
Choices A, B, and C are the correct answers.

The == operator returns true, when used to compare object references, if both operands refer to the same object. Here, both s1 and s2 are references to the same StringBuffer object. Since the object is the same, the equals method also returns true. So choices A and B are correct.

If two objects are equal, their hashcodes must also be equal. So choice C is also correct. Since s3 and s1 refer to two different objects, s3==s1 returns false. So choice D is incorrect.

Two unequal objects may have equal hashcodes, though it is preferable to have different hashcodes for better performance.
Incorrect

Question
16
Which of the following statements are true? Select two choices.
Choose at least one answer.
a. Just like classes, interfaces may also be generic.
b. Generic methods can be static or non-static.
c. Only a generic class can have a generic constructor.
d. Only a generic class can have a generic method.
Choices A and B are the correct answers.

It is perfectly legal to have generic interfaces, so choice A is correct. Choice B is correct because generic methods can be static or non-static, no such restrictions exist. Choices C and D are incorrect because generic methods and constructors may exist in non-generic classes.

More information is available at:
http://java.sun.com/docs/books/tutorial ... erics.html
Incorrect

Question
17
Which of these will compile and run? Select two choices.
Choose at least one answer.
a. LinkedList<Integer> l=new LinkedList<int>();
b. List<Number> l=new LinkedList<Number>();
c. LinkedList<Integer> l=new LinkedList ();
d. LinkedList<Integer> l=new <Integer>LinkedList();
e. List<Number> l=new LinkedList<Integer>();
Choices B and C are the correct answers.

The List interface is implemented by the LinkedList class. So List<Number> is the super type of LinkedList<Number>, which accepts only objects of type Number. LinkedList<Integer> declares a list that accepts only Integer objects. Assigning a LinkedList raw type to it gives warnings of unsafe operations, however, it does compile and run without errors.

Choice A is incorrect because generic parameters cannot be primitives.

Choice D is incorrect because the right hand side of the assignment uses the wrong syntax.

Choice E is incorrect because List<Number> is not a supertype of LinkedList<Integer>.

Reference:
http://java.sun.com/docs/books/tutorial ... index.html
Incorrect

Question
18
Which of the following statements are true about a Map object? Select two choices.
Choose at least one answer.
a. It cannot be assigned to a reference variable of type Collection.
b. It maps unique keys to unique values.
c. It maps unique keys to non-unique values.
d. It can be iterated using the MapIterator.
Choices A and C are the correct answers.

The Map interface does not extend the Collection interface, so Map objects cannot be assigned to a reference variable of type Collection.

A Map object maps unique keys to values, which may be duplicated. So choice C is correct, while choice B is incorrect.

Choice D is incorrect because there is no type called MapIterator.
Incorrect

Question
19
Which of the following will occur if you add a duplicate element to a HashSet t?
Choose one answer.
a. The element gets added to t.
b. An exception is thrown at runtime.
c. The code causes compiler error.
d. The add() method returns false and the element is not added to t.
Choice D is the correct answer.

The HashSet class implements Set interface; Set types do not allow duplicate elements. The add() method is called to add elements to the HashSet. The method returns true if the addition was successful and false if the element was not added. When you attempt to add a duplicate element, it is simply ignored and not added to the Set. The add() method returns false in this case. Since duplicate elements are not accepted, choice A is incorrect.

Choices B and C are incorrect because the code compiles and runs without any errors.

More information is available at:
http://java.sun.com/j2se/1.5.0/docs/api ... shSet.html
Incorrect

Question
20
Which of the following statements are true about the following code?

class Generics17
{
public static void main(String[] args)
{
List <Object> list=new LinkedList <Object>();
list.add("A");
addToList("B",list);
System.out.println(list);
}
static void addToList(Object o, List<?> l)
{
l.add(o);
}
}
Choose one answer.
a. The code will compile if List<?> is replaced by List<Object>.
b. The code will compile if List<Object> is replaced by List<String>.
c. The code will compile if List<Object> is replaced by LinkedList<Object>.
d. The code compiles fine.
Choice A is the correct answer.

The wildcard (?) character indicates unknown types, so the compiler does not allow adding or inserting into such types. So in this case, you cannot add objects to the variable type List<?> as the exact type of the List is unknown. Since String is an Object, the List <Object> type will accept String objects, so choice B is incorrect.

List <Object> is the supertype of LinkedList <Object>, so assigning an object of type LinkedList <Object> to List <Object> is legal, hence choice C is also incorrect.

Since choice A is correct, choice D is incorrect.

Reference:
http://java.sun.com/docs/books/tutorial ... cards.html
Incorrect

Question
21
Which of the following methods are defined in the java.util.Arrays class? Select two choices.
Choose at least one answer.
a. asList
b. toList
c. toArray
d. search
e. sort
Choices A and E are the correct answers.

The asList method returns a fixed-size list backed by the specified array.

The sort method sorts the specified array.

The toArray method is defined in the Collection interface and not in the Arrays class. So choice C is incorrect.

There are no methods called toList and search. So choices B and D are also incorrect.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... rrays.html
Incorrect

Question
22
Which of the following is a valid declaration of a generic method?
Choose one answer.
a. public static <X , Y extends X> boolean isPresent(X x, Y[] y){}
b. public <X , Y extends X> static boolean isPresent(X x, Y[] y){}
c. public static boolean <X , Y extends X> isPresent(X x, Y[] y){}
d. None of these
Choice A is the correct answer.

Generic methods are methods that are parameterized by one or more type parameters. Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. The type parameters must be declared before the return type of the method, but after the modifiers. This condition is satisfied by choice A, but not by choices B and C.

So choices B, C, and D are incorrect.

Reference:

http://java.sun.com/docs/books/tutorial ... thods.html
Incorrect

Question
23
Insert the correct option at #1 so that a separate thread is started which prints the string "running".

class MyRunnable implements Runnable
{
public void run()
{
System.out.println("running");
}
public void start()
{
run();
}
}

class ThreadTest
{
public static void main(String[] args)
{
#1
}
}
Choose one answer.
a. new Thread(new MyRunnable()).start();
b. new Thread(new MyRunnable()).run();
c. new MyRunnable().start();
d. new MyRunnable().run();
ANSWER : A

Explanation:
One of the Thread class constructors takes a Runnable object as its argument. This Runnable object becomes the target of the Thread i.e., the run() method of the Runnable object gets called when the thread is started.

A new thread can be started by calling the start() method of the Thread object, which ultimately causes the run() method of the Runnable target to be invoked.

There is no requirement for a start() method in the Runnable object, it is never invoked.

For more information, refer to http://java.sun.com/j2se/1.5.0/docs/api ... hread.html
Incorrect

Re: oracle java 6 certification exam mock questions

PostPosted: Fri Mar 02, 2012 11:02 am
by tomrff
Question
24
What would be the result of an attempt to compile and run the following code?

class SimpleThread extends Thread
{
public SimpleThread(String str)
{
super(str);
}
public void run()
{
for (int i = 0; i < 10; i++)
{
System.out.println(i + " " + getName());
try
{
sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
public class TwoThreadsDemo
{
public static void main (String[] args)
{
new SimpleThread("Java Programmer").start(); // line A
new SimpleThread("Java Programmer").start(); // line B
}
}
Choose one answer.
a. It will not compile because SimpleThread is a subclass of thread, but does not have a no-argument public constructor.
b. It will not compile because two separate threads in line A and line B have been given the same name "Java Programmer".
c. It will compile, but at runtime the second thread will overwrite the first thread and so the run method of the SimpleThread class will be executed only once instead of twice.
d. It will compile but will throw RuntimeException.
e. It will compile and run with success and the run method of SimpleThread class will be executed twice by two separate threads created.
Choice E is the correct answer.

The thread name does not need to be unique, so two threads with the same name can execute separately. Any String can be used as a name of the thread. Here two threads are started and executed accordingly.

There are no compiler errors in the given code, so choices B and C are incorrect.

Choice D is incorrect because no exceptions are thrown by this code.

Choice A is incorrect because there is no requirement for a no-arg constructor in a Thread subclass.
Incorrect

Question
25
What would be the result of an attempt to compile and run the following code?

public class OrderedThread
{
public static void main(String[] args)
{
MBThread first,second,third;
OrderedThread orderedThread = new OrderedThread();
first = new MBThread("One", orderedThread);
second = new MBThread("Two", orderedThread);
third = new MBThread("Three", orderedThread);
second.start(); // Line 1
first.start(); // Line 2
third.start(); // Line 3
}
public void display(String msg)
{
synchronized(msg)
{
for(int i=1;i<=20;i++)
{
System.out.println("Name= "+msg);
}
}
}
}

class MBThread extends Thread
{
String name;
OrderedThread orderT;
MBThread(String name, OrderedThread orderT)
{
this.name = name;
this.orderT = orderT;
}
public void run()
{
orderT.display(name);
}
}
Choose one answer.
a. The code compiles fine and prints Two, One, and Three in order and repeats the same for another 19 times.
b. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially. However, the order whether Two will come first, then One, and at last Three is not guaranteed.
c. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially and the behavior is guaranteed.
d. The code compiles fine and prints Two, One, and Three 20 times each in an indefinite order.
e. The code compiles fine but throws InterruptedException due to synchronization of msg String in a wrong way.
Choice D is the correct answer.

The code compiles fine but prints One, Two, and Three each 20 times in an indefinite order due to wrong synchronization mechanism applied to print them in order.

Choice A is clearly incorrect as the for loop resides within the method and there is no such code that ensures that a thread printing the value of the String 'msg' will print the value only once before another thread comes and executes the same statement.

Notice that in Line 1, 2, 3 the main thread starts the other three threads that all get the same priority of the main thread. So there is no guarantee that they will always be printed in the same order, which confirms that choice C is false.

Choice B would be true only if the display method would have been synchronized instead of the String 'msg'. There is no point in synchronizing the local String 'msg' to control the behavior of three threads.

Instead, a common static reference or 'this' reference may be tried as alternatives to achieve the behavior. So, choice D is correct.

The following article discusses important concepts about multithreading -
http://www.developerlife.com/lessons/th ... efault.htm
Incorrect

Question
26
Which of the following statements are true about the sleep method of Thread class? Select two choices.
Choose at least one answer.
a. A thread releases any locks it is holding when it is invoked on the thread.
b. It is defined as static within the Thread class.
c. A thread starts running as soon as it wakes up from the sleeping state.
d. The sleep method throws InterruptedException.
Choices B and D are the correct answers.

The sleep method is defined as static within the Thread class; it acts on the currently active thread. This method declares the InterruptedException in its throws clause.

Choice A is incorrect because when a thread sleeps, it keeps all the locks it was holding before going to sleep.

Choice C is incorrect because a thread moves from the blocked state into the runnable state when it wakes up from the sleeping state. It can start running only when the thread scheduler chooses it.
Incorrect

Question
27
Which of the following statements are true about synchronization? Select two choices.
Choose at least one answer.
a. Static methods cannot be synchronized.
b. Synchronized methods cannot make calls to non-synchronized methods.
c. A synchronized method can be overridden to be non-synchronized and vice versa.
d. When a thread is executing a synchronized method, other threads can freely access non-synchronized methods of the same object.
Choices C and D are the correct answers.

A subclass decides whether an inherited method should be marked synchronized or not.

When a thread is executing a synchronized method, other threads cannot access the synchronized methods of that object. However, there are no restrictions on accessing the non-synchronized methods of the same object.

Static methods can be synchronized. In this case, the lock is obtained on the Class object of the class. So choice A is incorrect.

Synchronized methods can call methods that are not synchronized. So choice B is also incorrect.
Incorrect

Question
28
What is the output when the following code is run.

public static void main(String[] args)
{
callMe(new char[] {'A','B','C','D'} );
}
static void callMe(char... c)
{
for(char ch : c)
System.out.println(ch);
}
Choose one answer.
a. Compilation error.
b. D
c. Exception at runtime.
d. ABCD.
ANSWER : D

Explanation:
Variable arguments (varargs) allow you to specify that a method can take multiple arguments of the same type and don't require that the number of arguments be predetermined. You can work with varargs just like you work with arrays.

An ellipsis (...) symbol is used for the varargs argument. Here, the array {'A','B','C','D'} is created as an anonymous array using the 'new' keyword. The array is received in the varargs argument c. The enhanced for loop is then used to iterate through the elements in c.

Refer: http://java.sun.com/j2se/1.5.0/docs/gui ... rargs.html for more on how to use varargs.
Incorrect

Question
29
Choose the options that have correct Exception description.
(Choose three options)
Choose at least one answer.
a. ArithmeticException : Thrown when an integer is divided by zero.
b. OutOfMemoryError : Thrown when the JVM is out of memory when trying to allocate an object .
c. : OutOfMemoryException : Thrown when the JVM is out of memory when trying to allocate an object .
d. : ClassCastException : Thrown when an attempt is made to cast an object to a subclass of which it is not an instance.
e. IllegalArgumentException : Thrown when an attempt is made to access an array element by specifying a negative index.
ANSWER : A, B, D

Explanation: ArithmeticException is thrown when an exceptional arithmetic condition has occurred, such as, an integer "divide by zero".

OutOfMemoryError is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory and no more memory could be made available by the garbage collector.

ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

ArrayIndexOutOfBoundsException is thrown to indicate that an array has been accessed with an illegal index. The index is either negative, or greater than, or equal to the size of the array.
Incorrect

Question
30
Which method declarations, when inserted independently at the indicated position, will not cause the program to fail during compilation? Select two choices.

public class Test
{
public long sum(long a, long b)
{
return a + b;
}
// Insert new method declaration here.
}
Choose at least one answer.
a. public int sum(int a, int b) { return a + b; }
b. public int sum(long a, long b) { return a+b; }
c. abstract int sum();
d. private static long sum(long a, long b) { return a + b; }
e. public long sum(long a, int b) { return a + b; }
Choices A and E are the correct answers.

Overloading requires that the method arguments differ, the return types may or may not be different.

Choice B is incorrect since the method signatures only differ in the return type, which is not legal.

Choice C is incorrect since it tries to declare an abstract method in a non-abstract class.

Choice D is incorrect since its signature is identical to the existing method in the Test class, except for the static and private modifiers. It is illegal for overloading methods to differ just by modifiers; the arguments must be different too.

More about overloading is available at:
http://java.sun.com/docs/books/jls/thir ... tml#|8.4.9
Incorrect

Question
31
Which of the following are legal identifiers for variable names?
Choose one answer.
a. instanceOf
b. 3_$int
c. -int
d. !byte
e. volatile
Choice A is the correct answer.

A valid identifier must start with a letter, $(dollar) sign, or an underscore and the subsequent characters may be letters, dollar signs, underscores, or digits. Also, it shouldn't be a reserved Java keyword. Though "instanceof" is a keyword, "instanceOf" is a valid identifier since the case of "O" is different. Here, choices B, C, and D are incorrect because they don't start with a letter, $(dollar) sign, or an underscore.

Choice E is incorrect because 'volatile' is a keyword.
Reference:
http://java.sun.com/docs/books/jls/seco ... l.doc.html
Incorrect

Question
32
What will happen when you compile and run the following code?

public class MyClass
{
private static int x = getValue();
private static int y = 5;
private static int getValue()
{
return y;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Choose one answer.
a. Compiler error about access restriction of private variables of MyClass
b. Compiler error about forward referencing of the getValue() method
c. Prints 0
d. Compiler error about forward referencing of the y static field
e. Prints 10
Choice C is the correct answer.

Please note that the declaration of variable x is valid. The first statement to be called will be "x = getValue();". But note that getValue() will return 0, as y = 5 is not called before "x = getValue()". Had "y = 5;" been before declaration of x, 5 would be returned. Thus 0 will be printed out. So choice E is incorrect.

Since forward referencing is legal here, choices B and D are incorrect.

Choice A is incorrect because accessing private variables is allowed within the same class.
Incorrect

Question
33
What is the result of compiling and running the following program?

enum Fish
{
GOLDFISH, ANGELFISH, GUPPY;
}
public class EnumTest2
{
public static void main(String[] args)
{
Fish f=Fish.valueOf("GUPPY");
if(f==Fish.GUPPY)
System.out.println("Are equal");
if(f.equals(Fish.GUPPY))
System.out.println("Are equal");
}
}
Choose one answer.
a. Compiler error
b. Prints "Are equal" twice
c. Prints "Are equal" once
d. Prints nothing
Choice B is the correct answer.

The valueOf() method returns the enum constant whose value corresponds to the string argument passed.

Two enum constants can be compared for equality by using the == relational operator. They can also be compared using the equals method, since they are instances of the declared enumeration type. So both == operator and equals method return true causing the output "Are equal" to occur twice. Since there are no compiler errors, choice A is incorrect.

Since choice B is correct, the other choices are automatically incorrect.

Want to know more about enums?

Check out:
http://java.sun.com/docs/books/jls/thir ... .html#|8.9
http://java.sun.com/j2se/1.5.0/docs/gui ... enums.html
Incorrect

Question
34
What is the result of compiling and executing the following code ?

class MyBoolean
{
Boolean[] bool = new Boolean[5];

public static void main(String[] args)
{
new MyBoolean().myMethod();
}

public void myMethod()
{
if(bool[1]==true)
{
System.out.println("It's true");
}
else
{
System.out.println("It's false");
}
}
}
Choose one answer.
a. Prints: "It's true"
b. Prints: "It's false"
c. Compile time error
d. Exception
e. None of the above
Choice D is the correct answer.

Array elements are initialized to default values when an array is created. For objects, the default value is null. So all the elements of the array bool contain null values.

Comparing a Boolean with a boolean will result in an autoboxing operation. Since the Boolean object is null, autoboxing a null will cause a NullPointerException to be thrown. Since there is no compiler error in this code, choice C is incorrect.

Choices A and B are incorrect because the exception occurs before anything is printed.
Incorrect

Question
35
What happens when you try to compile and run the following program?
1. class Mystery
2. {
3. String s;
4. public static void main(String[] args)
5. {
6. Mystery m = new Mystery();
7. m.go();
8. }
9. void Mystery()
10. {
11. s = "Constructor";
12. }
13.
14. void go()
15. {
16. System.out.println(s);
17. }
18. }
Choose one answer.
a. The code does not compile.
b. The code runs but nothing appears in the standard output.
c. The code runs and "Constructor" appears in the standard output.
d. The code runs and writes "null" in the standard output.
Choice D is the correct answer.

Choice D is correct because void Mystery() is a method, but not a constructor because a constructor does not have any return type.

Choice A is incorrect because the code compiles without any errors, it is perfectly legal to have a method with the same name as that of the class. Since it is a just a method and not a constructor, Mystery() does not get automatically called. So the variable s does not get initialized. So s refers to null, which is the default value for reference variables. Since "null" is the output, choices B and C are incorrect.

Reference:
http://java.sun.com/docs/books/tutorial ... ctors.html
Incorrect

Question
36
What will be the result of compiling and running the following code?

class TestInner
{
int i=10; //1

TestInner()
{
System.out.print("Outer"); // 2
}

static class MyInner
{
MyInner()
{
System.out.print(i); //3
}
}
public static void main(String[] args) { //4
new TestInner.MyInner(); //5
}
}
Choose one answer.
a. Compilation fails at line 3
b. Compilation fails at line 5
c. Prints "Outer10"
d. None of the above
Choice A is the correct answer.

The code does not compile because static nested classes are not allowed to access non-static variables of the enclosing class.

Here, MyInner class attempts to access the non-static variable i of TestInner. There is no error at line 5, this is a perfectly valid way to instantiate a static nested class. So choice B is incorrect.

If i had been static, the output would have been 10. Static nested classes do not require an instance of the enclosing class. Since compilation fails at line 3, choices C and D are also incorrect.
Incorrect

Question
37
Which of the following statements is/are true about compiling and running the following code?

class Test
{
final Object obj;

Test()
{
obj=null; //1
System.out.println(obj instanceof Object); //2
Integer i=new Integer("1"); //3
obj=i; //4
}

public static void main(String args[])
{
Test test=new Test();
System.out.println(test.obj);
}
}
Choose one answer.
a. The program compiles correctly and prints "false" and null.
b. The program will compile correctly if line 1 is removed.
c. The program will compile correctly if line 2 is removed.
d. The program will compile correctly if line 3 is removed.
e. The program will compile correctly if line 4 is removed.
f. None of the above.
Choice E is the correct answer.

This program will compile and run correctly if line 4 is removed. You can assign a value to a final variable only once. If you try to reassign, as is done in line 4, the compiler gives an error. Thus choices A and F are incorrect.

There is no harm in assigning a null value to obj. The instanceof operator returns false, if the object reference on the left is null. So lines 1 and 2 are correct. Hence choices B and C are not correct.

The Integer constructor can take a String argument, so line 3 is also compiles without errors. Thus choice D is also incorrect.
Incorrect

Question
38
Exception1 and Exception2 are subclasses of Exception.

Exception3 is the subclass of RuntimeException. Given the following classes, which of these exceptions can be thrown by the test() method in class A3?

class A1
{
void test() throws Exception1, Exception2{}
}

class A2 extends A1
{
void test() throws Exception2{}
}

class A3 extends A2
{
void test() throws _______{}
}
Choose one answer.
a. Exception1, Exception2, and RuntimeException
b. Exception1 and Exception2 only
c. Exception2 and RuntimeException only
d. It cannot throw any exceptions
e. RuntimeException only
Choice C is the correct answer.

The test() method in class A3 can only throw RuntimeException and Exception2. Since the method in class A2 is throwing only Exception2 as a checked exception, the overriding method in the derived class A3 can also only throw Exception2 as a checked exception. Exception1 and Exception2 are checked exceptions since they extend Exception. So choices A and B are incorrect.

However, RuntimeException can be thrown because it is an unchecked exception and overriding methods have no restrictions in throwing unchecked exceptions. So choice D is incorrect.

Reference:
http://java.sun.com/docs/books/tutorial ... clare.html
Incorrect

Question
39
What will appear in the standard output if tryThis() throws an IOException?
1. try
2. {
3. tryThis();
4. return;
5. }
6. catch(IOException x1)
7. {
8. System.out.println("exception 1");
9. return;
10. }
11. catch(Exception x2)
12. {
13. System.out.println("exception 2");
14. return;
15. }
16. finally
17. {
18. System.out.println("finally");
19. }
Choose one answer.
a. "exception 1" followed by "finally"
b. "exception 2" followed by "finally"
c. "exception 1"
d. "exception 2"
Choice A is the correct answer.

Regardless of whether or not an exception occurred, or whether or not it was handled, execution proceeds to the finally block associated with the try block. Here, the exception gets handled in lines 6 to 9 and then the execution proceeds to the finally block at line 16. Hence, the output is "exception 1" followed by "finally".

Since the exception is handled by the first catch block itself, control never reaches the next catch. So "exception 2" is never printed, thus choices B and D are incorrect.

Choice C is incorrect because control does proceed to the finally block.

Reference:
http://java.sun.com/docs/books/tutorial ... nally.html
Incorrect

Question
40
Which of the following code fragments can you insert at the specified location in the given code so that it continues with the next iteration of the outermost loop?

outer: for ( int x = 0; x < 3; x++ )
{
middle: for ( int y = 0; y < 3; y++ )
{
inner: for ( int z = 0; z < 3; z++ )
{
if ( y == 1)
{
// insert here
}
}
}
}
Choose one answer.
a. break;
b. break middle;
c. break outer;
d. continue;
e. continue middle;
Choice B is the correct answer.

The break statement is used to break out of a loop. In the case of nested loops, encountering the break statement in an inner loop moves the control to the enclosing loop. Thus, when 'break middle' statement is executed, the control shifts to the outer loop and the next iteration starts for the outer loop.

The continue statement can be only used to skip the current iteration of the loop, so choices D and E are incorrect.

Another way to achieve the same result would be inserting the statement 'continue outer' at the same location.
Incorrect

Question
41
The AssertionError class has the "-IS-A" relationship with which of the following classes? Select two choices.
Choose at least one answer.
a. RuntimeException
b. Error
c. VirtualMachineError
d. IllegalAccessException
e. Throwable
Choices B and E are the correct answers.

The AssertionError class is an Error, which denotes an "incorrect condition" as opposed to an "unusual condition" (Exception). Since the Error class descends from Throwable, AssertionError also has "IS-A" relationship with Throwable.

Here is the hierarchy:

java.lang.Object
|
+-java.lang.Throwable
|
+-java.lang.Error
|
+-java.lang.AssertionError

Choices A, C and D are incorrect because they are not in the same inheritance hierarchy as AssertionError. Want to know more?

You can find more information about this as an answer to "Why is AssertionError a subclass of Error rather than RuntimeException?" at: http://java.sun.com/j2se/1.4/docs/guide ... ssert.html
Incorrect

Question
42
What will happen when you attempt to compile and run the following code? (Assume that the code is compiled and run with assertions enabled.)

public class AssertTest
{
private void methodA(int i)
{
assert i >= 0 : methodB();
System.out.println(i);
}

private String methodB()
{
return "The value must not be negative";
}

public static void main(String[] args)
{
AssertTest test = new AssertTest();
test.methodA(-10);
}
}
Choose one answer.
a. It will print -10.
b. It will result in AssertionError with the message -"The value must not be negative".
c. The code will not compile.
d. None of these
Choice B is the correct answer.

This assert statement is of the form -

assert Expression1 : Expression2;

In this code, both the expressions are perfectly valid, and hence the code will compile successfully without any error. Hence choices C and D are incorrect.

The expression (Expression1) "i >= 0" is a boolean expression which is evaluated to false at runtime, hence Expression2 is evaluated which is a method call that returns a String object. Hence, an AssertionError object with this string message is created and thrown. Thus, it results in AssertionError with the message - "The value must not be negative".

Once the assert condition fails, the rest of the statements are not executed. Thus choice A is incorrect.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... Error.html
Incorrect

Question
43
The AssertTest class defines a method, methodA(int i), as given below. Which of the following declarations of methodA(int i) would be valid in a subclass of AssertTest?
(Assume that the code is compiled successfully and runs with assertions enabled.) Select three choices.

public class AssertTest
{
public void methodA(int i) throws AssertionError
{
assert i < 1024 : "Invalid Value";
}
}
Choose at least one answer.
a. public void methodA(int i)
b. public void methodA(int i) throws Exception
c. public void methodA(int i) throws Throwable
d. public void methodA(int i) throws Error
e. public void methodA(int i) throws RuntimeException
f. Only option A is valid
Choices A, D and E are the correct answers.

Both are the valid declarations of methodA(int i). Note that AssertionError is a subclass of Error, and it is not mandatory to declare it in the throws clause of the method. Choice A obviously will compile without any error.

Also, since it is not mandatory to declare Error or its subclass in the throws clause of the method, any method can throw it; irrespective of what its super class implementation throws. This is similar to RuntimeException. Hence, choice D and E correct.

Exception is the super class of all Exceptions and subclass method can't throw it if its super class counterpart does not throw it. Hence, choice B is incorrect.

It applies to Throwable as well, which is the super class of both - Exception and Error. Hence, choice C is also incorrect.
Incorrect

Question
44
What will happen when you attempt to compile and run the following code? (Assume that the code is compiled and run with assertions enabled.)

1. public class AssertTest
2. {
3. int LOCAL_RATE = 12;
4.
5. private void computeAmount(int rate)
6. {
7. assert rate = LOCAL_RATE : "Invalid rate";
8. int amount = 10000;
9. int total = amount + (amount * rate/100);
10. System.out.println("Total = " + total);
11. }
12.
13. public static void main(String[] args)
14. {
15. AssertTest test = new AssertTest();
16. test.computeAmount(12);
17. }
18. }
Choose one answer.
a. It will print-"Total = 11200"
b. Compilation error at line 16
c. Compilation error at line 7
d. Compilation error at line 5
e. None of these
Choice C is the correct answer.

The syntax of assert requires first expression to be a boolean. This expression is of form -

assert Expression1 : Expression2

where Expression1 MUST be a boolean. In this code, the expression "rate = LOCAL_RATE" is not a boolean (note the single =, instead of ==), hence it results in a compilation error at line 7.

There is nothing wrong with lines 16 and 5. Hence choices B and D are incorrect. The main method is contained in the class AssertTest and hence it can access its private methods.

It is helpful to remember this form of an assert statement as follows -

assert boolean_expression : secondary_expression
Incorrect

Question
45
What will be the result of an attempt to compile and run the following code?

public class Test
{
public static void main(String[] args)
{
float i=0;
final byte j=5;
final short s=4;
while(i<5)
{
switch((int)i+2){ //1
default: //2
case j:
System.out.println("one"); //3
break;
case s+1: //4
{
System.out.println("two");
break;
}
}
i++;
}
}
}
Choose one answer.
a. Compiler error on line 1
b. Compiler error on line 2
c. Compiler error on line 3
d. Compiler error on line 4
e. Compiles and runs without errors
Choice D is the correct answer.

Compiler gives an error at line 4 because you cannot have duplicate case labels for a switch case block. Here, j and (s+1) are of value 5, though they are two different variables. So the compiler complains. There is no error on line 1 because the expression passed to the switch statement yields an integer result, which is allowed.

Thus choice A is incorrect. Line 2 has no errors because it is not mandatory to give a body to a case statement. Line 3 has no errors because j is final.

Thus choices B, C and E are incorrect.

Check out:
http://java.sun.com/docs/books/tutorial ... witch.html
Incorrect

Question
46
Given the following two classes, which statement is true?

package pack;

public class Parent
{
protected void test()
{
System.out.println("Test");
}
}

1. package mypack;
2. import pack.*;
3. class ParentTest extends Parent{
4. public static void main(String[] args){
5. new ParentTest().test();
6. new Parent().test();
7. }
8. }
Choose one answer.
a. The code will compile and run only if line 5 is removed.
b. The code will compile and run only if line 6 is removed
c. The code compiles and runs, printing "Test" twice.
d. The code compiles but throws an exception at runtime.
Choice B is the correct answer.

The code will compile and run only if line 6 is removed.

Subclasses that are in a package different from that of the superclass can access protected members of the superclass only through inheritance. Such a subclass cannot use a superclass reference to access a protected member.

Line 5 is legal since we are invoking the test() method using the subclass reference itself, it is the inherited method which we are accessing.

However, line 6 will not compile because the subclass is using the superclass reference to call the test() method.

Since the code does not compile, choices C and D are incorrect.

Reference:
http://java.sun.com/docs/books/tutorial ... ntrol.html
Incorrect

Question
47
What will happen when we try to compile the following code?

1. public void WhichArray( Object x )
2. {
3. if( x instanceof int[] )
4. {
5. int[] n = (int[]) x ;
6. for( int i = 0 ; i < n.length ; i++ )
7. {
8. System.out.println("integers = " + n[i] );
9. }
10. }
11. if( x instanceof String[] )
12. {
13. System.out.println("Array of Strings");
14. }
15. }
Choose one answer.
a. The compiler objects to line 3 comparing an Object with an array.
b. The compiler objects to line 5 casting an Object to an array of int primitives.
c. The compiler objects to line 11 comparing an Object to an array of Objects.
d. It compiles without error.
Choice D is the correct answer.

The "instanceof" operator tests the class of an object at runtime. It returns true if the type of the left-hand argument is the same as, or is some subtype of, the class or interface specified by the right-hand operand. Arrays are also objects, so they can be referred to by variables of type Object. Hence comparing Object type to array using instanceof is allowed. So choices A, B and C are incorrect.
Incorrect

Question
48
What is the result of compiling and running the following code?

abstract class Test
{
void test()
{
System.out.println("Super");
}
}

protected class SubTest extends Test
{
void test()
{
System.out.println("Sub");
}
}

public class AccessTest
{
public static void main(String[] args)
{
Test t=new SubTest();
t.test();
}
}
Choose one answer.
a. Compiler Error: Abstract class Test must contain at least one abstract method
b. Prints "Super"
c. Prints "Sub"
d. None of these
Choice D is the correct answer.

The code does not compile because a non-nested class cannot be declared protected. For such a class, only public and default access levels are allowed.

Choice A is incorrect because it is not mandatory for abstract classes to have abstract methods.

Since the code does not compile, choices B and C are automatically incorrect.
Incorrect

Question
49
Given the following main method in a class called Cycle and a command line as shown below:

java Cycle one two.

What will be output?

class Cycle
{
public static void main(String[] bicycle)
{
System.out.println(bicycle[0]);
}
}
Choose one answer.
a. Compiler error
b. Prints "Cycle"
c. Prints "one"
d. Prints "Two"
Choice C is the correct answer.

The command line arguments are provided after the class name, they get stored in a String array, which is the argument to the main method. The indexing of arrays start from 0.

The class name does not get stored in the array. So, bicycle[0] will contain "one" and bicycle[1] will contain "two". Hence, the output is "one".

Since choice C is correct, the other choices are automatically incorrect.

Refer to:
http://java.sun.com/docs/books/tutorial ... eArgs.html
Incorrect

Question
50
The following line of code is equivalent to which of the given codes? Select two choices.

if(x > y)
z = x;
else
z = y;
Choose at least one answer.
a. z = x < y ? x : y
b. z = x < y ? y : x
c. z = y < x ? x : y
d. z = y < x ? y : x
e. None of the above
Choices B and C are the correct answers.

The syntax and rule governing the output of the ternary operator ?: in java is as follows:

condition ? e1 : e2 evaluates to e1 if the condition is true, to e2 otherwise.

Here are the choices B and C.
z = x < y ? y : x
z = y < x ? x : y

In the first case, the condition can be x>y or x<y, e1 is y and e2 is x. Thus choice B is correct.

In the second case, the condition can be y>x or y<x, e1 is x and e2 is y. So choice C is also correct.

Hence all the other choices are incorrect.
Incorrect

Question
51
What will be written to the standard output when the following program is executed?

public class Test
{
int a;
int b;

public void f()
{
a = 0;
b = 0;
int[] c = { 0 };
g(b, c);
System.out.println(a + " " + b + " " + c[0] + " ");
}

public void g(int b, int[] c)
{
a = 1;
b = 1;
c[0] = 1;
}

public static void main(String[] args)
{
Test obj = new Test();
obj.f();
}
}
Choose one answer.
a. 0 0 0
b. 0 0 1
c. 0 1 0
d. 1 0 0
e. 1 0 1
Choice E is the correct answer.

In Java, method arguments are passed by value. When the g() method is called, the argument b receives a copy of the instance variable b. Since the copy alone is modified, the change of value in parameter b is confined to the g() method. So b's value remains 0. However, the change made to the instance variable a is reflected, since there is only copy of a. So the value of a becomes 1. When an object reference is passed to a method, the copy of the object reference is received as the method argument.

Now the copy also refers to the original object itself. Since arrays are objects, the changes made within the g() method affect the original array object, so the value of the first element changes to 1. Thus the values of a, b, and c[0] are printed as 1, 0, and 1 respectively.

Hence, choice E is correct and the other choices are automatically incorrect.
Incorrect

Question
52
Which of the following statements are true about the following code fragment?

1. int a = 1;
2. String [] names = { "John", "Merry", "Tom"};
3. names[--a] += "-";
4. for (int i = 0; i < names.length; i++)
5. {
6. System.out.println(names[i]);
7. }
Choose one answer.
a. The output starts with "John-".
b. The output starts with "John" and includes "Merry-".
c. An ArrayIndexOutOfBoundException is thrown.
d. None of these.
Choice A is the correct answer.

At first, the value of a is 1. Then the prefix decrement operator --a makes the value of a=0. At line 3, names[0] gets modified to "John-". After that the loop just prints the whole array, the remaining array elements remain unchanged. So choice B is incorrect.

Choice C is incorrect because the array bounds are not exceeded.
Incorrect

Question
53
Which of the following operators will always evaluate all the operands? Select two choices.
Choose at least one answer.
a. ||
b. +
c. &&
d. ? :
e. %
Choices B and E are the correct answers.

The + operator is for adding or concatenating, it must evaluate both operands to produce the result.

The % operator returns the remainder of a division operation and needs to evaluate both operands.

The && and || operators exhibit short-circuit behavior, that is, the second operand is evaluated only if the result of the operation is not clear from the value of the first operand.

The first operand of the ternary operator (? : ) is always evaluated. Based on the result of this evaluation, either the second or the third operand is evaluated.

So choices A, C and D are incorrect.
Incorrect

Question
54
After which line is the object created on line 2 eligible for garbage collection?

public class Test
{
public static void main(String[] args)
{
String msg; //1
String a=new String("abc"); //2
String b=null; //3
b=a; //4
a=new String("abc"); //5
b+="de"; //6
System.out.println(b); //7
b=null; //8
}
}
Choose one answer.
a. 4
b. 5
c. 6
d. 7
e. None of the above
Choice C is the correct answer.

The object created at line 2 is a String that contains "abc". First a referred to it, then b also is made to refer to it.

At line 4, a is made to refer to a new String object, but b still refers to the original object itself.

Now at line 6, the String "de" is concatenated with the String contained in b. As you know, String objects are immutable, so here a new String object is created with the contents "abcde" and b now refers to it. The original object that contained "abc" has no references now and hence becomes eligible for garbage collection at line 6.

Thus choices A, B, D and E are incorrect.

You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
Incorrect

Question
55
How many objects are eligible for garbage collection by the time the method f() is invoked?

class MyClass
{
private MyClass z;

public void other(MyClass c)
{
z = c;
}
protected void finalize()
{
System.out.println("called");
}
}

class Test
{
private static void f() { }

public static void main (String[] args)
{
MyClass c1 = new MyClass();
MyClass c2 = new MyClass();
c1.other(c2);
c2.other(c1);
MyClass c3=new MyClass();
c1=c3;
c2=c3;
f();
}
}
Choose one answer.
a. 1
b. 2
c. 3
d. Code does not compile
e. None of the above
Choice B is the correct answer.

The two objects originally referred to by c1 and c2 are eligible for garbage collection after you make c1 and c2 refer to c3. These objects do have references to each other, but this doesn't stop them from being garbage collected. Objects that have circular references like this are eligible for garbage collection, if there are no external references to either of them.

Since 2 objects are eligible for GC, choices A, C, D and E are incorrect.

Want to know more?

You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881
Incorrect

Question
56
Choose the statements which are TRUE.
(Choose two options)
Choose at least one answer.
a. IS-A relationship : Inheritance.
b. The extent to which a class uses other classes : Composition .
c. HAS-A relationship : Coupling.
d. The extent to which methods in a class are related : Cohesion.
ANSWER : A, D

Explanation:
Two things, X and Y are in the IS-A relationship if the phrases "X is a Y" or "all Xs are Ys" are true. Objects in an IS-A relationship use inheritance as in class X extends Y. Two things, X and Y are in a HAS-A relationship if Y is a property or component of X, as in the phrases "X has a Y", or "Y is a component of X". If X HAS-A Y, then Y will be an instance variable of class X. This relationship is also called composition or aggregation.

Cohesion is the extent to which methods in a class are related and coupling is the extent to which a class uses other classes.

High coupling tends to indicate poor design of classes, since it makes modifying parts of the system difficult, e.g., modifying a component affects all the components to which the component is connected. A well designed unit will have high cohesion.

More about coupling, cohesion and other related concepts is available at: http://satc.gsfc.nasa.gov/support/STC_A ... ly_oo.html
Incorrect

Question
57
Which of the following statements are true about the relationships between the following classes? Select three choices.

class Foo
{
int num;
Baz comp = new Baz();
}
class Bar
{
boolean flag;
}
class Baz extends Foo
{
Bar thing = new Bar();
double limit;
}
Choose at least one answer.
a. A Bar is a Baz.
b. A Foo has a Baz.
c. A Baz is a Foo.
d. A Foo is a Baz.
e. A Baz has a Bar.
Choices B, C, and E are the correct answers.

An instance of the Baz class is also an instance of the class Foo since the Baz class extends the Foo class. So choice C is correct.

A Baz has a Bar, since instances of the Baz class contain an instance of the Bar class by reference. So choice E is correct.

A Foo has a Baz, since instances of the Foo class contain an instance of the Baz class by reference. Since a Foo has a Baz, which in turn has a Bar, a Foo has a Bar. So choice B is also correct.

Choice A is incorrect because Bar does not extend Baz.

Choice D is also incorrect because Foo does not extend Baz either.

Reference: http://cnx.rice.edu/content/m11709/latest/
Incorrect

Question
58
Which statement, when inserted at the indicated position in the following code, will cause a runtime exception to be thrown?

class A {}
class B extends A {}
class C extends A {}
public class Test
{
public static void main(String[] args)
{
A x = new A();
B y = new B();
C z = new C();
// insert statement here
}
}
Choose one answer.
a. x = y;
b. z = x;
c. y = (B) x;
d. z = (C) y;
e. y = (A) y;
Choice C is the correct answer.

Choice A will compile and run without errors because it is legal to assign a subclass object to a superclass reference variable.

Choices B and E will cause compilation errors, since they attempt to assign an incompatible type to the reference.

Choice D will cause a compilation error, since classes C and B do not share an inheritance relationship.

Choice C will compile, but will throw a ClassCastException at runtime, since the object that is cast to B is not an instance of B.
Incorrect

Question
59
What will happen when you attempt to compile and run the following code?

class Base
{
private void aMethod(int iBase)
{
System.out.println("Base");
}
}

class Over extends Base
{
public static void main(String[] argv)
{
Base o = new Over();
int iBase = 0;
o.aMethod(iBase);
}
public void aMethod(int iOver)
{
System.out.println("Over");
}
}
Choose one answer.
a. Compiler error
b. Prints "Base"
c. Prints "Over"
d. ClassCastException
Choice A is the correct answer.

The aMethod method is defined as private in the Base class. So you cannot invoke the subclass version of aMethod using the Base class reference even though the method is public in the class. This is because the compiler searches for the method in the declared type, which is Base.

Private methods are for the internal use of the class in which they are defined, so they cannot be accessed by outside code.

Since the method won't compile, all the other choices are automatically incorrect.
Incorrect

Question
60
Which of the following methods can be legally inserted in place of the comment //Method Here? Select two choices.

class Base
{
public void aMethod(int i) { }
}

public class Scope extends Base
{
public static void main(String[] argv) { }
//Method Here
}
Choose at least one answer.
a. void aMethod(int i) throws Exception {}
b. void aMethod(long i)throws Exception {}
c. void aMethod(long i){}
d. public void aMethod(int i) throws Exception {}
Choices B and C are the correct answers.

Choices A and D will not compile as they attempt to throw Exception, which is not declared in the base class.

Overriding methods are not allowed to throw wider checked exceptions than those thrown by overridden methods.

Since choices B and C take a parameter of type long, they represent overloading, and not overriding. There are no restrictions on overloaded methods.
I

Re: oracle java 6 certification exam mock questions

PostPosted: Fri Mar 02, 2012 11:07 am
by tomrff
Question
1
What is the output of the following code.

String thePattern = "ill\\d(?i)";
Pattern pattern = Pattern.compile(thePattern);
String target = "Jack and JILL1 WENT UP THE hill2";
Matcher matcher = pattern.matcher(target); System.out.println(matcher.replaceAll("xxxx") );
Choose one answer.
a. Compilation error.
b. Exception at runtime .
c. Jack and Jxxxx WENT UP THE hxxxx.
d. Jack and xxxx WENT UP THE xxxx.
ANSWER : C

Explanation:
Here we compile the regular expression string using the Pattern class, use the Pattern class to get a Matcher object, and call methods on the Matcher to get at any matches.

The regular expression "ill\\d" matches 'ill' words that end with a digit. The expression "(?i)" causes the case to be ignored. So both uppercase and lowercase versions of 'ill' can match. The replaceAll() method of the Matcher class takes a replacement string and replaces all matches with it.

Want to know more ? Check out:
http://docs.oracle.com/javase/1.5.0/doc ... ttern.html
Correct
Marks for this submission: 1/1.

Question
2
Choose the option that will compile without any errors.
Choose one answer.
a. new DateFormat(DateFormat.LONG, Locale.FRANCE).format(new Date());
b. DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE).format(new Date());
c. DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE).parse(new Date());
d. new DateFormat(DateFormat.LONG, Locale.FRANCE).parse(new Date());
ANSWER : B

Explanation:
DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner.

Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG, and FULL.

The SHORT format consists entirely of numbers while the FULL format contains most of the date components.

There is also a default format called DEFAULT and is the same as MEDIUM.


More about Locale class is available at:
http://java.sun.com/j2se/1.5.0/docs/api ... ocale.html
http://java.sun.com/docs/books/tutorial/i18n/
Correct
Marks for this submission: 1/1.

Question
3
Choose the correct options.
(Choose three options)
Choose at least one answer.
a. Changes the current working directory : changeWorkingDirectory().
b. Deletes a file : remove() .
c. Creates a file : createNewFile().
d. Renames a file : renameTo().
e. Makes a directory : mkdir().
ANSWER : C, D, E

Explanation:
The File class does not provide any methods to change the current working directory.
The delete() method attempts to delete a file or a directory.
The createNewFile() method creates a new empty disk file.
The renameTo() method can be used to rename a file or a directory.
The mkdir() method attempts to create a new directory.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... /File.html
Correct
Marks for this submission: 1/1.

Question
4
What is the output of the following code.

public class T
{
public static void main (String[ ] args) throws Exception
{
String s="it";
boolean b=false;
System.out.format("The value is %3$.2f. That is %2$b ,isn't %1$s ?", s, b , 0.345);
}
}
Choose one answer.
a. Compilation error.
b. Exception at runtime .
c. The value is 0.35. That is false ,isn't it ?
d. The value is 0.345. That is false ,isn't it ?
e. The value is it. That is false ,isn't 0.345 ?
ANSWER : C

Explanation:
The Formatter class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output.

The PrintStream class (of which System.out is an instance) has two format methods.


The format(String format, Object... args) method writes a formatted string to this object's destination using the specified format string and arguments.


The %s format string is used for formatting the value supplied as a String and printing it.

The %b format is for boolean values and %f for floating point values.


The $ notation is used to re-order the arguments according to the specified integer, that is 3$ stands for argument no. 3, 2$ stands for argument no. 2, and so on.

To know more about the Formatter, refer to:
http://download.oracle.com/javase/1.5.0 ... atter.html
Correct
Marks for this submission: 1/1.

Question
5
What is the result of compiling and running the following code?

String s1 = new String("Bicycle");

String s2 = new String("bicycle");

System.out.println(s1.equals(s2)==s2.equals(s1));
Choose one answer.
a. Compiler error
b. Prints "true"
c. Prints "false"
d. Prints "false==false"
e. Prints "true==true"
Choice B is the correct answer.

The given expression will print true not only for the given strings but for any two strings you might choose.

The equals method is symmetric: for any reference values x and y, x.equals( y ) should return true if and only if y.equals(x) returns true. So in this case, s1.equals(s2) gives false and s2.equals(s1) also gives false. The result of (false==false) is true. So the output is true.

More information is available at:
http://java.sun.com/j2se/1.3/docs/api/j ... bject.html

Correct
Marks for this submission: 1/1.

Question
6
Which of the following, if inserted independently at the indicated point in the main method, will print true? Select three choices.

public class Test
{
public static void main(String[] args)
{
Boolean b=new Boolean("TRUE");
boolean b1=true;
// insert code here
System.out.print("true");
}
}
Choose at least one answer.
a. if(b.booleanValue()==b1)
b. if(b.booleanValue()=="true")
c. if(b.equals("true"))
d. if(b1=="true")
e. if(b==b1)
f. if(b.equals(b1))
Choices A, E, and F are the correct answers.

The booleanValue() method of the Boolean class returns the encapsulated boolean value of the Boolean object, which is true in this case. Comparing true with b1, which is also true, results in true. So choice A is correct.

In choice F, b1 is autoboxed into a Boolean object of the same value, so b.equals(b1) returns true.

In choice E, b is unboxed into a boolean primitive of value true. Comparing the true values of both boolean primitives yields true.

Choice B will not compile because boolean type and String type cannot be compared.

Choice C prints false as a Boolean object and a String object cannot be the same.

Choice D will not compile because the Boolean object and the String object cannot be compared with the == operator.
Correct
Marks for this submission: 1/1.

Question
7
What is the result of compiling and running the following code?

String s=new String("hello");

StringBuffer sb=new StringBuffer("hello");

System.out.println(s.equals(sb));
Choose one answer.
a. Compiler error: String and StringBuffer objects cannot be compared
b. ClassCastException: String and StringBuffer objects cannot be compared
c. Prints "true"
d. Prints "false"
Choice D is the correct answer.

The equals method does not cause any compiler error or exception if the invoking object and the argument are objects of different classes. This is because the argument to equals method is of type Object, so any object can be passed. Thus choices A and B are incorrect.

However, the method must return false, if the objects are not of the same class.

So choice D is correct while choice C is incorrect.
Correct
Marks for this submission: 1/1.

Question
8
You want a floating point number to be formatted in Italian format. Which of the following code snippets can help you achieve this?
Choose one answer.
a. NumberFormat nf=new NumberFormat(Locale.Italy);
String s=nf.format(123.45);
b. NumberFormat nf=NumberFormat.getInstance(Locale.Italy);
String s=nf.format(123.45);
c. NumberFormat nf=NumberFormat.getInstance();
String s=nf.format(123.45,Locale.Italy);
d. NumberFormat nf=new NumberFormat();
String s=nf.format(123.45,Locale.Italy);
Choice B is the correct answer.

You can use the following factory method when a Locale other than the default Locale is to be used.

public static NumberFormat.getInstance(Locale locale)

The format method just takes the number as the argument and returns the formatter string. So choices C and D are incorrect.

Choice A is incorrect because NumberFormat is an abstract class and cannot be instantiated using the new operator.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... ormat.html
Correct
Marks for this submission: 1/1.

Question
9
What is the result when the following code is executed?

String s = "howzzat";
Scanner scanner = new Scanner(s);
scanner.useDelimiter("wz");
scanner.next();
System.out.println(scanner.next());
Choose one answer.
a. No output
b. Prints "wz"
c. Prints "wzz"
d. Prints "ho"
e. Prints "zat"
Choice E is the correct answer.

When the given code is executed, the string "zat" is printed to the standard output. The java.util.Scanner can be used to break the contents of the given string into tokens using a delimiter pattern. Here you set the delimiter to "wz" through the useDelimiter() method of Scanner.

The first invocation of the next() method returns "ho" and the second invocation returns "zat" which is then printed out. Since choice E is correct, the other choices are automatically incorrect.

References:
http://java.sun.com/j2se/1.5.0/docs/api ... anner.html
http://java.sun.com/developer/JDCTechTi ... t1201.html
Correct
Marks for this submission: 1/1.

Question
10
Which of the following compiles correctly if f is an instance of the File class? Select two choices.
Choose at least one answer.
a. String[] s =f.list();
b. File[] files=f.list();
c. File[] files=f.listFiles();
d. List files=f.listFiles();
Choices A and C are the correct answers.

The File class defines a list() method and a listFiles() method.

The list() method returns an array of Strings containing the names of the files and directories in the directory denoted by the abstract pathname represented by the File object.

The listFiles() method returns an array of File objects denoting the files and directories in the directory denoted by the abstract pathname represented by the File object.
Correct
Marks for this submission: 1/1.

Question
11
Choose the correct options.
(Choose two options)
Choose at least one answer.
a. Does not allow duplicates, no ordering : LinkedList.
b. Does not allow duplicate keys, may use last accessed order : LinkedHashMap.
c. Allows random access, synchronized methods : Vector.
d. Unique keys mapped to value objects, sorted order of keys : HashMap.
ANSWER : B,C

Explanation: Set types do not allow duplicate elements.

HashSet is the most efficient Set class; it does not provide any ordering for its elements.

LinkedHashMap is a Map class, which allows two types of ordering for its elements, insertion order or last accessed order.

Vector is a List type, which is similar to ArrayList except that its methods are synchronized, whereas the methods of ArrayList are not.

TreeMap maps unique keys to non-unique values; the pairs are sorted in the order of keys.
Correct
Marks for this submission: 1/1.

Question
12
What is the result of compiling and running the following code?

ConcurrentNavigableMap myMap = new ConcurrentSkipListMap();
myMap.put("ab", 10);
myMap.put("cd", 5);
myMap.put("ca", 30);
myMap.put("c", 30);
myMap.put("az", 20);
NavigableMap myMap2 = myMap.tailMap("c", true);
System.out.println(myMap.size() + " " + myMap2.size());
Choose one answer.
a. Compiler error
b. Exception
c. Prints 5 3
d. Prints 5 2
Choice C is correct.

The tailMap(fromKey) method defined in NavigableMap returns a view of the portion of this map whose keys are greater than or equal to fromKey. Here, the key is "c", hence the map view returned contains "c","ca" and "cd".

Since the main map contains 5 elements and the view contains 3 elements, the output is 5 3. Since the code compiles and runs correctly, all the other choices are incorrect.

For more information, refer to
http://java.sun.com/javase/6/docs/api/j ... leMap.html
Correct
Marks for this submission: 1/1.

Question
13
What is the return type of the firstEntry() method in the NavigableMap interface?
Choose one answer.
a. String
b. Object
c. Map
d. Map.Entry
Choice D is correct.

The firstEntry() method returns a key-value mapping associated with the least key in this map, or null if the map is empty. It returns an entry of type Map.Entry with the least key, or null if this map is empty. Since choice D is correct, all the other choices are automatically incorrect.

For more information, check out the following link.
http://java.sun.com/javase/6/docs/api/j ... leMap.html
Correct
Marks for this submission: 1/1.

Question
14
Which interface defines the int compare(Object, Object) method?
Choose one answer.
a. Comparator
b. Comparable
c. SortedSet
d. TreeMap
Choice A is the correct answer.

The java.lang.Comparator interface defines the compare method whose signature is

int compare(Object o1, Object o2)

A comparator can be used to define total ordering of objects in a collection, based on the result of the compare method. So choice A is correct.

Comparable interface imposes a total ordering on the objects of each class that implements it. The method defined by it is int compareTo(Object). So choice B is incorrect.

The SortedSet interface represents a Set, whose elements can be iterated in a sorted order. It does not define the compare method. So choice C is incorrect.

Choice D is also incorrect since TreeMap is a class and not an interface. Moreover, it does not define any method called compare.

Reference: http://java.sun.com/j2se/1.5.0/docs/api ... rator.html
Correct
Marks for this submission: 1/1.

Question
15
What will happen when you try to compile and run the following code?

1. import java.util.*;
2. public class MapTest
3. {
4. public static void main(String[] args)
5. {
6. Object obj = new LinkedHashMap();
7. if(obj instanceof Collection)
8. System.out.print("For ");
9. if(obj instanceof Map)
10. System.out.print("A Few ");
11. if(obj instanceof LinkedList)
12. System.out.print("Dollars More ");
13. if(obj instanceof HashMap)
14. System.out.print("Good Men");
15. }
16. }
Choose one answer.
a. It will print - A Few Good Men
b. It will print - For A Few Good Men
c. It will print - For A Few Dollars More Good Men
d. It will print - For A Few Dollars More
e. It will print - For A Few
f. It will print - A Few Dollars More
Choice A is the correct answer.

The code will compile and print - A Few Good Men. The LinkedHashMap class extends the HashMap class, which in turn implements the Map interface. It is also important to understand that the Map interface does not extend the interface Collection. Here is the hierarchy for the class LinkedHashMap-

java.lang.Object
|
+-java.util.AbstractMap (implements Map)
|
+-java.util.HashMap (implements Map)
|
+-java.util.LinkedHashMap (implements Map)

Let's look at the execution of this code now. At line 6, a new LinkedHashMap object is created, since LinkedHashMap does not implement the Collection interface directly or indirectly, the instanceof check at line 7 returns false.

Next, since the parent class of the LinkedHashMap class implements Map, the instanceof operator in line 9 returns true and the code at line 10 prints - "A Few " (without the quotes). Since the LinkedHashMap class does not extend the LinkedList class in any way, the instanceof check at line 11 returns false and the print statement at line 12 is not executed.

The instanceof check at line 13 succeeds because the LinkedHashMap class extends HashMap; hence the statement at line 14 prints "Good Men". Thus the entire code prints - A Few Good Men. Want to know more?

You can read more about the new collection class LinkedHashMap and its usage at -
http://www-106.ibm.com/developerworks/j ... j-mer0821/
Correct
Marks for this submission: 1/1.

Question
16
What is the result of compiling and executing the following code?

1. Vector v=new Vector<Integer>();
2. v.add(18);
3. v.add(20);
4. v.add(12);
5. for(int i : v)
6. System.out.print(i+" ");
Choose one answer.
a. Compiler error at line 1
b. Compiler error at lines 2, 3, and 4
c. Compiler error at line 5
d. Prints 18 20 12
Choice C is the correct answer.

The code does not compile at line 5 because iterating through v gives elements of type Object, and Object type cannot be assigned to int or Integer variables. This happens because the declared type of v is Vector and not Vector<Integer>.

Choice A is incorrect because line 1 compiles without errors, it is allowed to assign generic types to raw types.

Choice B is incorrect because lines 2, 3, and 4 do compile fine, the int type values get autoboxed to Integer.

Since choice C is correct, choice D is automatically incorrect.
Correct
Marks for this submission: 1/1.

Question
17
Which of the following classes override the hashCode() method defined in java.lang.Object class? Select two choices.
Choose at least one answer.
a. java.lang.String
b. java.lang.StringBuffer
c. java.lang.Byte
d. java.lang.Number
e. Only choice A is correct
Choices A and C are the correct answers.

The java.lang.String and java.lang.Byte classes override the equals() and hashCode() methods of the java.lang.Object class to provide their own implementation. On the other hand, the java.lang.StringBuffer and java.lang.Number classes do not override these methods and inherit their implementation from the java.lang.Object superclass. Hence, choices B and D are incorrect.
Correct
Marks for this submission: 1/1.

Question
18
Which collection implementation is suitable for maintaining an ordered sequence of objects when objects are frequently inserted and removed from the middle of the sequence?
Choose one answer.
a. TreeMap
b. Vector
c. ArrayList
d. LinkedList
Choice D is the correct answer.

When objects are frequently inserted and deleted from the middle of the sequence, LinkedList gives the best performance. TreeMap does not maintain an ordered sequence of objects. So choice A is incorrect.

Vector and ArrayList require shifting of objects on insertion and deletion, while LinkedList does not. So choices B and C are incorrect.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... dList.html
Correct
Marks for this submission: 1/1.

Question
19
What is the result of compiling and running the following code?

1. ArrayList<Double> a=new ArrayList<Double>();
2. a.add(new Integer(4));
3. System.out.println(a);
Choose one answer.
a. Compiler error at line 2
b. ClassCastException at line 2
c. Compiles and runs fine printing [4]
d. Compiles and runs fine printing [4.0]
Choice A is the correct answer.

Using generics, it is possible to marks collections as being restricted to contain a particular data type. The code does not compile at line 2 because we are trying to add an Integer object in an ArrayList of type Double.

Generic types offer this compile time type-checking to avoid runtime exceptions from getting thrown. So choice B is incorrect.

Since the code does not even compile, choices C and D are also incorrect.

For more information, check out:
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Correct
Marks for this submission: 1/1.

Question
20
Given the following code line.

Map<Integer,String> map = new HashMap<Integer,String>();

Which of the following are legal? Select three choices.
Choose at least one answer.
a. for(Map.Entry pairs : map.entrySet()){}
b. Iterator i=map.entrySet().iterator();
c. Iterator i=map.iterator();
d. Iterator<Map.Entry<Integer,String>> i=map.entrySet().iterator();
e. Iterator<Map.Entry> i=map.entrySet().iterator();
Choices A, B, and D are the correct answers.

A Map interface is implemented by an object that maps unique keys to values. Here, the key is of Integer type and the value of String type. The HashMap class is an efficient implementation of the Map interface, which does not guarantee any ordering for the keys. The entrySet() method of Map returns a Set view of the mappings contained in this Map. Each element in the Set is a Map.Entry, from which the key and the value can be obtained.

Choice A is correct because enhanced for loop can be used to iterate through all collection types, including sets.

Choice B is correct because the iterator() method of a set returns the Iterator object which can be used to traverse the set.

Choice C is incorrect because the Map interface does not define an iterator() method.

Choice D is correct because the objects iterated upon are of type Map.Entry<Integer,String>.

Choice E is incorrect because the object type is specified as Map.Entry instead of Map.Entry<Integer,String>.

For more information, check out:
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Correct
Marks for this submission: 1/1.

Question
21
What is the result of compiling and running the following code?

import java.util.*;

class MyClass implements java.io.Serializable
{
int i;
MyClass(int i)
{
this.i=i;
}
public String toString()
{
return(""+i);
}
}

public class TreeTest
{
public static void main(String[] args)
{
Set<MyClass> s=new TreeSet<MyClass>();
s.add(new MyClass(2));
s.add(new MyClass(3));
s.add(new MyClass(1));
for(MyClass m : s)
System.out.println(m);
}
}
Choose one answer.
a. Compiler error
b. ClassCastException
c. Prints 2 3 1
d. Prints 1 2 3
e. Prints 3 2 1
Choice B is the correct answer.

The add() method of TreeSet throws ClassCastException if the elements of the Set cannot be compared. For this, the element class needs to implement Comparable interface and override the compareTo() method.

Here the MyClass class does not implement Comparable, hence the error. There are no compiler errors in this code, so choice A is incorrect.

Since ClassCastException is thrown, no output is generated. So the other choices are also incorrect.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... eeSet.html
Correct
Marks for this submission: 1/1.

Question
22
Which of the following will compile and run correctly? Select two choices.
Choose at least one answer.
a. List<?> l=new Vector<String>();
b. Map<? extends Number, ? extends Number> m1=new Hashtable<Integer,Float>();
c. Map<String, String> m2=new Map<String,String>();
d. Set<String> s=new LinkedHashSet<String>;
Choices A and B are the correct answers.

The List interface is implemented by the Vector class. Hence, a List type variable can hold a reference to a Vector object. The wild card character (?) stands for an unknown type, which can legally hold any type. So it is legal to assign a collection of type Vector<String> to List<?>. So choice A is correct.

Hashtable implements the Map interface, so it is legal to assign a Hashtable object to a Map type. Both Integer and Float classes extend Number. The type of Map is declared as Map<? extends Number, ? extends Number>, so the key of the Hashtable object can be of Integer type, and the value of Float type. So choice B is also correct.

Map is an interface, so directly instantiating it is not allowed. Hence, choice C is incorrect.

Choice D is incorrect because the parentheses are missing at the end. The correct statement would be Set<String> s=new LinkedHashSet<String>();

For more information,
check out: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Correct
Marks for this submission: 1/1.

Question
23
Which of the following methods must be implemented correctly by a class if the objects of the class are to behave properly and consistently with all Java collection types? Select two choices.
Choose at least one answer.
a. public int hashCode()
b. protected Object clone()
c. public String toString()
d. public boolean equals(Object obj)
e. public long hashCode()
Choices A and D are the correct answers.

The public int hashCode() and public boolean equals(Object obj) methods must be implemented correctly by a class if its objects have to behave consistently and properly with all Java collection classes and interfaces.

Also, note that the hashCode() method returns an int, and not long. Hence, choice E is incorrect.

Also, it is not mandatory to implement/override any other method so that the class behaves properly and consistently with all Java collection classes and interfaces. Let us understand why it is important to implement these methods correctly. The collection classes internally use these two methods of objects for performing various collection operations. If these methods are implemented incorrectly, you simply do not know how your class objects will behave when confronted to objects of other classes.

For an example, if your class violates the "reflexivity" rule which says that an object must be equal to itself, and then an instance of your class is added to a collection; the collection's contains() method would return false indicating that the collection did not contain the instance that you just added.

Also, whenever equals method is overridden in a class, it is necessary to override hashCode() method as well, as specified by the general contract of the hashCode() method.

Reference:
http://java.sun.com/j2se/1.4.2/docs/api ... bject.html
Correct
Marks for this submission: 1/1.

Question
24
Given that a static method doIt() in the Work class represents work to be done, which of the following blocks of code will succeed in starting a new thread that will do the work?
Choose one answer.
a. Runnable r = new Runnable()
{
public void run()
{
Work.doIt();
}
};
Thread t = new Thread(r);
t.start();
b. Thread t = new Thread()
{
public void start()
{
Work.doIt();
}
};
t.start();
c. Runnable r = new Runnable()
{
public void run()
{
Work.doIt();
}
};
r.start();
d. Thread t = new Thread(new Work());
t.start();
e. Runnable t = new Runnable()
{
public void run()
{
Work.doIt();
}
};
t.run();
Choice A is the correct answer.

A Thread object created passing a Runnable object as the target, executes the run() method of the Runnable object in a separate thread when started.

A Runnable object can be given when constructing a Thread object. If no Runnable object is supplied, the Thread object (which implements the Runnable interface) will execute its own run() method.

A thread is initiated using the start() method of the Thread object.

Choice B is incorrect because the method executed by the new thread is run() and not start(). So the run() needs to be overridden instead of start().

Choice C is incorrect because the start() method to be invoked is that of the Thread object and not of the Runnable target.

Choice D is incorrect because of the invalid argument passed to the Thread class constructor.

Choice E is incorrect because it will simply cause the run() method to be executed as if it were a normal method.

Correct
Marks for this submission: 1/1.

Question
25
Which of the following lines will not compile? Select two choices.

class MyClass implements Runnable
{
public void run(){}
}

class Test
{
public static void main (String[] args) throws Exception
{
Thread t1 = new Thread(); // 1
Thread t2 = new Thread(new MyClass()); // 2
Thread t3 = new Thread(new MyClass(), "Thread3"); // 3
Thread t4 = new Thread("Thread4"); //4
Thread t5 = new Thread("Thread5",5); //5
Thread t6 = new Thread("Thread6",new MyClass()); //6
}
}
Choose at least one answer.
a. Line 1
b. Line 2
c. Line 3
d. Line 4
e. Line 5
f. Line 6
Choices E and F are the correct answers.

Choices E and F do not compile.

The valid Thread constructors are:
Thread()
Thread(Runnable target)
Thread(Runnable target,String name)
Thread(String name)
Thread(ThreadGroup group,Runnable target)
Thread(ThreadGroup group,Runnable target,String name)
Thread(ThreadGroup group,String name)
Choices E and F are thus invalid, whereas all the others are valid constructor calls.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api ... hread.html
Correct
Marks for this submission: 1/1.

Question
26
What will be the result of an attempt to compile and run the following program?

class Test implements Runnable
{
public void run()
{
String str = new String("hello");
synchronized (str)
{
try
{
System.out.print(Thread.currentThread().getName());
Thread.sleep(5000);
System.out.print(Thread.currentThread().getName());
}
catch(InterruptedException e) { }

}
}

public static void main (String[] args)
{
new Thread(new Test(), "A").start();
new Thread(new Test(), "B").start();
}
}
Choose one answer.
a. Result cannot be predicted
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown
Choice A is the correct answer.

In the given code, the String str is a local variable. A local variable is not shared by threads i.e., each thread has a separate copy of the variable. So when each thread runs, a new String object is created and its lock is obtained by the thread.

Since the String objects are different, synchronization is not effective here. Here you cannot predict which thread will start first, nor can we predict whether the other thread will run when one thread is sleeping.

Correct
Marks for this submission: 1/1.

Question
27
What will be the result of an attempt to compile and run the following code?

class TestThread extends Thread
{
public void restart()
{
startMe();
}
public static void startMe()
{
synchronized(this)
{
notifyAll();
System.out.println("Trying to notify");
}
}
public void run()
{
try
{
synchronized(this)
{
wait();
System.out.println("Notified");
}
}
catch(InterruptedException e) {}
}
public static void main(String[] args)
{
TestThread t1 = new TestThread();
t1.start();
t1.restart();
}
}
Choose one answer.
a. "Trying to Notify" is printed followed by "Notified"
b. "Trying to Notify" alone is printed
c. No output
d. Compiler error
e. Throws an exception at runtime
Choice D is the correct answer.

The code gives compiler error in the static method startMe(). As you know, static methods do not have a "this" reference and cannot access instance members. So synchronizing on the current object and invoking notifyAll() are not allowed here.

Since the code does not compile, choices A, B, and C are automatically incorrect.
Correct
Marks for this submission: 1/1.

Re: oracle java 6 certification exam mock questions

PostPosted: Fri Mar 02, 2012 11:07 am
by tomrff
Question
28
Which of the following statements regarding the wait() method are correct? Select three choices.
Choose at least one answer.
a. It is an instance method of Object class.
b. It is a static method of the Object class.
c. It is an instance method of Thread class.
d. The Thread must have a lock on the object on which the wait() method is to be invoked.
e. An object can have only one Thread in a waiting state at a time.
f. It must be called in a synchronized code.
Choices A, D, and F are the correct answers.

The wait() method is an instance (non-static) method of the Object class. Thus, choices B and C are incorrect.

The Thread must have a lock on object on which the wait() method is to be invoked, otherwise IllegalMonitorStateException is thrown at runtime. The wait() and notify() methods must be called in a synchronized code.

Choice E is incorrect as there can be any number of Threads waiting for an object at a time.

Check out the API for more about the wait and notify methods:
http://java.sun.com/j2se/1.5.0/docs/api ... bject.html
Correct
Marks for this submission: 1/1.

Question
29
Which of the following are legal? Select three choices.
Choose at least one answer.
a. int myArray1[10];
b. int myArray2[];
c. int myArray3[] = new int[10];
d. int myArray4[10] = new int[10];
e. int []myArray5 = new int[10];
f. int myArray6[] = new int[];
Choices B, C, and E are the correct answers.

You can't specify the array dimension in the type declaration (left hand side), so choices A and D are incorrect. In choice F, the array size is missing (right hand side), so choice F is also incorrect.

Choices B, C, and E are all valid declarations.
Correct
Marks for this submission: 1/1.

Question
30
Which of the following are legal identifiers? Select three choices.
Choose at least one answer.
a. !done
b. publicprotected
c. hello-world
d. $34
e. _we45$
Choices B, D, and E are the correct answers.

A valid identifier must start with a letter, a dollar sign ($), or an underscore (_) and the subsequent characters may be letters, dollar signs, underscores, or digits. Also, the identifier must not be a keyword. Choice B is correct because it starts with a letter and is not a keyword. Choices D and E are correct since starting with a $ or _ is fine.

Choice A is incorrect because it is illegal to start with a "!" character.

Choice C is incorrect because "-" character must not be present.
Correct
Marks for this submission: 1/1.

Question
31
What will be the result of compiling and running the following code?

class MyOuter
{
private class MyInner
{
private float f()
{
return 1.2;
}
}

MyInner getInner()
{
return new MyInner();
}

float getValue()
{
return getInner().f();
}
}

class Test
{
public static void main(String[] args)
{
MyOuter outer = new MyOuter();
System.out.println(outer.getValue());

}
}
Choose one answer.
a. Prints 1.2
b. Compiler error : Cannot access the functions of a private inner class
c. Compiler error : Cannot access the private method of the inner class
d. None of the above
Choice D is the correct answer.

This program does not compile, but the reason has nothing to do with inner classes. The function
f() has been declared to return a variable of type float. But the value returned is of type double because double is the default type for floating point numbers in Java. So the compiler complains of possible loss of
precision.

MyInner is a private inner class, so you cannot access it directly from outside code, for example,

new MyOuter().new MyInner().f();

will give compiler error. But in the given program we call the inner class method from a method of the outer class, which is allowed.
Correct
Marks for this submission: 1/1.

Question
32
Which of the following import statements are legal? Select two choices.
Choose at least one answer.
a. import java.lang;
b. static import java.lang.Math;
c. import java.lang.Math;
d. import static java.lang.Math.*;
e. static import java.lang.Math.*;
Choices C and D are the correct answers.

The static import construct allows unqualified access to static members without inheriting from the type containing the static members.

Whereas the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

Choice C is correct because it imports the Math class correctly.

Choice D is correct because it imports the static members of Math class correctly.

Choice A is incorrect because you can only import classes or interfaces from a package, and not the package itself.

Choices B and E are incorrect because the static keyword must follow the import keyword in a static import.

To know more about static imports, refer to
http://java.sun.com/docs/books/jls/thir ... html#7.5.3
http://java.sun.com/j2se/1.5.0/docs/gui ... mport.html
Correct
Marks for this submission: 1/1.

Question
33
What will happen when you attempt to compile and run the following class?

class Base
{
Base(int i)
{
System.out.println("Base");
}
}

class Derived extends Base
{
public static void main(String[] argv)
{
Derived d = new Derived();
}
void Derived()
{
System.out.println("Derived");
}
}
Choose one answer.
a. Compiles fine and prints "Derived" at runtime
b. Compiler error
c. Compiles fine but no output is produced
d. Compiles fine and prints "Base" at runtime
Choice B is the correct answer.

When an object of the Derived class is constructed in the main method, a super() call is automatically made by the constructor of the class. However, there is no matching constructor (no-args constructor) in the super class. So, the code causes a compiler error.

The compiler would have provided a default constructor, if no constructors had been written in the base class. However, in this case, the base class already defines a single argument constructor. So, no default constructor is provided.

Since the code does not compile, all the other choices are incorrect.
Correct
Marks for this submission: 1/1.

Question
34
What is the result of compiling and executing the following code?

class Vararg2
{
public static void main(String[] args)
{
Integer i[]={1,2,3,4};
test(i);
test();
}
public static void test(int... s)
{
for(int i : s)
System.out.printf(" %d \n", i);
}
}
Choose one answer.
a. Does not compile because test(Integer[]) cannot be applied to test(int?)
b. Does not compile because there test() cannot be applied to test(int?)
c. Prints 1,2,3,4
d. None of these
Choice A is the correct answer.

The void test(int...) method cannot match the test(i) invocation because i is of type Integer[]. Though Integer can be boxed into int type, Integer[] cannot be boxed to int[]. So the code does not compile.

Variable arguments (varargs) methods can be invoked with zero arguments also, so choice B is incorrect.

Since the code does not compile, choice C is incorrect.

Choice A is correct, thus, choice D is automatically incorrect.

Refer the following link to learn more on how to use varargs.
http://java.sun.com/j2se/1.5.0/docs/gui ... rargs.html

Correct
Marks for this submission: 1/1.

Question
35
What is the result of attempting to compile and run the following code?

abstract class SuperTest
{
static int i=10;
}
class Test extends SuperTest implements Inter
{
final static int i;
static { i=9; }
void f()
{
System.out.println("i is "+i);
}
public static void main(String[] args)
{
Inter t = new Test();
t.f();
}
}
interface Inter
{
int i= 1;
void f();
}
Choose one answer.
a. Code does not compile because you cannot extend a class and implement an interface at the same time.
b. Code does not compile because SuperTest does not contain any abstract methods.
c. Code does not compile because a final static variable cannot be initialized in a static block.
d. Code compiles and prints 9.
e. Code compiles and prints 1.
f. None of the above.
Choice F is the correct answer.

The code does not compile, but not because of any of the given reasons. As you know, interface methods are implicitly public.

When you implement the method in your class, you have to declare the method as public too otherwise you are violating the overriding rule which states that the overriding method cannot have weaker access privileges than the overridden method. Here if you make the f() method public in the Test class, it compiles fine and prints 9.

Choice A is incorrect because you can extend a class and implement an interface at the same time.

Choice B is incorrect because an abstract class need not have any abstract methods.

Choice C is incorrect because a final static variable can be initialized at the time of declaration or in a static block.
Correct
Marks for this submission: 1/1.

Question
36
import java.util.*;

public class Test
{
void f()
{
System.out.println("Outer");
}
public class InnerTest
{
InnerTest()
{
System.out.println("Inner constructor");
}
void f()
{
System.out.println("Inner f");
}
}
public static void main(String[] args)
{
Test t=new Test();
Test.InnerTest test=t.new InnerTest()
{
public void f()
{
t.f();
System.out.println("Sub Inner f");
}
};
test.f();
}
}
Choose one answer.
a. Code does not compile
b. Prints "Inner Constructor", "Outer" and "Sub Inner f"
c. Prints "Outer" and " Sub Inner f"
d. Prints "Outer", "Inner f" and "Sub Inner f"
e. Prints "Inner Constructor", "Outer", "Inner f" and "Sub Inner f"
f. None of the above
Choice A is the correct answer.

The given code does not compile because we are attempting to access the method local variable t, from within the local anonymous inner class. A method local class can access local variables in the enclosing method only if the variables are final. So the compiler gives an error. Since the code does not even compile, no output is produced. So all the other choices are incorrect.

Reference:
http://java.sun.com/docs/books/tutorial ... asses.html
Correct
Marks for this submission: 1/1.

Question
37
Given the following code for the Demo class, what would be the result of calling the showName() method with an argument of 0 immediately after creating an instance of Demo?

1. public class Demo
2. {
3. private String userNames[];
4. public Demo()
5. {
6. userNames = new String[10];
7. }
8. public void showName(int n)
9. {
10. System.out.println("Name is " + userNames[n]);
11. }
12.
13. public String getName(int n)
14. {
15. return(userNames[n]);
16. }
17. }
Choose one answer.
a. Prints "Name is null".
b. A NullPointerException would be thrown.
c. An ArrayIndexOutOfBoundsException would be thrown.
d. Prints "Name is ".
Choice A is the correct answer.

When an array is created using the new operator, all its elements are automatically initialized to the default values for that particular data type. So the elements of the array userNames are initialized to null value, which is the default value for object reference types. So the output is "Name is null", hence choice A is correct while choice D is incorrect.

No NullPointerException is thrown; hence, choice B is incorrect.

Since the array index 0 is valid for the first element, no ArrayIndexOutOfBoundsException is thrown. So choice C is also incorrect.
Correct
Marks for this submission: 1/1.

Question
38
What is the result of compiling and running the following code?

interface Inter{}
class First implements Inter
{
public Inter method1()
{
System.out.println("super");
return new First();
}
}

class Second extends First
{
public First method1()
{
System.out.println("sub");
return new Second();
}
}

public class CovariantTest2
{
public static void main(String[] args)
{
First first=new Second();
Inter first1=first.method1();
}
}
Choose one answer.
a. Does not compile
b. ClassCastException is thrown
c. Prints "super"
d. Prints "sub"
Choice D is the correct answer.

The code demonstrates the use of covariant return types i.e., the return type of the overriding method is a subtype of the return type of the overridden method.

Here the super type is an interface, which is perfectly legal. The object of Second class has been assigned to a variable declared to be of type First. This is also allowed since the Second class is a subclass of the First class. Since the code compiles without errors, choice A is incorrect.

Overriding comes into play here, so even though the declared type of the variable first is First, the method invoked is that of Second class. So the output is "sub". Thus choice C is incorrect while choice D is correct.

To know more about the covariant return types feature, refer to:
http://java.sun.com/developer/JDCTechTi ... t1201.html
Correct
Marks for this submission: 1/1.

Question
39
Choose the option that will compile without any errors.
Choose one answer.
a. ArrayList <String[]> s=new ArrayList<String[]>();
for(String[] arr : s)
for(String str : arr)
System.out.print(str); for(String[] arr : s)
for(String str : arr)
System.out.print(str);

b. ArrayList <String[]> s=new ArrayList<String[]>();
for(String str : s)
System.out.print(str);
c. ArrayList <String> s=new ArrayList<String>();
for(String[] arr : s)
System.out.print(arr);
ANSWER : A

Explanation:
The enhanced for loop is of the form

for ( VariableModifiersopt Type Identifier: Expression)

Here, we use two enhanced for loops: one to iterate through the ArrayList and another for each of its String[] elements.

For each iteration of the outer loop, we get a String[] object which is then iterated over to get its String elements.

Reference:
http://java.sun.com/docs/books/tutorial ... s/for.html
Correct
Marks for this submission: 1/1.

Question
40
What will happen when you attempt to run the following code from the command line using the command - java AssertTest?

(Assume that the code is compiled with assertions enabled.)

1. public class AssertTest
2. {
3. static int i = 10;
4. public static void main(String[] args)
5. {
6. i = i*2;
7. try
8. {
9. assert isValid() : i = i/4;
10. } catch(AssertionError ignore){}
11.
12. System.out.println("i = " +i);
13. }
14.
15. public static boolean isValid()
16. {
17. i = i * 2;
18. return false;
19. }
20. }
Choose one answer.
a. It will print - i = 20
b. It will print - i = 10
c. It will print - i = 40
d. It will print - i = 5
e. None of these
Choice A is the correct answer.

The code will print - i = 20. It is important to understand when the assert statement gets executed. Note that this code is run without enabling the assertions. The command - java AssertTest does not use any command line switch to enable the assertions in the AssertTest class. However, as stated in the question, the code is compiled with assertions enabled. Let's look at the execution of the code.

At line 3, a static int i is assigned the value 10. When the main method starts executing, at line 6 the value of i becomes 20. Next, since assertions are NOT enabled while running the program, the statement at line 9 is not executed. Hence, the isValid() method is not invoked in this execution.

It is very important to understand that assert statements get executed conditionally, depending upon whether the assertions are enabled or disabled at runtime. Hence, assert statement should not have any side effects and should not alter the state of the object (unlike this code).

The next statement, the print statement at line 12 prints the value of i, which is 20. Since the value of i has not been altered after line 6, the code will print - i = 20.

Want to know more? You can read more about assertions, their usage, and how to enable or disable them at -http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html
Correct
Marks for this submission: 1/1.

Question
41
Which methods can legally be inserted after the comment //XX? Select four choices.

class Parent
{
public void amethod(int i) throws IOException, RuntimeException
{
?
}
}
public class Child extends Parent
{
//XX
}
Choose at least one answer.
a. public void amethod(int i) throws FileNotFoundException{}
b. public void amethod(int i) throws IOException, RuntimeException{}
c. public void amethod(int i) throws RuntimeException{}
d. public void amethod(int i) throws Exception{}
e. public void amethod(int i){}
f. public void amethod(int i) throws Throwable{}
Choices A, B, C, and E are the correct answers.

The overriding method is not allowed to throw new or wider checked exceptions than what is thrown by the overridden method. However, there are no restrictions on throwing unchecked exceptions.

Choice A compiles because FileNotFoundException thrown by the overriding method is a subclass of IOException thrown by the overridden method.

Choice B is legal because IOException can be thrown in the superclass method and there are no restrictions on RuntimeException since it is unchecked.

Choice C is correct because of the same reason.

Choices D and F are incorrect since Exception and Throwable are wider than IOException and hence cannot be thrown.

Reference:
http://java.sun.com/docs/books/jls/thir ... tions.html
Correct
Marks for this submission: 1/1.

Question
42
Which of the following will be part of the output if the given code fragment is executed? Select three choices.

for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if (i != j)
{
continue;
}
System.out.println("i = " + i + " j = " + j);
}
}
Choose at least one answer.
a. i = 0 j = 0
b. i = 1 j = 2
c. i = 1 j = 1
d. i = 2 j = 2
e. i = 5 j = 5
Choices A, C, and D are the correct answers.

Since the inner loop executes a continue statement whenever i and j are not equal and the value is printed after the continue statement, only choices A, C, and D are correct.

Choice E will never occur as it is out of bounds, choice B will not occur because the continue statement will skip the execution.
Correct
Marks for this submission: 1/1.

Question
43
Suppose a NullPointerException is thrown by the test() method. Which message is displayed? Select three choices.

void Method()
{
try
{
test();
System.out.println("Message1");
}
catch (RuntimeException e)
{
System.out.println("Message2");
}
finally
{
System.out.println("Message3");
}
System.out.println("Message4");
}
Choose at least one answer.
a. Message1
b. Message2
c. Message3
d. Message4
Choices B, C and D are the correct answers.

When an exception occurs in the try block, the statements below it, within the try block, are not executed. So "Message1" is not printed, thus choice A is incorrect.

RuntimeException is the superclass of NullPointerException, so the control moves to that catch block when the exception is thrown. Here the output is "Message2". After the catch block completes, the control moves to the finally block, so "Message3" is also printed.

Once the finally block is over, the remaining code is also executed printing "Message4", which makes choice D also correct.

Reference:
http://java.sun.com/docs/books/tutorial ... dling.html
Correct
Marks for this submission: 1/1.

Question
44
Which of the following is the most appropriate code snippet that can be inserted at line 18 in the following code?
(Assume that the code is compiled and run with assertions enabled.)

1. import java.util.*;
2.
3. public class AssertTest
4. {
5. private HashMap cctld;
6.
7. public AssertTest()
8. {
9. cctld = new HashMap();
10. cctld.put("in", "India");
11. cctld.put("uk", "United Kingdom");
12. cctld.put("au", "Australia");
13. // more code...
14. }
15. // other methods ....
16. public String getCountry(String countryCode)
17. {
18. // What should be inserted here?
19. String country = (String)cctld.get(countryCode);
20. return country;
21. }
22. }
Choose one answer.
a. assert countryCode != null;
b. assert countryCode != null : "Country code can not be null" ;
c. assert cctld != null : "No country code data is available";
d. assert cctld : "No country code data is available";
e. assert cctld.size() != 0 : "No country code data is available";
Choice C is the correct answer.

Among the given choices, the code snippet -

assert cctld != null : "No country code data is available";

gives the most appropriate code snippet that can be inserted at line 18. This may sound strange, but assertions should be used to check for conditions that should never happen.

In this code, the constructor of the class creates a HashMap that contains country codes and their respective countries. Whenever an object of this class is created, one may assume that the HashMap object cctld will be created. But, there is a possibility that other methods may alter the HashMap, and could even make it null. Hence, it is appropriate to check that cctld is not null.

Let us now discuss why other choices are not really appropriate in this situation.

Java insists that assertions should not be used to check validity of arguments of a public method; this should be done using exceptions. This is justified for two reasons -
Exceptions can be explicitly mentioned in the throws cause of the method and checked exceptions must be caught while invoking the method.
Assertions can be disabled while running the code.
Hence, choices A and B are incorrect. Besides, passing null to the get method of HashMap will not result in an error or exception.

Choice D will not even compile, the first expression of an assert statement must be a boolean. Hence choice D is incorrect.

Choice E apparently looks quite appropriate, but when assertions are disabled, a HashMap with no entries will not cause any exception or error if its get() method is called with any key. Checking if the size of the HashMap is zero, and throwing an exception in that case, must be part of the program logic itself.

That leaves us with choice C. Assume that if any other method makes cctld null, the call cctld.get(countryCode);at line 19 will result in a NullPointerException. The code snippet in choice C will ensure that if this assert statement evaluates to true, the call at line 19 will not result in an error or exception. Hence, among the given choices, C is the most appropriate choice.

In real life code, very often such data comes from the database; and complex data structures are created conditionally. In such cases, usage of assertions as shown above provides the necessary sanity checks.

Want to know more? You can read more about assertions, their usage, how and when to use them appropriately at -
http://java.sun.com/j2se/1.4/docs/guide ... ssert.html
Correct
Marks for this submission: 1/1.

Question
45
What will happen when you attempt to run the following code from the command line using command - java AssertDemo?
(Assume that the code is compiled with assertions enabled.)

1. public class AssertDemo
2. {
3. public static void main(String args[])
4. {
5. boolean assertEnabled = false;
6.
7. assert assertEnabled = true;
8.
9. System.out.println("Assertions are " +
10. (assertEnabled ? "enabled" : "disabled"));
11. }
12. }
Choose one answer.
a. It will throw an AsertionError.
b. The code will not compile, compilation error at line 7.
c. It will print - Assertions are disabled.
d. It will print - Assertions are enabled.
e. None of these.
Choice C is the correct answer.

The code will compile and run without any error and it will print - Assertions are disabled. Note that this code is run without enabling the assertions. The command - java AssertDemo does not use any command line switch to enable the assertions in the class AssertDemo. However, as stated in the question, the code is compiled with assertions enabled.

There is nothing wrong with line 7, and it will compile without any error. The expression assertEnabled = true; is indeed a boolean expression that yields true. The single "=" operator performs an assignment rather than a comparison. In this particular case, this side effect is desired. Otherwise, an assert statement should have no side effects, and should not alter the state of the object.

The statement at line 5 assigns false to a variable assertEnabled. Since the program is run without enabling the assertions, the statement at line 7 is not executed, and hence the value of assertEnabled remains false. So print statement at line 9-10 prints - Assertions are disabled.

If the same code is run from command line with command - java -ea AssertDemo, it will enable the assertions and will print - Assertions are enabled. But with the given statement, only choice C is correct.

Want to know more? You can read more about assertions, their usage, and how to enable or disable them at -
http://java.sun.com/j2se/1.4/docs/guide ... ssert.html
Correct
Marks for this submission: 1/1.

Question
46
Which of the following access are illegal for the getMe() method in class B?

class A
{
void getMe(){}
}
class B extends A
{
void getMe(){}
}
Choose one answer.
a. public
b. protected
c. private
d. default
Choices C is the correct answer.

When you override a method, the overriding method must not have a less restricted access than the overridden method. Thus, a method with no access modifier (default access) may be overridden to be of default, protected or public access.

Since private is more restricted than default access, it is not allowed, while all the others are allowed. So choice C is correct and the others are incorrect.
Correct
Marks for this submission: 1/1.

Question
47
What will be the output when you compile and execute the following program?

public class Base
{
private void test()
{
System.out.println(6 && 3);
}
static public void main(String[] a)
{
new Base().test();
}
}
Choose one answer.
a. Prints true
b. Prints false
c. Prints 9
d. Prints 2
e. Compiler error : Incorrect declaration of main method
f. None of these
Choice F is the correct answer.

The code does not compile because the && operator works only with boolean operands. If both operands are true, the && operator returns true and false in all the other cases. In this case, integer operands are passed to the && operator, so the code does not compile. Since the code does not compile, choices A to D are incorrect.

Choice E is incorrect because there is nothing wrong with the declaration of the main method. The modifiers public and static can appear in any order. Also, the main method takes a String[] as the argument.
Correct
Marks for this submission: 1/1.

Question
48
Given the class CommandLineTest

class CommandLineTest
{
public static void main(String[] args)
{
System.out.print(____);
}
}

Which of the following expressions can be passed to the print method to output 2, if you execute the class using the following command

java -cp . CommandLineTest 3 "+" 2 "=" 5
Choose one answer.
a. args[0]
b. args[1]
c. args[2]
d. args[3]
e. None of these
Choice C is the correct answer.

The command-line arguments passed to the java command are read into the args array.

The class name is not included in the command-line arguments. So args[0] returns 3, args1 returns "+", args2 returns 2 and so on. So C is correct and the other choices are automatically incorrect.

Reference:
http://docs.oracle.com/javase/tutorial/ ... eArgs.html
Correct
Marks for this submission: 1/1.

Question
49
What is the result of compiling and executing this code?

class PassTest
{
int i=3;
}
public class Test
{
public static void xx(PassTest p)
{
p.i=10;
}
public static void yy(PassTest p)
{
p=new PassTest();
}
public static void main(String[] args)
{
PassTest passTest=new PassTest();
xx(passTest);
System.out.println(passTest.i);
yy(passTest);
System.out.println(passTest.i);
}
}
Choose one answer.
a. Does not compile
b. Prints 3 10
c. Prints 3 3
d. Prints 10 10
e. Prints 10 3
Choice D is the correct answer.

When a method which takes an object argument is invoked, the method obtains a copy of the object reference from the calling method. Both the original reference variable and the copy refer to the same object in memory. So, altering the object within the method affects the original object itself.

In the xx() method, setting i=10 using p, alters the object which is referenced by both p and passTest variables. So 10 is output when the value of i is printed. However, in the yy() method, the argument variable p is made to refer to a new PassTest object.

This does not affect the reference variable passTest in the original method. So passTest still refers to the object which has the value of i set to 10. So the output is 10 again.

Since choice D is correct, all the other choices are automatically incorrect.
Correct
Marks for this submission: 1/1.

Question
50
What results from running the code below?

int a = -5;
int b = -2;
System.out.println(a % b);
Choose one answer.
a. 0
b. 1
c. -1
d. A compiler error saying "%" operator is not valid for negative numbers.
Choice C is the correct answer.

To calculate a % b (a modulus b), the simplest way is to drop any negative signs from both the operands and compute the result.

Now, if the left-hand side operand is negative, negate the result, the sign of the right-hand side operand doesn't matter. In our case (-5 % -2) is equal to -(5 % 2) = -(1) = -1, hence choice C is correct.
Correct
Marks for this submission: 1/1.

Question
51
What will be the output when you compile and execute the following program?

class Test
{
public static void main(String[] args)
{
1. Boolean b1 = true;
2. boolean b2 = false;
3. System.out.print(!b1 ^ b2);
4. System.out.print(b1 & (b2 = true));
5. System.out.println(b2 && (b1 | b2));
}
}
Choose one answer.
a. truetruetrue
b. falsetruetrue
c. falsefalsefalse
d. truetruefalse
e. truefalsetrue
f. Code does not compile
Choice B is the correct answer.

The ^ (xor) operator returns true if exactly one operand is true.

The ! operator inverts the operand's boolean value. In line 3, the expression (!b1 ^ b2) yields false because both operands evaluate to false.

In line 4, b2 is assigned a true value, so b1 & b2 is true. Since both b1 and b2 are true, line 5 also results in an output of true.
Correct
Marks for this submission: 1/1.

Question
52
Which of the following statements are true? Select two choices.
Choose at least one answer.
a. Garbage collection is performed by a low priority daemon thread.
b. Garbage collection always uses a mark and sweep algorithm
c. The finalize() method is invoked for objects in the order in which they were created
d. The finalize() method is typically used to free up resources other than memory
e. Objects that are created and accessed locally within a method, are eligible for garbage collection when the method returns.
Choices A and D are the correct answers.

The finalize() method is typically used to free up resources like files, network connections etc. Freeing the memory is the job of the garbage collector only. Garbage collection is performed by a low priority daemon thread, which dies when no more user threads are running. So choices A and D are correct.

The algorithm used for garbage collection is dependent on the vendor, so choice B is incorrect. The order in which the finalize() methods are invoked cannot be predicted, it is not dependent on the order in which the objects were created. So choice C is also incorrect.

Objects that are created and accessed locally within a method are eligible for garbage collection, after the method terminates, unless references to these objects are exported out of the method.So choice E is also incorrect.

Want to know more? You can read more about garbage collection at -
http://java.sun.com/docs/books/performa ... GC.fm.html
http://www.developer.com/tech/article.php/628881

Also, the API documentation of the Object class contains the necessary information about the finalize() method - http://java.sun.com/j2se/1.4/docs/api/j ... bject.html
Correct
Marks for this submission: 1/1.

Question
53
Assume that MyClass is a class which defines two methods f() and g(). How many objects would be eligible for garbage collection by the time the method g() is invoked?

MyClass c1 = new MyClass();
MyClass c2 = new MyClass();
f(c1);
c1=null;
c2=c1;
g();
Choose one answer.
a. 1
b. 2
c. 0
d. The given information is insufficient
Choice D is the correct answer.

The reference to c1 has been passed to a method and the method body is not shown here. We do not know if the function is passing this object's reference to other live threads.

So we cannot be sure that the object referred to by c1 is eligible for garbage collection or not. Thus, the information is insufficient to predict the result.
Correct
Marks for this submission: 1/1.

Question
54
What will be the result of compiling and running the following code?

class SuperTest
{
SuperTest() throws Exception { }
int f()
{
return 0;
}
}

public class Test extends SuperTest
{
int i;
int f()
{
return i;
}
Test(int i)
{
this.i=i;
}
public static void main(String[] args)
{
SuperTest t=new Test(5);
System.out.println(t.f());
}
}
Choose one answer.
a. Code does not compile
b. Prints 0
c. Prints 5
d. Exception is thrown at runtime
Choice A is the correct answer.

The code does not compile because the superclass constructor throws an Exception which is not handled in the subclass constructor. So the compiler complains.

The subclass constructor makes an implicit call to the superclass parameterless constructor. So it has to catch the Exception or declare it in a throws clause.
Correct
Marks for this submission: 1/1.

Question
55
What will be the result of an attempt to compile and run the following code?

class SuperBase{}
class Base extends SuperBase{}
class Derived extends Base{}
public class Test
{
public static void main(String[] args)
{
SuperBase[] s1 = new Base[2]; //1
SuperBase[] s2 = new Derived[1]{new Derived()}; //2
Base[] b1 = new Derived[0]; //3
Derived[] d1 = (Derived[])s2; //4
Base[] b3 = d1; //5
s1 = b1; //6
}
}
Choose one answer.
a. Compiler error at line 1
b. Compiler error at line 2
c. Compiler error at line 3
d. Compiler error at line 4
e. Compiler error at line 5
f. Compiler error at line 6
g. Compiles and runs without errors
h. Throws ClassCastException at runtime
Choice B is the correct answer.

This is a tricky question, here the problem is with the array creation syntax.

When we use this syntax to create arrays, we should not specify the size, the size is evaluated from the number of elements between the curly braces. Here the declaration should be changed to new Derived[]{new Derived()}.

Other than this there are no errors in this program. A derived class array can be assigned to a base class array. So all the other assignments are valid. It is legal to make an array of size 0 also.
Correct
Marks for this submission: 1/1.

Question
56
What will be the result of an attempt to compile and run the following code?

class Test
{
static Object test="hello";
void f(Object x)
{
System.out.print("Object");
}
void f(String x)
{
System.out.print("String");
}
void f(StringBuffer x)
{
System.out.print("StringBuffer");
}
public static void main(String[] args)
{
Test t=new Test();
t.f(test);
}
}
Choose one answer.
a. Prints "String"
b. Prints "StringBuffer"
c. Prints "Object"
d. Compiler complains about an ambiguous method call
e. Exception thrown at runtime
f. None of the above
Choice C is the correct answer.

Here the method f is overloaded with Object, String and StringBuffer arguments. The String literal "hello" is assigned to the variable test which is of Object type. Here even though the actual object passed is String type, the object reference is of Object type.

The Object type can be assigned only to an Object type reference variable, so the only method which matches in this case is the one which takes Object as the argument.

So there is no ambiguity here, the output is "Object".
Correct
Marks for this submission: 1/1.

Question
57
Given the following class definition, which of the following methods could be legally placed after the comment //Here? Select two choices.

1. public class Rid
2. {
3. public void aMethod(int i, String s){}
4. //Here
5. }
Choose at least one answer.
a. public void aMethod(String s, int i) {}
b. public int aMethod(int i, String s) {}
c. public void aMethod(int i, String mystring) {}
d. public void AMethod(int i, String s) {}
Choices A and D are the correct answers.

Choice A is correct because it is a valid case of method overloading, where the list of arguments is different.

Choice B is incorrect because the argument list is not different, it is not enough if the return type alone differs.

Choice C is incorrect because the same method definition has been repeated, it is not enough to have a different variable name for the argument.

Choice D is correct because the method name is different, so it is treated as just another method in that class.
Correct
Marks for this submission: 1/1.

Question
58
Which of the following is true about the takeOrdersAndServe() method in the below code?

class Waitor
{
void takeOrders(){}
void serveFood(){}
void takeOrdersAndServe()
{
takeOrders();
serveFood();
}
}
Choose one answer.
a. It exhibits high cohesion
b. It exhibits low cohesion
c. It exhibits tight coupling
d. It exhibits loose coupling
Choice B is the correct answer.

Cohesion refers to the number and diversity of tasks that a single unit is responsible for. If each unit is responsible for one single logical task, we say it has high cohesion.

Cohesion applies to classes and methods. Here the takeOrdersAndServe() method is not focused on a single task, so it shows low cohesion. A well designed unit will have high cohesion.

Correct
Marks for this submission: 1/1.

Question
59
A Vehicle has an owner and a registration number. A Car is a Vehicle that has a steering wheel and a model name. Choose the fields which must be included in the Car class. (The Vehicle class is already defined) Select two choices.
Choose at least one answer.
a. Steering s;
b. Person owner;
c. String registrationNo;
d. String modelName;
e. Vehicle c;
Choices A and D are the correct answers.

Since a Vehicle has an owner and a registration number, the class Vehicle looks like this.

class Vehicle
{
Person owner;
String registrationNo;
}

As a Car is a Vehicle, Car is a subclass of class Vehicle. So the Car class inherits the fields owner and registration number from the Vehicle class. So the Car class only needs to declare the fields Steering s and String modelName.

class Car extends Vehicle
{
Steering s;
String modelName;
}

So choices A and D are correct, while the other choices are incorrect.

Reference:
http://cnx.rice.edu/content/m11709/latest/
Correct
Marks for this submission: 1/1.

Question
60
What will be the result of compiling and running the following code?

class SuperTest
{
int f()
{
return 0;
}
}
public class Test extends SuperTest
{
int i;
protected int f() throws Error
{
return i;
}
Test(int i)
{
this.i=i;
}
public static void main(String[] args)
{
SuperTest t=new Test(5);
System.out.println(t.f());
}
}
Choose one answer.
a. Prints 0
b. Prints 5
c. Code does not compile, a method with default access cannot be overridden as protected.
d. Code does not compile, a method in the subclass cannot throw exceptions not thrown by the overridden method
e. None of the above
Choice B is the correct answer.

The code compiles without errors and prints 5.

Choice C is not valid because protected is more public than default access, so you can override a default method to be protected.

Error and RuntimeException are unchecked exceptions, so they can be thrown in the overriding subclass method even if the overridden method does not throw them.

The variable t is of type Test, so at runtime the method invoked is the method f() defined in the subclass. Thus 5 is printed.