Q-081
Give:
class Fibonacci extends RecursiveTask {
final int n;
Fibonacci(int n) {
this.n = n;
}
Integer compute() {
if (n <= 1) {
return n;
}
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join(); // Line X
}
}
Suppose that line X is replace with:
return f1.join()+f2.compute() ; // Line X
What is the likely result?
A. The program produces the correct result, with similar performance to the original.
B. The program produces the correct result, with performance degraded to the equivalent of being single-threaded.
C. The program produces an incorrect result.
D. The program goes into an infinite loop.
E. An exception is thrown at runtime.
F. The program produces the correct result, with better performance than the original.
Answer: A
Q-082
Given the following files in doc directory:
- Index.htm
- Service.html
- Logo.gif
- Title.jpg
And the code fragment:
public class SearchApp extends SimpleFileVisitor {
private final PathMatcher matcher;
Search App() {
matcher = Filesystems. getDefault().
getPathMatcher("glob:*.htm,html,xml");
}
void search(Path file) {
Path name = file.getFileName();
if(name != null && matcher.matches(name)) {
System.out.println(name);
}
}
public FileVisitResult visitFile (Path file, Basic FileAttribuites attris){
search (file);
return FileVisitResult.CONTINUE;
}
public static void main (String args) throws IOException{
Files.WalkFileTree(Paths.get("doc"), new SearchApp());
}
}
What is the result, if doc is present in the current directory?
A. No output is produced.
B. index.htm
C. index.htm userguide.txt logo.gif
D. index.htm service.html userguide.txt logo.gif
Answer: A
需要寫成 "glob:*.{htm,html,xml}"
Q-083
Given:
public class Test {
public static void main(String[] args) {
String[] arr = {"SE", "ee", "ME"};
for (String var : arr) {
try {
switch (var) {
case "SE":
System.out.println("Standard Edition");
break;
case "EE":
System.out.println("Enterprise Edition");
break;
default:
assert false;
}
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
}
And the commands:
javac Test.java
java -ea Test
What is the result?
A. Compilation fails
B. Standard Edition
Enterprise Edition
Micro Edition
C. Standard Edition
class java.lang.AssertionError
Micro Edition
D. Standard Edition is printed and an Assertion Error is thrown
Answer: D
"SE" 印出 "Standard Edition"
"ee" 產生Assertion Error, 但無法被Exception抓到, 所以往上報到JVM, 然後停止
Q-084
Given the classes:
class Pupil {
String name = "unknown";
public String getName() {return name;}
}
class John extends Pupil {
String name = "John";
}
class Harry extends Pupil {
String name = "Harry";
public String getName() {return name;}
}
public class Director {
public static void main(String[] args) {
Pupil p1 = new John();
Pupil p2 = new Harry();
System.out.print(p1.getName() + " ");
System.out.print(p2.getName());
}
}
What is the result?
A. John Harry
B. unknown Harry
C. john unknown
D. unknown unknown
E. Compilation fails.
F. An exception is thrown at runtime.
Answer: B
John p1=new John();
p1.getName() 還是 "unknow"
Q-085
Given the code fragment:
05 public static void displayDetails(){
06 try(BufferedReader br=
07 new BufferedReader(new FileReader("salesreport.dat"))){
08 String record;
09 while((record=br.readLine()!=null){
10 System.out.println(record);
11 }
12 br.close();
13 br=new BufferedReader(new FileReader("annualeport.dat"));
14 while((record=br.readLine())!=null){
15 System.out.println(record);
16 }
17 }catch(IOException e){
18 System.error.print(e.getClass());
19 }
20 }
What is the result, if the file salesreport.dat does not exist?
A. Compilation fails only at line 6
B. Compilation fails only at line 13
C. Compilation fails at line 6 and 13
D. Class java.io.IOException
E. Class java.io.FileNotFoundException
Answer: B
在try()裏的變數, 不可以再指定給其他的物件, 不然無法AutoCloseable
Q-086
Given:
01 import java.util.ArrayDeque;
02 import java.util.Deque;
03
04 public class Counter {
05 public static void main(String[] args) {
06 Deque deq = new ArrayDeque(2);
07 deq.addFirst("one");
08 deq.addFirst("two");
09 deq.addFirst("three");
10 System.out.print(deq.pollLast());
11 System.out.print(deq.pollLast());
12 System.out.print(deq.pollLast());
13 }
14 }
What is the result?
A. An exception is thrown at runtime on line 9.
B. An exception is thrown at runtime on line 12
C. one two null
D. one two three
E. two one null
F. three two one
Answer: D
add/poll為Queue, push/pop為stack
addFirst後的Queue 為{three, two, one} 所以pollLast為 one, two, three
first last
Q-087
Which class safely protects the doIt () method from concurrent thread access?
A. class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (s) {
System.out.println("Name:"+ s +"ID:"+ id++);
}
}
}
B. class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (new object () ) {
System.out.println("Name:"+ s +"ID:"+ id++);
}
}
}
C. class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (this) {
System.out.println("Name:"+ s +"ID:"+ id++);
}
}
}
D. class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (SafeMethod.class) {
System.out.println("Name:"+ s +"ID:"+ id++);
}
}
}
Answer: D
Q-088
Given:
interface Event {
String getCategory();
}
public class CueSports {
public String getCategory() {
return "Cue sports";
}
}
public class Snooker extends CueSports implements Event { // Line 9
public static void main(String[] args) {
Event obj1 = new Snooker(); // Line 11
CueSports obj2 = new Snooker(); // Line 12
System.out.print(obj1.getCategory() + ", " + obj2.getCategory());
}
}
What is the result?
A. Cue sports, Cue sports
B. Compilation fails at line 9
C. Compilation fails at line 11
D. Compilation fails at line 12
E. Compilation fails at line 13
Answer: A
Q-089
Which is a factory method from the java.text.NumberFormat class?
A. format (long number)
B. getInstance()
C. getMaxiraumFractionDigits ()
D. getAvailableLocales ()
E. isGroupingUsed()
Answer: B
Q-090
Given:
class InvalidAgeException extends IllegalArgumentException { }
public class Tracker {
void verify (int age) throws IllegalArgumentException {
if (age < 12) throw new InvalidAgeException ();
if (age >= 12 && age <= 60)
System.out.print("General category");
else
System.out.print("Senior citizen category");
}
public static void main(String[] args) {
int age = Integer.parseInt(args[1]);
try {
new Tracker().verify(age);
}
catch (Exception e) {
System.out.print(e.getClass());
}
}
}
And the command-line invocation:
Java Tracker 12 11
What is the result?
A. General category
B. class InvalidAgeException
C. class java.lang.IllegalArgumentException
D. class java.lang.RuntimeException
Answer: B
Exception可以捕抓到IlleagalArgumentException
Q-091
Which code fragment correctly appends "Java 7" to the end of the file /tmp/msg.txt?
A. FileWriter w = new FileWriter("/tmp/msg.txt");
append("Java 7");
close();
B. FileWriter w = new FileWriter("/tmp/msg.txt", true);
append("Java 7");
close();
C. FileWriter w = new FileWriter("/tmp/msg.txt", FileWriter.MODE_APPEND);
append("Java 7");
close();
D. FileWriter w = new FileWriter("/tmp/msg.txt", Writer.MODE_APPEND);
append("Java 7");
close();
Answer: B
Q-092
Given the code format:
SimpleDateFormat sdf;
Which code statements will display the full text month name?
A. sdf = new SimpleDateFormat ("mm", Locale.UK);
System.out.println("Result:", sdf.format(new date()));
B. sdf = new SimpleDateFormat ("MM", Locale.UK);
System.out.println("Result:", sdf.format(new date()));
C. sdf = new SimpleDateFormat ("MMM", Locale.UK);
System.out.println("Result:", sdf.format(new date()));
D. sdf = new SimpleDateFormat ("MMMM", Locale.UK);
System.out.println("Result:", sdf.format(new date()));
Answer: D
Q-093
Given:
class Car implements TurboVehicle, Steerable {
// Car methods
}
interface Convertible{
// Convertible methods
}
public class SportsCar extends Car implements Convertible {
}
Which statement is true?
A. SportsCar must implement methods from TurboVehicle and Steerable
B. SportsCar must override methods defined by Car.
C. SportsCar must implement methods define by Convertible.
D. Instances of Car can invoke Convertible methods.
Answer: C
A : 不是SportsCar, 是Car才需實作TuboVehicle及Steerable的方法
B : SportsCar不一定要覆蓋
D : Car 跟 Convertible一點關係也沒有
Q-094
Given:
public class Dog {
protected String bark() {
return "woof ";
}
}
public class Beagle extends Dog {
private String bark() {
return "arf ";
}
}
public class TestDog {
public static void main(String[] args) {
Dog[] dogs = {new Dog(), new Beagle()};
for (Dog d : dogs) {
System.out.print(d.bark());
}
}
}
What is the result?
A. woof arf
B. woof woof
C. arf arf
D. A RuntimeException is generated
E. The code fails to compile
Answer: E
Beagle的存取修飾子必需是protected或public
Q-095
Given:
1. interface Writable {
2. void write (String s);
3. }
4 .
5. abstract class Writer implements Writable {
6. // Line ***
7. }
Which two statements are true about the Writer class?
A. It compiles without any changes.
B. It compiles if the code void write (String s); is added at line***.
C. It compiles if the code void write (); is added at line ***.
D. It compiles if the code void write (string s) { } is added at line ***.
E. It compiles if the code write () {}is added at line ***.
Answer: AD
Q-096
Given the class
public class Name implements Comparable {
String first, last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public int compareTo (Name n) {
int cmpLast = last.compareTo(n.last);
return cmpLast != 0 ? cmpLast : first.compareTo(n.first);
}
public String toString() {
return first + " " + last;
}
}
and the code fragment:
ArrayList list = new ArrayList();
list.add (new Name("Joe","Shmoe"));
list.add (new Name("John","Doe"));
list.add (new Name("Jane","Doe"));
Collections.sort(list);
for (Name n : list) {
System.out.println(n);
}
What is the result?
A. Jane Doe
John Doe
Joe Shmoe
B. John Doe
Jane Doe
Joe Shmoe
C. Joe Shmoe
John Doe
Jane Doe
D. Joe Shmoe
Jane Doe
John Doe
E. Jane Doe
Joe Shmoe
John Doe
F. John Doe
Joe Shmoe
Jane Doe
Answer: A
Q-097
Given the code fragment:
01 public void infected() {
02 System.out.print("before ");
03 try {
04 int i = 1/0;
05 System.out.print("try ");
06 } catch(Exception e) {
07 System.out.print("catch ");
08 throw e;
09 } finally {
10 System.out.print("finally ");
11 }
12 System.out.print("after ");
13 }
What is the result when infected() is invoked?
A. before try catch finally after
B. before catch finally after
C. before catch after
D. before catch finally
E. before catch
Answer: D
注意, 因為第8行又重丟了e, 所以印出finally後就停止了.
如果沒有重丟e的話,那麼after也會被印出來
Q-098
Given the two Java classes:
public class Word {
private Word(int length) {}
protected Word(String w) {}
}
public class Buzzword extends Word {
public Buzzword() {
// Line ***, add code here
}
public Buzzword(String s) {
super(s);
}
}
Which two code snippets, added independently at line ***, can make the Buzzword class compile?
A. this ();
B. this (100);
C. this ("Buzzword");
D. super ();
E. super (100);
F. super ("Buzzword");
Answer: CF
E不可以, 因為父類別的Word(int length)是private
Q-099
Given:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
private static String REGEX = "\\Sto\\S|\\bo\\b";
private static String INPUT = "Nice to see you,to,be fine.";
private static String REPLACE =",";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
What is the result?
A. Nice to see you,be fine
B. Nice, see you,be fine
C. Nice, see you,to, be fine
D. Nice, see you,be fine
E. Nice to see y,u,be fine
Answer: A
\S : 非空白
\b : 字串開始或結尾
所以 ",to," 會被取代成 ","
Q-100
Given the following code fragment:
10. p1 = Paths.get("report.txt");
11. p2 = Paths.get("company");
12. / / insert code here
Which code fragment, when inserted independently at line 12, move the report.txt file to the company directory, at the same level, replacing the file if it already exists?
A. Files.move(p1, p2,
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
B. Files.move(p1, p2,
StandardCopyOption.REPLACE_Existing, LinkOption.NOFOLLOW_LINKS);
C. Files.move (p1, p2,
StandardCopyOption.REPLACE_EXISTING, LinkOption.NOFOLLOW_LINKS);
D. Files.move(p1, p2,
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.copy_ATTRIBUTES, StandrardCopyOp)
E. Files.move (p1, p2
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.copy_ATTRIBUTES, LinkOption.NOF)
Answer: A