0% found this document useful (0 votes)
51 views30 pages

CDJAVA

The document consists of multiple-choice questions related to Java programming concepts, including streams, exception handling, collections, and concurrency. Each question presents a code snippet and asks the reader to select the correct option based on the expected behavior or output of the code. The questions cover a wide range of topics, testing knowledge on Java syntax, functionality, and best practices.

Uploaded by

yuuwhisky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views30 pages

CDJAVA

The document consists of multiple-choice questions related to Java programming concepts, including streams, exception handling, collections, and concurrency. Each question presents a code snippet and asks the reader to select the correct option based on the expected behavior or output of the code. The questions cover a wide range of topics, testing knowledge on Java syntax, functionality, and best practices.

Uploaded by

yuuwhisky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Cau 1:Choose the correct option based on this code segment:

Stream<String> words = Stream.of("eeny", "meeny", "miny", "mo"); // LINE_ONE

String boxedString = words.collect(Collectors.joining(", ", "[", "]")); // LINE_TWO

System.out.println(boxedString);
a) This code results in a compiler error in line marked with the comment LINE_ONE
b) This code results in a compiler error in line marked with the comment LINE_TWO
c) This program prints: [eeny, meeny, miny, mo]
d) This program prints: [eeny], [meeny], [miny], [mo]

Cau2 :Given this code segment:


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String integer = br.readLine();
// CODE
System.out.println(val);

Which one of the following statements when replaced by the comment CODE
will successfully read an integer value from console?
a) int val = integer.getInteger();
b) int val = Integer.parseInt(integer);
c) int val = String.parseInt(integer);
d) int val = Number.parseInteger(integer);

Cau 3: Given this class definition:


public class AssertCheck {
public static void main(String[] args) {
int score = 0;
int num = 0;
assert ++num > 0 : "failed";
int res = score / num;
System.out.println(res);
}
}

Choose the correct option assuming that this program is invoked as follows:
java –ea AssertCheck
a) This program crashes by throwing java.lang.AssertionError with the
message “failed”
b) This program crashes by throwing java.lang.ArithmeticException with the
message “/ by zero”
c) This program prints: 0
d) This program prints “failed” and terminates normally

Cau 4: Given the definition:


class Sum implements Callable<Long> { // LINE_DEF
long n;
public Sum(long n) {
this.n = n;
}
public Long call() throws Exception {
long sum = 0;
for(long longVal = 1; longVal <= n; longVal++) {
sum += longVal;
}
return sum;
}
}
Given that the sum of 1 to 5 is 15, select the correct option for this code segment:
Callable<Long> task = new Sum(5);
ExecutorService es = Executors.newSingleThreadExecutor(); // LINE_FACTORY
Future<Long> future = es.submit(task); // LINE_CALL
System.out.printf("sum of 1 to 5 is %d", future.get());
es.shutdown();

a) This code results in a compiler error in the line marked with the comment
LINE_DEF
b) This code results in a compiler error in the line marked with the comment
LINE_FACTORY
c) This code results in a compiler error in the line marked with the comment
LINE_CALL
d) This code prints: sum of 1 to 5 is 15

Cau 5: Choose the correct option based on this code segment:


List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
ints.removeIf(i -> (i % 2 == 0)); // LINE
System.out.println(ints);

a) This code segment prints: [1, 3, 5]


b) This code segment prints: [2, 4]
c) This code segment prints: [1, 2, 3, 4, 5]
d) This code segment throws java.lang.UnsupportedOperationException
e) This code segment results in a compiler error in the line marked with the
comment LINE
Explain: Arrays.asList(1, 2, 3, 4, 5)

Trả về một danh sách không hỗ trợ thêm hoặc xóa phần tử (dù có thể thay đổi giá trị phần tử).

Cau 6: Choose the correct option based on this code segment:


LocalDate feb28th = LocalDate.of(2015, Month.FEBRUARY, 28);
System.out.println(feb28th.plusDays(1));

a) This program prints: 2015-02-29


b) This program prints: 2015-03-01
c) This program throws a java.time.DateTimeException
d) This program throws a java.time.temporal.
UnsupportedTemporalTypeException

Explain: Năm 2015 có phải năm nhuận không?

Không phải, vì năm 2015 không chia hết cho 4.

Do đó, tháng 2 năm 2015 chỉ có 28 ngày.

Cau 7: Choose the correct option for this code segment:


List<String> lines = Arrays.asList("foo;bar;baz", "", "qux;norf");
lines.stream()
.flatMap(line -> Arrays.stream(line.split(";"))) // FLAT
.forEach(str -> System.out.print(str + ":"));
a) This code will result in a compiler error in line marked with the comment FLAT
b) This code will throw a java.lang.NullPointerException
c) This code will throw a java.util.regex.PatternSyntaxException
d) This code will print foo:bar:baz::qux:norf:

Cau 8: Given the class definition:


class NullableBook {
Optional<String> bookName;
public NullableBook(Optional<String> name) {
bookName = name;
}
public Optional<String> getName() {
return bookName;
}
}
Choose the correct option based on this code segment:
NullableBook nullBook = new NullableBook(Optional.ofNullable(null));
Optional<String> name = nullBook.getName();
name.ifPresent(System.out::println).orElse("Empty"); // NULL

a) This code segment will crash by throwing NullPointerException


b) This code segment will print: Empty
c) This code segment will print: null
d) This code segment will result in a compiler error in line marked with NULL

Cau 9: Given the code segment:


List<Integer> integers = Arrays.asList(15, 5, 10, 20, 25, 0);
// GETMAX
Which of the code segments can be replaced for the comment marked with
GETMAX to return the maximum value?

