CDJAVA
CDJAVA
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]
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);
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
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
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 10: Select all the statements that are true about streams (supported in
java.util.stream.Stream interface)?
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
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
}
}
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);
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 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);
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
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
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
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
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();
}
};
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 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
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(){}}
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
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”
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 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 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
**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 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
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