a) Integer max = integers.stream().max((i, j) -> i - j).get();


b) Integer max = integers.stream().max().get();
c) Integer max = integers.max();
d) Integer max = integers.stream().mapToInt(i -> i).max();

Cau 10: Select all the statements that are true about streams (supported in
java.util.stream.Stream interface)?

a) Computation on source data is performed in a stream only when the terminal


operation is initiated, i.e., streams are “lazy”
b) Once a terminal operation is invoked on a stream, it is considered consumed
and cannot be used again
c) Once a stream is created as a sequential stream, its execution mode cannot
be changed to parallel stream (and vice versa)
d) If the stream source is modified when the computation in the stream is being
performed, then it may result in unpredictable or erroneous results

Cau 11: Given this class definition:


class Outer {
static class Inner {
public final String text = "Inner";
}
}

Which one of the following expressions when replaced for the text in place of
the comment /*CODE HERE*/ will print the output “Inner” in console?
class InnerClassAccess {
public static void main(String []args) {
System.out.println(/*CODE HERE*/);
}
}
a) new Outer.Inner().text
b) Outer.new Inner().text
c) Outer.Inner.text
d) new Outer().Inner.text

Cau 12: Given the following class and interface definitions:


class CannotFlyException extends Exception {}
interface Birdie {
public abstract void fly() throws CannotFlyException;
}
interface Biped {
public void walk();
}
abstract class NonFlyer {
public void fly() { System.out.print("cannot fly "); } // LINE A
}
class Penguin extends NonFlyer implements Birdie, Biped { // LINE B
public void walk() { System.out.print("walk "); }
}

Select the correct option for this code segment:


Penguin pingu = new Penguin();
pingu.walk();
pingu.fly();

a) Compiler error in line with comment LINE A because fly() does not declare to
throw CannotFlyException
b) Compiler error in line with comment LINE B because fly() is not defined and
hence need to declare it abstract
c) It crashes after throwing the exception CannotFlyException
d) When executed, the program prints “walk cannot fly”

Cau 13: For the following enumeration definition, which one of the following prints the
value 2 in the console?
enum Pets { Cat, Dog, Parrot, Chameleon };
a) System.out.print(Pets.Parrot.ordinal());
b) System.out.print(Pets.Parrot);
c) System.out.print(Pets.indexAt("Parrot"));
d) System.out.print(Pets.Parrot.value());
e) System.out.print(Pets.Parrot.getInteger());
Giải thích:
ordinal() trả về vị trí index (bắt đầu từ 0) của giá trị enum
Thứ tự: Cat(0), Dog(1), Parrot(2), Chameleon(3)
→ Parrot.ordinal() trả về 2

Cau 14: Which one of the following statements will compile without any errors?
a) Supplier<LocalDate> now = LocalDate::now(); //sai cu phap ()
b) Supplier<LocalDate> now = () -> LocalDate::now; //khong hop le
c) String now = LocalDate::now::toString; // sai cú pháp
d) Supplier<LocalDate> now = LocalDate::now;
Tương đương với: Supplier<LocalDate> now = () -> LocalDate.now();
Cau 15: Consider the following program and choose the correct option:
import java.util.concurrent.atomic.AtomicInteger; //là thao tác với int tăng/giảm/gán giá
class AtomicVariableTest {
private static AtomicInteger counter = new AtomicInteger(0);
static class Decrementer extends Thread {
public void run() {
counter.decrementAndGet(); // #1
}
}

static class Incrementer extends Thread {


public void run() {
counter.incrementAndGet(); // #2
}
}
public static void main(String []args) {
for(int i = 0; i < 5; i++) {
new Incrementer().start();
new Decrementer().start();
}
System.out.println(counter);
}
}
a) This program will always print 0
b) This program will print any value between -5 to 5
c) If you make the run() methods in the Incrementer and Decrementer classes
synchronized, this program will always print 0
d) The program will report compilation errors at statements #1 and #2

Cau 16: Consider the following program and choose the correct option that describes
its output:
import java.util.concurrent.atomic.AtomicInteger;
class Increment {
public static void main(String []args) {
AtomicInteger i = new AtomicInteger(0); //// Giá trị ban đầu = 0
increment(i); // Truyền tham chiếu đến đối tượng AtomicInteger
System.out.println(i);
}
static void increment(AtomicInteger atomicInt){
atomicInt.incrementAndGet(); // Tăng giá trị lên 1 (0 → 1)
}
}

a) 0
b) 1
c) This program throws an UnsafeIncrementException
d) This program throws a NonThreadContextException

Cau 17: Which one of the following interfaces is empty (i.e., an interface that does not
declare any methods)?
a) java.lang.AutoCloseable interface
b) java.util.concurrent.Callable<T> interface
c) java.lang.Cloneable interface ///Cloneable là interface rỗng
d) java.lang.Comparator<T> interface
Cau 18: Choose the correct option based on this code segment:
Stream<Integer> ints = Stream.of(1, 2, 3, 4);
boolean result = ints.parallel().map(Function.identity()).isParallel();
System.out.println(result);

a) This code segment results in compiler error(s)


b) This code segment throws InvalidParallelizationException for
the call parallel()
c) This code segment prints: false
d) This code segment prints: true

Vì .parallel() được gọi và không có gì làm thay đổi lại thành tuần tự (sequential()),
nên stream vẫn giữ trạng thái song song.

Cau 19: Given this code segment:


Set<String> set = new CopyOnWriteArraySet<String>(); // #1
set.add("2");
set.add("1"); //[“2”, “1”]
Iterator<String> iter = set.iterator(); // Snapshot: ["2", "1"] -> không chèn thêm zô nữa
set.add("3");
set.add("-1");
while(iter.hasNext()) {
System.out.print(iter.next() + " ");
}
Choose the correct option based on this code segment.
a) This code segment prints the following: 2 1
b) This code segment the following: 1 2
c) This code segment prints the following: -1 1 2 3
d) This code segment prints the following: 2 1 3 -1
e) This code segment throws a ConcurrentModificationException
f) This code segment results in a compiler error in statement #1

Cau 20: Choose the correct option based on this code segment:
String []exams = { "OCAJP 8", "OCPJP 8", "Upgrade to OCPJP 8" };
Predicate isOCPExam = exam -> exam.contains("OCP"); // LINE-1
List<String> ocpExams = Arrays.stream(exams)
.filter(exam -> exam.contains("OCP")) // lọc phần tử chứa OCP
.collect(Collectors.toList()); // LINE-2
boolean result = ocpExams.stream().anyMatch(exam -> exam.contains("OCA")); // LINE-3

System.out.println(result);

a) This code results in a compiler error in line marked with the comment LINE-1 //Predicate <T> mới
đúng
b) This code results in a compiler error in line marked with the comment LINE-2
c) This code results in a compiler error in line marked with the comment LINE-3
d) This program prints: true
e) This program prints: false

Cau 21: Choose the correct option based on this code segment:
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
ints.replaceAll(i -> i * i); // LINE // không cho phép thêm/xoá phần tử, nhưng cho phép thay
đổi giá trị phần tử hiện có
System.out.println(ints);

a) This code segment prints: [1, 2, 3, 4, 5]


b) This program prints: [1, 4, 9, 16, 25]
c) This code segment throws java.lang.UnsupportedOperationException
d) This code segment results in a compiler error in the line marked with the
comment LINE

Cau 22:Given the class definition:


class Student{
public Student(int r) {
rollNo = r;
}
int rollNo;
}
Choose the correct option based on this code segment:
HashSet<Student> students = new HashSet<>();
students.add(new Student(5));
students.add(new Student(10));
System.out.println(students.contains(new Student(10)));

a) This program prints the following: true


b) This program prints the following: false
c) This program results in compiler error(s)
d) This program throws NoSuchElementException

Cau 23: Given this code segment:


List<Map<List<Integer>, List<String>>> list = new ArrayList<>(); // ADD_MAP
Map<List<Integer>, List<String>> map = new HashMap<>();
list.add(null); // ADD_NULL
list.add(map);
list.add(new HashMap<List<Integer>, List<String>>()); // ADD_HASHMAP
list.forEach(e -> System.out.print(e + " ")); // ITERATE

Which one of the following options is correct?


a) This program will result in a compiler error in line marked with comment
ADD_MAP
b) This program will result in a compiler error in line marked with comment
ADD_HASHMAP
c) This program will result in a compiler error in line marked with comment
ITERATE
d) When run, this program will crash, throwing a NullPointerException in line
marked with comment ADD_NULL
e) When run, this program will print the following: null {} {}

Cau 24: Choose the correct option based on this program:


import java.util.stream.Stream;
public class Reduce {
public static void main(String []args) {
Stream<String> words = Stream.of("one", "two", "three");
int len = words.mapToInt(String::length).reduce(0, (len1, len2) ->
len1 + len2);
System.out.println(len);
}
}
a) This program does not compile and results in compiler error(s)
b) This program prints: onetwothree
c) This program prints: 11 ( 0+ 3 + 3+ 5 = 11)
d) This program throws an IllegalArgumentException

Cau 25: Which one of the following interfaces declares a single abstract method
named iterator()? (Note: Implementing this interface allows an object to be
the target of the for-each statement.)
a) Iterable<T>
b) Iterator<T>
c) Enumeration<E>
d) ForEach<T>

Cau 26: In a class that extends ListResourceBundle, which one of the following
method definitions correctly overrides the getContents() method of the
base class?
a) public String[][] getContents() {
return new Object[][] { { "1", "Uno" }, { "2", "Duo" }, { "3", "Trie" }};
}
b) public Object[][] getContents() {
return new Object[][] { { "1", "Uno" }, { "2", "Duo" }, { "3", "Trie" }};
}
c) private List<String> getContents() {
return new ArrayList (Arrays.AsList({ { "1", "Uno" }, { "2", "Duo" },
{ "3", "Trie" }});
}
d) protected Object[] getContents(){
return new String[] { "Uno", "Duo", "Trie" }; }

Cau 27: Choose the correct option based on the following code segment:
Comparator<String> comparer =
(country1, country2) ->
country2.compareTo(country2); // COMPARE_TO

String[] brics = {"Brazil", "Russia", "India", "China"};


Arrays.sort(brics, null);
Arrays.stream(brics).forEach(country -> System.out.print(country + " "));

a) The program results in a compiler error in the line marked with the comment
COMPARE_TO
b) The program prints the following: Brazil Russia India China
c) The program prints the following: Brazil China India Russia
d) The program prints the following: Russia India China Brazil
e) The program throws the exception InvalidComparatorException

Cau 28: Consider the following program:


class ClassA {}

interface InterfaceB {}

class ClassC {}
class Test extends ClassA implements InterfaceB {
String msg;
ClassC classC;
}
Which one of the following statements is true?
a) Class Test is related(liên quan) with ClassA with a HAS-A relationship.
b) Class Test is related to ClassC with a composition relationship.
c) Class Test is related with String with an IS-A relationship.
d) Class ClassA is related with InterfaceB with an IS-A relationship.

Cau 29: In the context of Singleton pattern, which one of the following statements
is true?
a) A Singleton class must not have any static members
b) A Singleton class has a public constructor
c) A Factory class may use Singleton pattern
d) All methods of the Singleton class must be private

Cau 30: Consider the following program:


class WildCard {
interface BI {}
interface DI extends BI {}
interface DDI extends DI {}

static class C<T> {}


static void foo(C<? super DI> arg) {}

public static void main(String []args) {


foo(new C<BI>()); // ONE
foo(new C<DI>()); // TWO
foo(new C<DDI>()); // THREE
foo(new C()); // FOUR
}
}
Which of the following options are correct?
a) Line marked with comment ONE will result in a compiler error
b) Line marked with comment TWO will result in a compiler error
c) Line marked with comment THREE will result in a compiler error
d) Line marked with comment FOUR will result in a compiler error

Cau 31: Choose the correct option based on this program:


class base1 {
protected int var;
}
interface base2 {
int var = 0; // #1
}
class Test extends base1 implements base2 { // #2
public static void main(String args[]) {
System.out.println("var:" + var); // #3
}
}

a) The program will report a compilation error at statement marked with the
comment #1
b) The program will report a compilation error at statement marked with the
comment #2
c) The program will report a compilation error at statement marked with the
comment #3
d) The program will compile without any errors

Cau 32: Which of the following statements are true with respect to enums? (Select all that apply.)
a) An enum can have private constructor
b) An enum can have public constructor
c) An enum can have public methods and fields
d) An enum can implement an interface
e) An enum can extend a class

Enum luôn luôn private

Cau 33: Consider the following program:


public class Outer {
private int mem = 10;
class Inner {
private int imem = new Outer().mem; // ACCESS1
}

public static void main(String []s) {


System.out.println(new Outer().new Inner().imem); // ACCESS2
}
}
Which one of the following options is correct?
a) When compiled, this program will result in a compiler error in line marked with
comment ACCESS1
b) When compiled, this program will result in a compiler error in line marked with
comment ACCESS2
c) When executed, this program prints 10
d) When executed, this program prints 0

Cau 34: Consider the following program:


class Outer {
class Inner {
public void print() {
System.out.println("Inner: print");
}
}
}
class Test {
public static void main(String []args) {
// Stmt#1
inner.print();
}
}
Which one of the following statements will you replace with // Stmt#1 to
make the program compile and run successfully to print “Inner: print” in
console?

a) Outer.Inner inner = new Outer.Inner();


b) Inner inner = new Outer.Inner();
c) Outer.Inner inner = new Outer().Inner();
d) Outer.Inner inner = new Outer().new Inner();
Cau 35: Consider the following program and choose the right option from the
given list:
class Base {
public void test() {
protected int a = 10; // #1
}
}

class Test extends Base { // #2


public static void main(String[] args) {
System.out.printf(null); // #3
}
}
a) The compiler will report an error at statement marked with the comment #1
b) The compiler will report an error at statement marked with the comment #2
c) The compiler will report errors at statement marked with the comment #3
d) The program will compile without any error

Cau 36:Given this code segment:


final CyclicBarrier barrier =
new CyclicBarrier(3, () -> System.out.println("Let's play"));
// LINE_ONE
Runnable r = () -> { // LINE_TWO
System.out.println("Awaiting");
try {
barrier.await();
} catch(Exception e) { /* ignore */ }
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Thread t3 = new Thread(r);
t1.start();
t2.start();
t3.start();

Choose the correct option based on this code segment.


a) This code segment results in a compiler error in line marked with the
comment LINE_ONE
b) This code segment results in a compiler error in line marked with the
comment LINE_TWO
c) This code prints:
Let's play

d) This code prints:


Awaiting
Awaiting
Awaiting
Let's play

e) This code segment does not print anything on the console


Cau 37: What will be the result of executing this code segment?
Stream.of("ace ", "jack ", "queen ", "king ", "joker ")
.mapToInt(card -> card.length())
.filter(len -> len > 3)
.peek(System.out::print)
.limit(2);
a) This code segment prints: jack queen king joker
b) This code segment prints: jack queen
c) This code segment prints: king joker
d) This code segment does not print anything on the console

Cau 38: Given


3. public class Chess implements Runnable {
4. public void run() {
5. move(Thread.currentThread().getId());
6. }
7. // insert code here
8. System.out.print(id + " ");
9. System.out.print(id + " ");
10. }
11. public static void main(String[] args) {
12. Chess ch = new Chess();
13. new Thread(ch).start();
14. new Thread(new Chess()).start();
15. }
16. }

And given these two fragments:


I. synchronized void move(long id) {
II. void move(long id) {
When either fragment I or fragment II is inserted at line 7, which are true? (Choose all that apply.)
A. Compilation fails
B. With fragment I, an exception is thrown
C. With fragment I, the output could be 4 2 4 2
D. With fragment I, the output could be 4 4 2 3
E. With fragment II, the output could be 2 4 2 4
C and E are correct. E should be obvious. C is correct because even though move() is
synchronized, it's being invoked on two different objects.
A, B, and D are incorrect based on the above. (Objective 4.3)

Cau 39: Given:


3. class Chicks {
4. synchronized void yack(long id) {
5. for(int x = 1; x < 3; x++) {
6. System.out.print(id + " ");
7. Thread.yield();
8. }
9. }
10. }
11. public class ChicksYack implements Runnable {
12. Chicks c;
13. public static void main(String[] args) {
14. new ChicksYack().go();
15. }
16. void go() {
17. c = new Chicks();
18. new Thread(new ChicksYack()).start();
19. new Thread(new ChicksYack()).start();
20. }
21. public void run() {
22. c.yack(Thread.currentThread().getId());
23. }
24. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output could be 4 4 2 3
C. The output could be 4 4 2 2
D. The output could be 4 4 4 2
E. The output could be 2 2 4 4
F. An exception is thrown at runtime

Cau 40 : Given:
3. class Dudes {
4. static long flag = 0;
5. // insert code here
6. if(flag == 0) flag = id;
7. for(int x = 1; x < 3; x++) {
8. if(flag == id) System.out.print("yo ");
9. else System.out.print("dude ");
10. }
11. }
12. }
13. public class DudesChat implements Runnable {
14. static Dudes d;
15. public static void main(String[] args) {
16. new DudesChat().go();
17. }
18. void go() {
19. d = new Dudes();

20. new Thread(new DudesChat()).start();


21. new Thread(new DudesChat()).start();
22. }
23. public void run() {
24. d.chat(Thread.currentThread().getId());
25. }
26. }
And given these two fragments:
I. synchronized void chat(long id) {
II. void chat(long id) {
When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be yo dude dude yo
E. With fragment I, the output could be dude dude yo yo
F. With fragment II, the output could be yo dude dude yo
Cau 41: Given:
3. public class Leader implements Runnable {
4. public static void main(String[] args) {
5. Thread t = new Thread(new Leader());
6. t.start();
7. System.out.print("m1 ");
8. t.join(); // phải có try-catch
9. System.out.print("m2 ");
10 .}

11. public void run() {


12. System.out.print("r1 ");
13. System.out.print("r2 ");
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output could be r1 r2 m1 m2
C. The output could be m1 m2 r1 r2
D. The output could be m1 r1 r2 m2
E. The output could be m1 r1 m2 r2
F. An exception is thrown at runtime

Cau 42: Given:


3. public class Starter implements Runnable {
4. void go(long id) {
5. System.out.println(id);
6. }
7. public static void main(String[] args) {
8. System.out.print(Thread.currentThread().getId() + " ");
9. // insert code here
10. }
11. public void run() { go(Thread.currentThread().getId()); }
12. }
And given the following five fragments:
I. new Starter().run();
II. new Starter().start();
III. new Thread(new Starter());
IV. new Thread(new Starter()).run();
V. new Thread(new Starter()).start();
When the five fragments are inserted, one at a time at line 9,
which are true? (Choose all that apply.)
A. All five will compile
B. Only one might produce the output 4 4
C. Only one might produce the output 4 2
D. Exactly two might produce the output 4 4
E. Exactly two might produce the output 4 2
F. Exactly three might produce the output 4 4
G. Exactly three might produce the output 4 2
Cau 43: Given:
public class TwoThreads {
static Thread laurel, hardy;
public static void main(String[] args) {
laurel = new Thread() {
public void run() {
System.out.println("A");
try {
hardy.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
hardy = new Thread() {
public void run() {
System.out.println("D");
try {
laurel.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");

}
};
laurel.start();
hardy.start();
}
}
Which letters will eventually appear somewhere in the output? (Choose all that apply.)
A. A
B. B
C. C
D. D
E. E
F. F
G. The answer cannot be reliably determined
H. The code does not compile

Cau 44: Given:


class MyThread extends Thread {
MyThread() {
System.out.print(" MyThread");
}
public void run() { System.out.print(" bar"); }
public void run(String s) { System.out.print(" baz"); }
}
public class TestThreads {
public static void main (String [] args) {
Thread t = new MyThread() {
public void run() { System.out.print(" foo"); }
};
t.start();
}}
What is the result?
A. foo
B. MyThread foo
C. MyThread bar
D. foo bar
E. foo bar baz
F. bar foo
G. Compilation fails
H. An exception is thrown at runtime

Cau 45: Given:


public static synchronized void main(String[] args) throws InterruptedException {

Thread t = new Thread();


t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}
What is the result of this code?
A. It prints X and exits
B. It prints X and never exits
C. It prints XY and exits almost immeditately
D. It prints XY with a 10-second delay between X and Y
E. It prints XY with a 10000-second delay between X and Y
F. The code does not compile
G. An exception is thrown at runtime

Sai dòng này: t.wait(10000); phải có synchronized (t) {


t.wait(1000); // Chờ 1 giây
}

Cau 46: Given the scenario: This class is intended to allow users to write a series of messages, so
that each message is identified with a timestamp and the name of the thread that wrote the
message:
public class Logger {
private StringBuilder contents = new StringBuilder();
public void log(String message) {
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());

contents.append(message);
contents.append("\n");
}
public String getContents() { return contents.toString(); }
}
How can we ensure that instances of this class can be safely used by multiple threads?
A. This class is already thread-safe
B. Replacing StringBuilder with StringBuffer will make this class thread-safe
C. Synchronize the log() method only
D. Synchronize the getContents() method only
E. Synchronize both log() and getContents()
F. This class cannot be made thread-safe

Cau 47: Given:


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

5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. } }
What is the result of trying to compile and run this program?
A. It fails to compile because the IllegalMonitorStateException of wait() is not dealt
with in line 7
B. 1 2 3
C. 1 3
D. 1 2
E. At runtime, it throws an IllegalMonitorStateException when trying to wait
F. It will fail to compile because it has to be synchronized on the this object

Cau 48:Given:
3. class MyThread extends Thread {
4. public static void main(String [] args) {
5. MyThread t = new MyThread();
6. Thread x = new Thread(t);
7. x.start();
8. }
9. public void run() {
10. for(int i=0;i<3;++i) {
11. System.out.print(i + "..");
12. }}}
What is the result of this code?
A. Compilation fails
B. 1..2..3..
C. 0..1..2..3..
D. 0..1..2..
E. An exception occurs at runtime

Cau 49 : The following block of code creates a Thread using a Runnable target:
Runnable target = new MyRunnable();
Thread myThread = new Thread(target);
Which of the following classes can be used to create the target, so that the preceding code
compiles correctly?
A. public class MyRunnable extends Runnable{public void run(){}}
B. public class MyRunnable extends Object{public void run(){}}
C. public class MyRunnable implements Runnable{public void run(){}}
D. public class MyRunnable implements Runnable{void run(){}}
E. public class MyRunnable implements Runnable{public void start(){}}

CAU 50: Given:


3. import java.util.*;
4. public class GeoCache {
5. public static void main(String[] args) {
6. String[] s = {"map", "pen", "marble", "key"};
7. Othello o = new Othello();
8. Arrays.sort(s,o);
9. for(String s2: s) System.out.print(s2 + " ");
10. System.out.println(Arrays.binarySearch(s, "map"));
11. }
12. static class Othello implements Comparator<String> {
13. public int compare(String a, String b) { return b.compareTo(a); }// so sánh giảm dần
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output will contain a 1
C. The output will contain a 2
D. The output will contain a –1
E. An exception is thrown at runtime
F. The output will contain "key map marble pen"
G. The output will contain "pen marble map key"

Explain: b.compare(a) sắp xếp giảm dần [“pen”, “map”, “marble”, “key”]
For(String s2:s) in ra: pen map marble key
Dòng: Arrays.binarySearch(s ,”map”) mặc định là tăng dần
nhưng ở đây là đang ưu tiên sắp xếp giảm dần trước -> nên kết quả tìm kiếm không chính xác -> trả
về giá trị âm (-1,-2,…)
không có lỗi runtime hay exception xảy ra

Kiến thức a.compareTo(b)


< 0 nếu ( a<b ) theo thứ tự từ điển
= 0 nếu a.equals(b)
> 0 nếu ( a > b )

Ví dụ: public int compare(String a, String b) { a.compareTo(b) - > so sánh tăng dần

return b.compareTo(a); // Chú ý: đảo thứ tự! b.compareTo(a) - > so sánh giảm dần

a=”map” ; b=”pen”

a. compareTo(b) “m” < ”p” ->-3


b. compareTo(a) “m” < “P” ->3

Cau 51: Given:


3. import java.util.*;
4. class Dog { int size; Dog(int s) { size = s; } }
5. public class FirstGrade {
6. public static void main(String[] args) {
7. TreeSet<Integer> i = new TreeSet<Integer>();
8. TreeSet<Dog> d = new TreeSet<Dog>();
9.
10. d.add(new Dog(1)); d.add(new Dog(2)); d.add(new Dog(1));
11. i.add(1); i.add(2); i.add(1);
12. System.out.println(d.size() + " " + i.size());
13. }
14. }
What is the result?
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime

TreeSet không cho trùng lặp và sắp xếp theo thứ tự.

nếu: TreeSet<String> set = new TreeSet<>(Collections.reverseOrder()); -> sẽ đảo ngược kết quả
** reverse là đảo ngược

Cau 52:Given:
3. import java.util.*;
4. class Business { }
5. class Hotel extends Business { }
6. class Inn extends Hotel { }
7. public class Travel {
8. ArrayList<Hotel> go() {
9. // insert code here
10. }
11. }
Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList<Inn>();
B. return new ArrayList<Hotel>();
C. return new ArrayList<Object>();
D. return new ArrayList<Business>();

Cau 53: Given:


3. import java.util.*;
4. public class Magellan {
5. public static void main(String[] args) {
6. TreeMap<String, String> myMap = new TreeMap<String, String>();
7. myMap.put("a", "apple"); myMap.put("d", "date");
8. myMap.put("f", "fig"); myMap.put("p", "pear");
9. System.out.println("1st after mango: " + // sop 1
10. myMap.higherKey("f"));
11. System.out.println("1st after mango: " + // sop 2
12. myMap.ceilingKey("f"));
13. System.out.println("1st after mango: " + // sop 3
14. myMap.floorKey("f"));
15. SortedMap<String, String> sub = new TreeMap<String, String>();
16. sub = myMap.tailMap("f");
17. System.out.println("1st after mango: " + // sop 4
18. sub.firstKey());
19. }
20. }
Which of the System.out.println statements will produce the output 1st after mango: p?
(Choose all that apply.)
A. sop 1
B. sop 2
C. sop 3
D. sop 4
E. None; compilation fails
F. None; an exception is thrown at runtime

Phương thức Ý nghĩa


higherKey(k) Trả về key lớn hơn k
ceilingKey(k) Trả về key ≥ k
floorKey(k) Trả về key ≤ k
tailMap(k) Trả về map con từ k trở đi
firstKey() Trả về key đầu tiên trong map con

Cau 54: Given the proper import statement(s), and:


13. TreeSet<String> s = new TreeSet<String>();
14. TreeSet<String> subs = new TreeSet<String>();
15. s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");
16.
17. subs = (TreeSet)s.subSet("b", true, "d", true);
18. s.add("g");
19. s.pollFirst();
20. s.pollFirst();
21. s.add("c2");
22. System.out.println(s.size() +" "+ subs.size());
Which are true? (Choose all that apply.)
A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime
Cau 54: Given:
3. import java.util.*;
4. class Turtle {
5. int size;
6. public Turtle(int s) { size = s; }
7. public boolean equals(Object o) { return (this.size == ((Turtle)o).size); }
8. // insert code here
9. }
10. public class TurtleTest {
11. public static void main(String[] args) {
12. LinkedHashSet<Turtle> t = new LinkedHashSet<Turtle>();
13. t.add(new Turtle(1)); t.add(new Turtle(2)); t.add(new Turtle(1));
14. System.out.println(t.size());
15. }
16. }

And these two fragments:


I. public int hashCode() { return size/5; }
II. // no hashCode method declared
If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)
A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails

Cau 55: Given:


3. import java.util.*;
4. public class Mixup {
5. public static void main(String[] args) {
6. Object o = new Object();
7. // insert code here
8. s.add("o");
9. s.add(o);
10. }
11. }

And these three fragments:


I. Set s = new HashSet();
II. TreeSet s = new TreeSet();
III. LinkedHashSet s = new LinkedHashSet();
When fragments I, II, or III are inserted, independently, at line 7, which are true?
(Choose all that apply.)
A. Fragment I compiles
B. Fragment II compiles
C. Fragment III compiles
D. Fragment I executes without exception
E. Fragment II executes without exception
F. Fragment III executes without exception

Cau 56: Which collection class(es) allows you to grow or shrink its size and provides indexed access
to its elements, but whose methods are not synchronized? (Choose all that apply.)
A. java.util.HashSet
B. java.util.LinkedHashSet
C. java.util.List
D. java.util.ArrayList
E. java.util.Vector
F. java.util.PriorityQueue

Cau 57: Given:


import java.util.*;
class MapEQ {
public static void main(String[] args) {
Map<ToDos, String> m = new HashMap<ToDos, String>();
ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");
ToDos t3 = new ToDos("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(m.size());
}}
class ToDos{
String day;
ToDos(String d) { day = d; }
public boolean equals(Object o) {
return ((ToDos)o).day == this.day;
}
// public int hashCode() { return 9; }
}
Which is correct? (Choose all that apply.)
A. As the code stands it will not compile
B. As the code stands the output will be 2
C. As the code stands the output will be 3
D. If the hashCode() method is uncommented the output will be 2
E. If the hashCode() method is uncommented the output will be 3
F. If the hashCode() method is uncommented the code will not compile

Cau 58: Given:


public static void before() {
Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}
Which statements are true?
A. The before() method will print 1 2
B. The before() method will print 1 2 3
C. The before() method will print three numbers, but the order cannot be determined
D. The before() method will not compile
E. The before() method will throw an exception at runtime

Cau 59: Which statements are true about comparing two instances of the same class, given that the
equals() and hashCode() methods have been properly overridden? (Choose all that apply.)
A. If the equals() method returns true, the hashCode() comparison == might return false
B. If the equals() method returns false, the hashCode() comparison == might return true
C. If the hashCode() comparison == returns true, the equals() method must return true
D. If the hashCode() comparison == returns true, the equals() method might return true
E. If the hashCode() comparison != returns true, the equals() method might return true

Cau 60: Given:


public static void main(String[] args) {
// INSERT DECLARATION HERE
for (int i = 0; i <= 10; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= 10; j++)
row.add(i * j);
table.add(row);
}
for (List<Integer> row : table)
System.out.println(row);
}
Which statements could be inserted at // INSERT DECLARATION HERE to allow this code to
compile and run? (Choose all that apply.)
A. List<List<Integer>> table = new List<List<Integer>>();
B. List<List<Integer>> table = new ArrayList<List<Integer>>();
C. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();
D. List<List, Integer> table = new List<List, Integer>();
E. List<List, Integer> table = new ArrayList<List, Integer>();
F. List<List, Integer> table = new ArrayList<ArrayList, Integer>();
G. None of the above

Cau 61: Given:


class Emu {
static String s = "-";
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
try { throw new Exception();
} catch (Exception ex) { s += "ic "; }
throw new Exception(); }
catch (Exception x) { s += "mc "; }
finally { s += "mf "; }
} finally { s += "of "; }
System.out.println(s);
}
}
What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails
Cau 62: Given:
3. public class Ebb {
4. static int x = 7;
5. public static void main(String[] args) {
6. String s = "";
7. for(int y = 0; y < 3; y++) {
8. x++;
9. switch(x) {
10. case 8: s += "8 ";
11. case 9: s += "9 ";
12. case 10: { s+= "10 "; break; }
13. default: s += "d ";
14. case 13: s+= "13 ";
15. }
16. }
17. System.out.println(s);
18. }
19. static { x++; } //// dòng 19 – chạy trước main
20. }
What is the result?
A. 9 10 d
B. 8 9 10 d
C. 9 10 10 d
D. 9 10 10 d 13
E. 8 9 10 10 d 13
F. 8 9 10 9 10 10 d 13
G. Compilation fails

**D is correct. Did you catch the static initializer block? Remember that switches work on
"fall-thru" logic, and that fall-thru logic also applies to the default case, which is used when
no other case matches.

Cau 63: Given:


3. class Infinity { }
4. public class Beyond extends Infinity {
5. static Integer i;
6. public static void main(String[] args) {
7. int sw = (int)(Math.random() * 3);
8. switch(sw) {
9. case 0: { for(int x = 10; x > 5; x++)

10. if(x > 10000000) x = 10;


11. break; }
12. case 1: { int y = 7 * i; break; }
13. case 2: { Infinity inf = new Beyond();
14. Beyond b = (Beyond)inf; }
15. }
16. }
17. }
And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception

Đáp án Phân tích Kết luận


A. Compilation fails Mã hợp lệ, không lỗi biên dịch ❌
B. ClassCastException Không xảy ra vì ép kiểu đúng ❌
C. StackOverflowError Không có đệ quy → không xảy ra ❌
D. NullPointerException ✅ Nếu vào case 1
E. IllegalStateException Không thấy ❌
F. Program hangs ✅ Nếu vào case 0
G. Always completes Có thể lỗi hoặc treo ❌
Cau 64:Given:
public class Circles {
public static void main(String[] args) {
int[] ia = {1, 3, 5, 7, 9};
for (int x : ia) {
for (int j = 0; j < 3; j++) {
if (x > 4 && x < 8) continue;
System.out.print(" " + x);
if (j == 1) break;
continue;
}
continue;
}
}
}

What is the result?


A. 1 3 9
B. 5 5 7 7
C. 1 3 3 9 9
D. 1 1 3 3 9 9
E. 1 1 1 3 3 3 9 9 9
F. Compilation fails

Cau 65: Given:


3. public class OverAndOver {
4. static String s = "";
5. public static void main(String[] args) {
6. try {
7. s += "1";
8. throw new Exception();
9. } catch (Exception e) {
10. s += "2";
11. } finally {
12. s += "3";
13. doStuff();
14. s += "4";
15. }
16. System.out.println(s);
17. }

18. static void doStuff() {


19. int x = 0;
20. int y = 7 / x; // ArithmeticException xảy ra ở đây
21. }
22. }

What is the result?


A. 12
B. 13
C. 123
D. 1234
E. Compilation fails
F. 123 followed by an exception

G. 1234 followed by an exception


H. An exception is thrown with no other output

CAU 66: Given:


3. public class Wind {
4. public static void main(String[] args) {
5. foreach:
6. for(int j=0; j<5; j++) {
7. for(int k=0; k< 3; k++) {
8. System.out.print(" " + j);
9. if(j==3 && k==1) break foreach;
10. if(j==0 || j==2) break;
11. }
12. }
13. }
14. }
What is the result?
A. 0 1 2 3
B. 1 1 1 3 3
C. 0 1 1 1 2 3 3
D. 1 1 1 3 3 4 4 4
E. 0 1 1 1 2 3 3 4 4 4
F. Compilation fails

Cau 67 :Given:
3. public class Clumsy {
4. public static void main(String[] args) {
5. int j = 7;
6. assert(++j > 7);
7. assert(++j > 8): "hi";
8. assert(j > 10): j=12;
9. assert(j==12): doStuff();
10. assert(j==12): new Clumsy();
11. }
12. static void doStuff() { }
13. }
Which are true? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 6
C. Compilation fails due to an error on line 7
D. Compilation fails due to an error on line 8
E. Compilation fails due to an error on line 9
F. Compilation fails due to an error on line 10
Cau 68: Given:
class Top {
public Top(String s) { System.out.print("B"); }
}
public class Bottom2 extends Top {
public Bottom2(String s) { System.out.print("D"); }
public static void main(String [] args) {
new Bottom2("C");
System.out.println(" ");
}}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails

Explain: khi lớp con(Bottom2) kế thừa lớp cha(Top) thì Constructor của lớp con phải gọi constructor
của lớp Cha thông qua super() -- nếu không gọi thì java mặc định hiểu là gọi ngầm super().
Nhưng lớp cha(Top) đã gọi constructor qua: public Top(String s) . Vì không có Constructor mặc định
nên gọi ngầm của Bottom2 -> gây lỗi biên dịch

Cau 69:Given:
class Clidder {
private final void flipper() { System.out.println("Clidder"); }
}
public class Clidlet extends Clidder {
public final void flipper() { System.out.println("Clidlet"); }
public static void main(String [] args) {
new Clidlet().flipper();
}}
What is the result?
A. Clidlet
B. Clidder
C. Clidder
Clidlet
D. Clidlet
Clidder
E. Compilation fails

Expain: vì lớp cha(Clidder) có phương thức khai báo “private” -> không kết thừa lớp con(Clidlet)
public final void flipper() ->đầy là phương thức mới không override(ghi đè) phương thức của lớp cha
và là “private”

Cau 70: Which statement(s) are true? (Choose all that apply.)
A. Cohesion is the OO principle most closely associated with hiding implementation details
B. Cohesion is the OO principle most closely associated with making sure that classes know
about other classes only through their APIs
C. Cohesion is the OO principle most closely associated with making sure that a class is
designed with a single, well-focused purpose (cho phép một class chỉ cho 1 mục đích duy nhất và
tập trung tốt)
D. Cohesion is the OO principle most closely associated with allowing a single object to be
seen as having many types

Cau 71: Given:


3. class Dog {
4. public void bark() { System.out.print("woof "); }
5. }
6. class Hound extends Dog {
7. public void sniff() { System.out.print("sniff "); }
8. public void bark() { System.out.print("howl "); }
9. }
10. public class DogShow {
11. static void main(String[] args) { new DogShow().go(); }
12. void go() {
13. new Hound().bark();
14. ((Dog) new Hound()).bark();
15. ((Dog) new Hound()).sniff();
16. }
17. }
What is the result? (Choose all that apply.)
A. howl howl sniff
B. howl woof sniff
C. howl howl followed by an exception
D. howl woof followed by an exception
E. Compilation fails with an error at line 14
F. Compilation fails with an error at line 15

Expain: Class Dog doesn’t have a sniff method.(khôngcó phương thức sniff)
ép kiểu về class Dog nhưng khong có phương thức sniff -> compline time

****BONUS: ClassCastException: lỗi ép kiểu

Cau 72: Given:


3. public class Tenor extends Singer {
4. public static String sing() { return "fa"; }
5. public static void main(String[] args) {
6. Tenor t = new Tenor();
7. Singer s = new Tenor();
8. System.out.println(t.sing() + " " + s.sing());
9. }
10. }
11. class Singer {
public static String sing() {
return "la"; }
}
What is the result?
A. fa fa
B. fa la
C. la la
D. Compilation fails
E. An exception is thrown at runtime

You might also like