0% found this document useful (0 votes)
2K views195 pages

TÀI LIỆU ÔN THI FE - PRO192

a

Uploaded by

hoangndhde180637
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)
2K views195 pages

TÀI LIỆU ÔN THI FE - PRO192

a

Uploaded by

hoangndhde180637
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/ 195

THAM KHẢO

Tham khảo PRO192 - 1:


https://docs.google.com/document/d/1pMmQYcZaSyZq60lDjba7C3MW0AwKKiLl0WPtW0V6
H2c/edit?usp=sharing
Tham khảo PRO192 - 2 – chỉ có đáp án, ko có giải thích:
https://docs.google.com/document/d/
1sYu2SVEEXDwTrdVRbD6kLBpmwKaJvcXdYszTazuvXKc/edit?usp=sharing
Thẻ ghi nhớ: PRO192 SOURCE TWINCODE_207 câu đầu | Quizlet
Thẻ ghi nhớ: PRO192 | Quizlet

KIẾN THỨC

byte < short < int < long.

Kế thừa
Cha = new Con
Con = new Con

Con = (Cha)xx
Cú pháp của Tính kế thừa trong Java

// class có thể extends 1 class & implements nhiều interface


class ten_lop_con extends ten_lop_cha
{
//cac phuong thuc va cac truong
}

// interface có thể implements nhiều interface


public interface A {}

public class B implements A{

public class C extends B{

Tính kế thừa trong Java - Từ khóa extends và implements trong Java | 155 bài học Java
miễn phí hay nhất (vietjack.com)

Abstract Class & Inteface

● Interface methods are by default abstract and public


● Interface attributes are by default public, static and final

List .size
List ms có compare
Wrapper thuộc java.lang.Number
Boxing và unboxing là cách chuyển đổi giữa kiểu dữ liệu nguyên thủy
(primitive) và kiểu dữ liệu đối tượng (object) trong Java.
Boxing là quá trình chuyển đổi giá trị của một kiểu dữ liệu nguyên thủy
thành một đối tượng tương ứng của kiểu dữ liệu đối tượng tương ứng. Ví
dụ, để boxing một giá trị int thành một đối tượng Integer, chúng ta có
thể sử dụng cú pháp sau:

java.lang.Comparable

Các interface trong java.lang bao gồm:


1. Comparable: Như đã đề cập ở trên, interface này được sử dụng để
so sánh các đối tượng của một lớp với nhau.
2. CharSequence: Interface này định nghĩa một chuỗi ký tự có thể đọc
và là một lớp cha cho các lớp String, StringBuilder,
StringBuffer, v.v.
3. Cloneable: Interface này được sử dụng để cho phép một đối tượng
được sao chép bằng phương thức clone(), mà không phải triệu hồi
constructor.
4. Iterable: Interface này định nghĩa một đối tượng có thể được lặp
qua, ví dụ như một danh sách hoặc một tập hợp.
5. Appendable: Interface này định nghĩa một đối tượng có thể được bổ
sung thêm các ký tự vào cuối của nó, ví dụ như một
StringBuilder hoặc StringBuffer.

Các interface trong java.util bao gồm:


1. List: Interface này định nghĩa một danh sách các phần tử, cho phép
truy cập theo chỉ số, chèn, xóa, v.v.
2. Set: Interface này định nghĩa một tập hợp các phần tử không có thứ
tự, không trùng lặp.
3. Map: Interface này định nghĩa một tập hợp các cặp key-value, cho
phép truy cập theo key, chèn, xóa, v.v.
4. Iterator: Interface này định nghĩa một đối tượng có thể lặp qua
một tập hợp các phần tử, cho phép truy cập tuần tự các phần tử và
xóa các phần tử.
5. Collection: Interface này định nghĩa một tập hợp các phần tử, cho
phép thêm, xóa, chèn, v.v.
Constructors are not members, so they are not inherited by subclasses, but the constructor
of the superclass can be invoked from the subclass.

The max() method of Java Collections class is used to get the maximum element of the given
collection, according to the natural ordering of its elements.

overriding là khác class overloading mới chung class

CÂU HỎI

Access modifier
AC - vì default là cùng package

Shape and Main are defined in the same package, examine the code and select the correct
statements. (select 2)
line1> class Shape {
line2> public void print() {
line3> System.out.println("Shape");
line4> }
line5> }
line6> class Main {
line7> public static void main(String... args) {
line8> Shape anShape = new Shape(); line9> anShape.print();
line10> }
line11> }
A. The class Main will print Shape
B. If the code on line 2 is changed as follows, the class Main will print Shape:
private void print() {
C. If the code on line 2 is changed as follows, the class Main will print Shape:
void print() {
D. If the code on line 2 is changed as follows, the class Main will print Shape:
default void print() {

===============

B
In situations where there are no implementations to inherit, an interface is often a better
choice than an abstract class. This is because a class can implement multiple interfaces but
can only inherit from a single abstract class. Additionally, interfaces allow for greater
flexibility in designing a system because they allow classes to be interchangeable as long as
they implement the same interface.

B không cùng kiểu dữ liệu thì kh sort đc


since the array contains objects of different types, the sorting operation will
fail with a ClassCastException.

A signed data type has an equal number of non-zero positive and negative values available
====> False. The range of negative numbers is greater by 1 than the range of positive numbers

Given the following code. What is the expected outcome?

public class Test{


public static void main(String[] a){
int[] b = [1,2,3,4,5,6,7,8,9,0];
System.out.println("a[2]=" + a[2]);
}
}
a. The code does not compile

b. "a[2] =2" is printed out to the console

c. The code compiles but does not output anything.

d. "a[2] = 3" is printed out to the console

phải là {
https://youtu.be/sMBZ1mMqRRM

https://www.careerride.com/view/placement-papers-on-java-set-2-13345.aspx

In Java, a class defined inside a method is called a local class. Local


classes are nested inside a method and can only be accessed within that
method.
When a local class is defined inside a method, it can access both local
variables and parameters of the enclosing method, as long as they are
declared as final or effectively final. An effectively final variable is a variable
that is not declared as final, but its value is not changed after it is
initialized.
Bởi vì trong quá trình chạy thì cái biến y kia có thể thay đổi giá trị sau khi phương thức
myMethod kết thúc, trong khi lớp nội bộ MyLocalClass có thể tiếp tục tồn tại và sử
dụng biến y sau đó. Do đó, để đảm bảo tính chính xác và dự đoán của lớp nội bộ
MyLocalClass, biến y phải được khai báo là final hoặc effectively final.
BE

B
C The variables declared in the initialization step must all have the same
data type

B
BC

File directory = new File("/path/to/directory");


directory.chdir();

File file = new File("/path/to/file.txt");


File parentDirectory = file.getParentFile();
String parentDirectoryName = parentDirectory.getName();
System.out.println(parentDirectoryName);

File file = new File("/path/to/file.txt");


file.delete();

analyze the byte values to look for patterns that are indicative of text or
binary data.
C

C
https://www.geeksforgeeks.org/datainputstream-readbyte-method-in-java-with-examples/
Acd

Rules to Declare a Variable

1. A variable name can consist of Capital letters A-Z, lowercase letters

a-z digits 0-9, and two special characters such as _ underscore and

$ dollar sign.

2. The first character must not be a digit.

3. Blank spaces cannot be used in variable names.

4. Java keywords cannot be used as variable names.

5. Variable names are case-sensitive.

6. There is no limit on the length of a variable name but by convention,

it should be between 4 to 15 chars.

7. Variable names always should exist on the left-hand side of

assignment operators.
Parrot

BC – cùng packages là đc, khác class kh sao


A
Which of the following statements is INCORRECT?
A. All of the variables in an interface are implicitly static
B. All of the variables in an interface are implicitly final
C. All of the methods in an interface are implicitly abstract
D. A method in an interface can access class level variables
D
(variable: public static final, method: abstract public)
A method in an interface cannot access class level variables because interfaces do not have
instance variables. They only define abstract methods and constants.

C - con này mâu thuẫn với con I am a student x2

Which of the File class description statements below is WRONG?

A File class helps accessing file/dictionary information only

B. File class doesn't have any method to access data in a file


C. File class has only one constructor with a file path parameter

D. File class is a class which could be found in java io package

https://www.geeksforgeeks.org/file-class-in-java/

The statement B is wrong. The File class in Java provides several methods

to access data in a file, such as reading data from a file, writing data to a

file, checking file permissions, etc. Therefore, the statement "File class

doesn't have any method to access data in a file" is incorrect.

Set and list


B

C ( input)
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-520.html
A (chứa object)
Stack chứa khuôn class
Heap là một vùng nhớ trong bộ nhớ được sử dụng để lưu trữ các
đối tượng khi từ khóa new được gọi ra, các biến static và các biến
toàn cục (biến instance).

BD
Trong java luôn là pass by value
Đã thử & A C

D
byte: The byte data type is an 8-bit signed two's complement
integer. It has a minimum value of -128 and a maximum value of
127 (inclusive).
A

B
A

A123
ép kiểu obj từ kiểu Object sang kiểu int[], ta sử dụng cú pháp (int[])obj. Việc
ép kiểu này chỉ được thực hiện khi kiểu thực tế của obj là một mảng kiểu
nguyên (int[]). Nếu obj không phải là một mảng kiểu nguyên, thì việc ép kiểu
này sẽ gây ra lỗi ClassCastException.
3. You have been given a design document for a veterinary registration system for
implementation in Java. It states:

"A pet has an owner, a registration date, and a vaccination-due date. A cat is a pet
that has a flag indicating whether it has been neutered, and a textual description of
its markings."

Given that the Pet class has already been defined, which of the following fields
would be appropriate for inclusion in the Cat class as members? (Choose all that
apply.)
A. Pet thePet;
B. Date registered;
C. Date vaccinationDue;
D. Cat theCat;
E. boolean neutered;
F. String markings;
EF

C
A

E - vì nó bị mất cái constructor không tham số

B
B

C
A

AC
C
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-76.html

d
Hợp lí khi nào? A C ( b=m, d=m) —> large = small

B
ClassCastException vì w là kiểu thing, w là 1 cái interface → cat, 2 cái kh
liên quan gì
B

D - completely & method

A
–A compound statement (also known as a block) is a sequence of zero or
more statements enclosed in curly braces {}. The curly braces define a
new scope for variables declared within the block.
CE – viết hoa nên là object, object thì có null

import java.io.*;

class Base {
public void amethod() throws FileNotFoundException {
}
}

public class ExcepDemo extends Base {


public static void main(String args[]) {
ExcepDemo e = new ExcepDemo();
}

@Override
public void amethod() {
}

public ExcepDemo() {
try {
DataInputStream din = new DataInputStream(System.in);
System.out.println("Pausing");
din.readByte();
System.out.print("Continuing");
this.amethod();
} catch (IOException ioe) {
}

}
}
A. Compile time error caused by protected constructor
B. Compile and run with output of "Pausing" and "Continuing" after a key is hit
C. Compile time error caused by amethod not declaring Exception
D. Runtime error caused by amethod not declaring Exception
99 100 102

B – con khác cha


What is the output when the following program is run?
A. a # b; a==c
B. a==b;a # c;
C. a #b, a#c

intern() là một phương thức của lớp String trong Java, được sử dụng để lấy một tham chiếu
đến chuỗi trong bộ nhớ heap (heap memory) của Java String Pool.

public class Test {

public static void main(String[] args) {

String a = "XYZ";
String b = new String("XYZ");
if (a == b) {
System.out.print(" a==b, ");
} else {
System.out.print(" a # b, ");
}
String c = b.intern();
if (a == c) {
System.out.println(" a == c");
} else {
System.out.println(" a # c");
}
}
}
B – đệ quy

D – super
C — mấy cái khác là tuần tự

D
2: 101010
>>:
>> là dịch giữ dấu, >>> là dịch không giữ dấu (nhiều > hơn thì dứt khoát hơn)
Zero-fill bit (hay còn gọi là unsigned right shift hay logical right shift) là một
phép dịch bit trên một số nguyên không giữ dấu, nghĩa là các bit 0 sẽ được
thêm vào bên trái của số sau khi dịch.

Both primitives and object references can be both converted and cast
( chuẩn)
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-97.html
Int chuyển sang double & ngược lại
int
Float là ép, string là convert

A
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-528.html
C
12
public class NewClass {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("dest");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(3);
dos.writeFloat(0.0001f);
dos.close();
fos.close();
}
catch (IOException e) { }
}
}

The writeFloat method of the DataOutputStream class writes a


float value to the output stream as a 32-bit quantity, which is equivalent
to 4 bytes.

writeInt method, which writes a 32-bit integer value (which is also


equivalent to 4 bytes) to the output stream. The writeInt method is used
to convert the float value to an int value using the
Float.floatToIntBits method before writing it to the output stream.

Which of the following is true?


A. A class inherits constructors from its superclasses.
B. A class inherits constructors from its direct superclass only
C. A class inherits constructors from its superclasses when the program points
out that.
D. A class does not inherit constructors from any of its superclasses.

C – points out

Nó nó không kế thừa constructor, mình phải chỉ ra thì nó ms kế thừa


public class A {
static int x;

public static void main(String[] args) {


A that1 = new A();
A that2 = new A();
x = 5;
that2.x = 1000;
x = -1;
System.out.println(x);
}
}
======> -1

in Java, constructors are always inherited from the superclass(es) of a


class, regardless of whether the program explicitly points it out or not.
In fact, the ability to inherit constructors is one of the key features of
object-oriented programming that promotes code reuse and reduces
duplication of code. When a subclass inherits a constructor from its
superclass, it can reuse the code in the superclass constructor to initialize
its own state, rather than duplicating that code in its own constructor.
So, option A is the correct statement, which states that a class inherits
constructors from its superclasses, and this is a fundamental feature of
Java's inheritance mechanism.

Which of the following statements is incorrect?

A. Values stored in TreeSet are automatically sorted.

B. Vector does not allow duplicate elements.

C. ArrayList can duplicate elements.

D. TreeSet does not allow duplicate elements.

B is incorrect: Vector allows duplicate elements.


Vector is a resizable array-like data structure that is similar to an
ArrayList, but with the added feature of being thread-safe. Like an
ArrayList, a Vector allows duplicate elements, and it does not
automatically sort its elements.

Suppose class X contains the following method:

void doSomething(int a., float b) { _ }

Which ofthe following methods may appear in class Y, which extends X?

A. private void doSomething(int a, float b) throws java.io.lOException {_ }

B. public void doSomething(int a. float b) throws java.io.IOException {_ }

C. private void doSomething(int a. float b) {_ }

D. public void doSomething(int a, float b) {_ }

===> D (nó phải rộng hơn)

public class Animal {


void doSomething(int a, float b) { }
}

public class Dog extends Animal{


private void doSomething(int a, float b) { }

}
Select an operation which may cause an unchecked exception.

a. Controlling the state of a running thread.

b. Accessing data in a file.

c. Accessing an element of an array

d. Accessing a remote resource.

e. Accessing data in a database.

Option C is an operation that may cause an unchecked exception.


Accessing an element of an array may cause an
ArrayIndexOutOfBoundsException, which is an unchecked exception.
This can occur if the index used to access the array is negative or greater
than or equal to the length of the array.
Unchecked exceptions are exceptions that do not need to be declared in a
method's signature or caught explicitly by the calling code. They can occur
at runtime and are usually caused by programming errors or unexpected
conditions that the program cannot recover from.
B

Bc

Statement 1: A protected member of a class can be accessed from any class in the
same package and from a subclass that is outside the package.
Statement 2: A member of a class that is declared private can be accessed only
within the class but nowhere outside the class.
Choose the correct answer?
Select one:
a. Statement 1 is FALSE, Statement 2 is TRUE

b. Statement 1 is TRUE, Statement 2 is FALSE

c. Both Statement 1 and Statement 2 are FALSE

d. Both Statement 1 and Statement 2 are TRUE


D – At the member level, you can also use the public modifier or no modifier (package-private) just as
with top-level classes, and with the same meaning. For members, there are two additional access
modifiers: private and protected. The private modifier specifies that the member can only be
accessed in its own class. The protected modifier specifies that the member can only be accessed within
its own package (as with package-private) and, in addition, by a subclass of its class in another package.

In his book, Herbert Schildt says in page 172 (3rd paragraph) that "protected applies
only when inheritance is involved.".

In page 228, Table 9-1 shows that a protected member can be accessed from a non-sub
class within the same package.

01 Given:
11. public static void parse(String str) {
12. try {
13. float f = Float.parseFloat(str);
14. } catch (NumberFormatException nfe) {
15. f = 0;
16. } finally {
17. System.out.println(f);
18. }
19. }
20. public static void main(String[] args) {
21. parse("invalid");
22. }
What is the result?
A. 0.0
B. Compilation fails.
C. A ParseException is thrown by the parse method at runtime.
D. A NumberFormatException is thrown by the parse method at runtime.
Answer: B – chưa khởi tạo f =))
B

C – vì nó xuất ra dạng string


B – i nó nó không static

public class Scope{


private int i;
public static void main(String argv[]){
Scope s = new Scope();
s.amethod();
}//End of main
public static void amethod(){
System.out.println(i); //end of amethod
}} //End of class

D – vector vs Array

class Up {
public Up(String s) {
System.out.print("B");
}
}

public class Down extends Up {


public Down(String s) {
// super(s);
System.out.print("D");
}

public static void main(String[] args) {


new Down("C");
System.out.println(" ");
}
}

=== nó không có constructor của lớp cha nên lỗi


=== nếu không lỗi thì nó sẽ in ra BD

Find the output of the below program?


class Animal { int id;
public Animal(){}
Animal(int id) { this.id = id;
}
}
public class Test {
public static void main(String[] args) {
Animal a1 = new Animal(1001);
Animal a2 = new Animal(1001);
Animal a3 = new Animal();
System.out.print(a1.equals(a2)+" ")
;
System.out.println(a2.equals(a3));
}
}

⇒ false false

● It first calls a1.equals(a2). Since a1 and a2 are two separate


objects with different memory addresses, their equals method will
return false.
● It then calls a2.equals(a3). Again, a2 and a3 are two separate
objects with different memory addresses, so their equals method
will also return false.

Nếu bạn override phương thức equals trong lớp Animal để so sánh
giá trị của instance variable id thay vì so sánh địa chỉ vùng nhớ của hai
đối tượng thì kết quả sẽ trả về là true khi so sánh a1.equals(a2)
trong đoạn mã trên.

Which of the following is true?


A. The ArrayList class is synchronized.
B. The Vector class use an array with fixed size to store objects
C. The Vector class provides the capability to implement a growable array of objects
D. The Vector class is not synchronized.

===> CC

https://www.geeksforgeeks.org/vector-vs-arraylist-java/
ArrayList is fast because it is non-synchronized. Vector is slow because it is
synchronized. Vector is synchronized, which means only one thread at a time
can access the code, while ArrayList is not synchronized, which means
multiple threads can work on ArrayList at the same time.

ArrayList increments 50% of the current array size if the number of


elements exceeds ts capacity. Vector increments 100% means doubles the
array size if the total number of elements exceeds its capacity.

Question 15)
What will be output if you try to compile and run the following code, but
there is no file called Hello.txt in the current directory?.

import java.io.*;
public class Mine {
public static void main(String argv[]){
Mine m=new Mine();
System.out.println(m.amethod());
}
public int amethod() {
try {
FileInputStream dis=new FileInputStream("Hello.txt");
}catch (FileNotFoundException fne) {
System.out.println("No such file found");
return -1;
}catch(IOException ioe) {
} finally{
System.out.println("Doing finally");
}
return 0;
}
}

1) No such file found


2 No such file found ,-1
3) No such file found, Doing finally, -1
4) 0

3) https://www.erpgreat.com/java/java-programmer-certification-mock-exam-no-1.htm

Which of these is correct way of calling a constructor having no parameters, of


superclass A by subclass B?

(a) super(void);
(b) superclass.();
(c) super.A();
(d) super();

=== D
Read more on Sarthaks.com - https://www.sarthaks.com/2434062/which-of-these-
correct-way-of-calling-constructor-having-parameters-superclass-subclass
The following lists the complete contents of the file named Derived.java

What will happen when this file is compiled?


A. The compiler will object to line 1.
B. Two class files, Base class and Derived class, will be created.
C. The compiler will object to line 7.

===> A vì nhiều class 1 file thì kh đc

public class Base extends Object {


String objType;
public Base() {
objType = "I am a Base type";
}
}

public class Derived extends Base {


public Derived() {
objType = "I am a Derived type";
}

public static void main(String[] args) {


Derived D = new Derived();
}
}

Choose two advantages of generics


A error detection at compile time
B error detection at runtime
C late binding
D. reduce casting

AD
https://docs.oracle.com/javase/tutorial/java/generics/why.html

The package provides some of the most useful Java classes that are
frequently needed in all types of applications.
A. java.lang
B. java.util
C. java.pack
D. java.io

— B vì cms bảo thế


3

B
Đa hình – F

(1) A value variable contains data's value.


(2) A reference variable contains the address of data.
The statement (1) is ___, and the statement (2) is___

True, false
False, true
False, false
True, true
True true

Select a correct statement

A. void f(double d, int ... x, int y) {}


B. void f(int ... x int ... y) {}
C. void f(int ... x int y) {}
D. void f(int x, int ... y) {}
đối số biến ... phải là tham số cuối cùng trong chữ ký của phương thức và không được theo
sau nó bởi bất kỳ tham số nào khác.
Which of the following is true about garbage collection?
A. If you want the program to collect garbage immediately, you should run the System.gc()
method.
B. You can force garbage collection of an object by setting all references to the object to
new values (null, for example).
C. Garbage collection guarantees that a program will not run out of memory.
D. Garbage collection does not guarantee that a program will not run out of memory.

D (does not)

http://www.java2s.com/ref/java/java-oca-ocp-practice-question-981.html

garbage collection does not guarantee that a program will not run out of
memory, because there are some situations where objects can still be
referenced and therefore not eligible for garbage collection, even though
the program no longer needs them. This can cause memory leaks and
eventually lead to an OutOfMemoryError.
Option A is incorrect because although System.gc() can suggest garbage
collection, it does not guarantee that garbage collection will occur
immediately. In fact, it is up to the JVM to determine whether or not to
perform garbage collection in response to a call to System.gc(). Option B is
incorrect because setting all references to an object to new values does
not guarantee that the garbage collector will actually collect the object, and
it is generally not a good practice to rely on this approach. Option C is
incorrect because although garbage collection can help prevent memory
leaks and manage memory usage, it cannot guarantee that a program will
not run out of memory under all circumstances.
A. Compiler error at line (1).
B. No compiler error and no exception.
C. An exception is thrown at line (2).
D. An exception is thrown at line (1).

Nó phải là age=ag chứ không phải age = age

The provided code has a syntax error in the constructor of class A. The
parameter int ag is incorrectly named as age, which is the same name
as the instance variable. This causes a compilation error because the
compiler cannot distinguish between the two and determine which one is
being referenced.
C

A ( do Base chứa void)


https://www.geeksforgeeks.org/java-gq/inheritance-2-gq/
Static không có thể ghi đè static (nhưng nó vẫn chạy đc)
class Base {
public void Base() {
System.out.println("Base");
}
}

public class In extends Base {


public static void main(String argv[]) {
In i = new In();
}
}

The ideal class to implement for the given programming problem is Set
because it is designed to store a collection of unique values and provides
efficient methods for testing membership, adding, and removing elements.
Since we want to store unique part ID numbers, we can use a Set to ensure
that each ID is only stored once.
Additionally, if we want the list to be in sorted order, we can use a
SortedSet implementation, such as TreeSet, which maintains its
elements in sorted order according to their natural ordering or a specified
comparator. Note that a SortedSet also satisfies all the requirements of
a Set.

public class Ombersley{


public static void main(String argv[]){
boolean b1 = true,
if((b==true) || place(true)){
System.out.printin("Hello Crowle"}.
}
}
public static boolean place(boolean location){ :
if(location==true){
System.out.printIn("Borcetshire"},
}
System.out.printIn("Powick"}
return true,
}
}
What will happen when you attempt to compile and run if?

A. No output "

B.Output of "Hello Crowle"

C. Output of Rnreatehira anrl Dawiek fallnwerl hư "Halln frnwla y

Trong đoạn code này, phương thức place() chỉ được gọi nếu biểu thức
(b1 == true) || place(true) trả về giá trị true. Tuy nhiên, vì biến
b1 được khởi tạo với giá trị true, biểu thức (b1 == true) sẽ trả về giá trị
true và phương thức place() không cần được gọi để đánh giá biểu
thức. Điều này có thể dẫn đến việc phương thức place() không được gọi,
dẫn đến việc không in ra chuỗi "Borcetshire".

BC
D sai vì nó chả ảnh hưởng gì cả

What does the following code do? Integer i = null;


if (i!= null & i.intValue() == 5) System.out.println("Value is 5");
A. Prints "Value is 5".
B. Throws an exception.
C. Compile error
D. Prints nothing

java.lang.NullPointerException

What happens when you try to compile and run the following application?
10. import java.io.*
11 public class Main [
12. public static void main(String argv[]) {
13 try
14
File d = new File("dir
15. Filet new File(d,"fi.xt").
18 (!exists()) { 17 LcreateNewFile().
18 21.
19 }catch (IOException e) { 20 e.printStackTrace()
22 1 231
A. Line 17 is never executed.
B. Line 17 throws an exception at runtime.
C. Line 15 throws an exception at runtime.
D. Line 17 creates a directory named "dir" and a file "fi.txt" within it
E. Line 15 creates a directory named 'dir" and a file "fi.txt" within it

public class NewClass {


// static final int[] a = { 100,200 };
static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
}

BD
D long không được vì nó to hơn int

A – không có break

public class NewClass {


public static void main(String[] args) {
int i = 9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}

23

Trong trường hợp của câu lệnh if, sử dụng toán tử & hoặc toán tử &&
không có sự khác biệt về kết quả, vì biểu thức điều kiện (x==4 & !b2) và
(x==4 && !b2) đều sẽ được đánh giá như nhau. Tuy nhiên, sử dụng toán
tử && sẽ có hiệu suất cao hơn trong một số trường hợp, vì nó sẽ ngắt việc
kiểm tra toán hạng bên phải nếu toán hạng bên trái đã là false.

public class Bar {


public static void main(String[] args) {
int x = 5;
boolean b1 = true;
boolean b2 = false;

if (x==4 & !b2)


System.out.print("1 ");
System.out.print("2 ");

if ((b2 = true) & b1)


System.out.print("3");
}
}

B
Truyền vào thì kh thay đổi gì, i++ thì in trước cộng sausau

and the rules governing these conversions are identical | dap an


Identical ở cuối (object rè)
\
C line 1 sai nhé

When a negative long is cast to a byte, what are the possible values of the result
| all the above
A đó
Vì kí tự thì nó xem là 1 số nguyên
| output: int version
import java.io.*;
public class Main {
public static void main(String argv[]) {
try {
File d = new File("dir");
File f = new File(d, "fi.txt");
if (!f.exists())
// d.mkdirs();
f.createNewFile();

} catch (IOException e) {
e.printStackTrace();
}
}
}

Which of the following is INCORRECT?


A. char c=\u1234;
B. char c=0x1234:
C. String x="ABC" +2:
D. char c=’\u1234’:

có dấu ‘ thì đúng


Ví dụ, để biểu diễn ký tự Unicode "A" (U+0041), bạn có thể sử dụng ký tự
escape \u0041. Ký tự escape này sẽ được xử lý tự động bởi trình biên dịch
Java để biến đổi thành ký tự Unicode tương ứng.

False ( super)

Ab, not thì kh chọn


Collection & map
https://docs.oracle.com/javase/tutorial/collections/interfaces/index.html
BE

A
Array.length không có ()

Bc
an inner class may be defined as static
an inner class may extend another class

False (method trong inteface là khum được có thân í)

Lỗi vì ở i
Output 2
B

Bc

Int ở đầu, loại AF


Ngoặc vuông, loại DE
Ad

C
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-569.html

C - allall
B

D, cả class & interface

A
A – abstract thì không có thânthân

class Base{
protected int i = 99;
}
public class Ab{
private int i = 1;
public static void main (String argv[]){
Ab a = new Ab();
a.hallow();
}
abstact void hallow(){
System.out.println("Claines "+i);
}
B — A chứ

AB

A
bd

C for sure

class A {
static int N = 10;
static String S = "Hello";
int x = 5;

static {
N = 7;
S = "GO";
}

void print() {
S = "TO";
System.out.println(S + N + x);
}
}

class Main {
public static void main(String[] args) {
System.out.println(A.S);
A a = new A();
a.print();
}
}

A vì tên filefile
CC

Vector: đồng bộ, chậm


Arraylist: đồng bộ, nhanh
CC
a for state ent can loop infinitely, for example: for(;;)

compilation and output of "not equal! 10"


A
A

C – stream streamstream
B all nhé

D nhé

What is the output of the following code:


class Main {
public static void main(String[] args){
byte b1 = 10;
byte b2 = 9;
b1 = (byte) (b1 |b2);
System.out.println(b1);
}
}
A. 14
B. 13
C. 9
D. 11
E. 8

1010
1001
→ 1011 = 1111

D
D
C not B

Object clone() giúp clone objectobject

Interface: default, cái kia là public


Which of these keywords must be used to monitor for exceptions - try

method of Object class is used to obtain class of an object at run time - Class
getClass()

RRead characters and strings in Java from console - BufferedReader

keywords is used to manually throw an exception - throw

method of ListIterator used to obtain index of previous element - previousIndex

methods is used to check for infinitely large and small values - isInfinite()

Generics add stability to your code by making more of your bugs detectable at
compile time

read a string from the input stream? - readLine()

all the exceptions that can be caught by using catch? - Exception

methods Byte wrapper return the value as a double - c. doubleValue()

methods of Character wrapper can be used to obtain the char value contained
in Character object.
methods of Character wrapper can be used to obtain the char value contained
in Character object. - getValue()

class is used to read from byte array - ByteArrayInputStream

InputStream và OutputStream trong Java đọc và ghi dữ liệu theo byte, chứ
không phải theo character. Điều này là do các lớp này được thiết kế để
hoạt động với các luồng dữ liệu nhị phân (binary streams) thay vì các
luồng dữ liệu văn bản (text streams).
Tuy nhiên, trong Java, bạn có thể sử dụng các lớp bọc (wrapper
classes) như InputStreamReader và OutputStreamWriter để đọc và ghi
dữ liệu theo character.

https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html

Given the following class:


package mypkg;

public class Fish {

protected int size;


protected void swim() { }

Which of the following may appear in a subclass of Fish named Tuna


that is not in the mypkg package?
● A. void swim() { }
● B. public void swim() { }
● C. size = 12;
● D. (new Tuna()).size = 12;

http://www.java2s.com/ref/java/java-oca-ocp-practice-question-10.html

#PRO192 RETAKE FE FALL23 BL5

Which of the following keywords can be applied to the methods of an interface?


A. default
B. private
C. final
D. protected
E. public
F. Depends on the particular implementation of the Java Virtual Machine
Mặc định method trong interface là public
public interface NewInterface {
default void a();
private void b();
final void c();
protected void d();
public void e();
void f();
}

(Choose 2 answers)
Which of the following methods can be legally inserted in place of the comment
//Method Here ? (select two)
class Base{
public void amethod(int i) {
}
public class Scope extends Base{
public static void main(String argv[]){
//Method Here
A. void amethod(int i) throws Exception {}
B. void amethod(long i) throws Exception {)
C. public void amethod(int i) throws Exception {}
D. void amethod(long i){}

Override thì không throws Exception → chọn long


// void amethod (int i) throws Exception {}
// void amethod (long i) throws Exception {}
// public void amethod(int i) throws Exception {}
// void amethod(long i) {}
// public void amethod(int i){};

If all three top-level elements occur in a source file, they must appear in which order?
A. Imports, package declarations, classes/interfaces/enums
B. Classes/interfaces/enums, imports, package declarations
C. Package declaration must come first, order for imports and class/interfaces/enum definiti
significant
D. Package declaration, imports, class/interface/enum definitions.
E. Imports must come first; order for package declarations and class/interface/enum definitic
significant

Java OCA OCP Practice Question 1230 (java2s.com)


In which stream, data unit is primitive data type or string?
A. Binary low-level stream
B. Binary high-level stream
C. Object stream
D. Character stream
FileReader in Java is a class in the java.io package which can be used to read a stream of
characters from the files.

Java treats all data sources ( file, directory, IO devices,…) as streams


The java.io package contains Java APIs for accessing to/from a stream.
A stream can be a binary stream.
Binary low-level stream: data unit is a physical byte.
Binary high-level stream: data unit is primitive data type value or a string.
Object stream: data unit is an object.
A stream can be a character stream in which a data unit is an Unicode character.

A low-level input stream reads data and returns it in bytes, and a low-level output stream
accepts data as bytes and writes the output in bytes.
https://tranthianhthi.files.wordpress.com/2018/01/06_i0_trong_java.pdf

Select the order of access More on Classes from least restrictive to most restrictive.
A. public, private, protected, default
B. default, protected, private, public
C. public, default, protected, private
D. default, public, protected, private
E. public, protected, default, private
Java OCA OCP Practice Question 1154 (java2s.com)
An object is
A. what classes are instantiated from
B. an instance of a class
C. a reference to an attribute
D. a variable
E. a concept of Object Oriented Programming
Consider the following code:
1. Dog rover, fido;
2. Animal anim;
3.
4. rover = new Dog();
5. anim = rover,
6. fido = (Dog)anim;
Where:
Mammal extends Animal Dog extends Mammal
Which of the following statements is true?
A. Line 5 will not compile.
B. Line 6 will not compile.
C. The code will compile but will throw an exception at line 6.
D. The code will compile and run.
E. The code will compile and run, but the cast in line 6 is not required and can be eliminated

Java OCA OCP Practice Question 201 (java2s.com)


public class Main {
public static void main(String[] args) {
Dog rover, fido;
Animal anim;

rover = new Dog();


anim = rover;
fido = (Dog) anim;
}
}

class Dog extends Animal {}


class Animal {}

Which of these stream contains the classes which can work on character stream?
A. InputStream
B. OutputStream
C. Character Stream
D. Byte Stream
Java.io Character Streams Questions & Answers - Sanfoundry

B
B

How can you change the current working directory using an instance of the File class called
A. FileName.chdir("DirName")
B. FileName.cd("DirName")
C. FileName.cwd("DirName")
D. The File class does not support directly changing the current directory.

By default, the java.lang package is imported into every Java program.


A. FALSE
B. TRUE

Study the following Java statements:


String s1= "Hello";
String s2= "Hello";
String s3= "Hello";
String s4= new String("Hello");
How many strings, specified by the above code, are stored in the memory of the program?
A. 2
B. 1
C. 4
D. None of the others
https://youtu.be/8Dmilyu9UJQ

Select correct statement:


A. String objects are constants. StringBuffer objects are not.
B. StringBuffer objects are constants. String objects are not.
C. Both String and StringBuffer objects are constants.
D. Both String and StringBuffer objects are not constants
Difference between string and stringBuffer? (50webs.com)
You have been given a design document for a veterinary registration system for
implementation in Java. It states:

"A pet has an owner, a registration date, and a vaccination-due date. A cat is a pet that has
a flag indicating if it has been neutered, and a textual description of its markings."

Given that the Pet class has already been defined and you expect the Cat class to be used
freely throughout the application, how would you make the opening declaration of the Cat
class, up to but not including the first opening brace? Use only these words and spaces:
boolean, Cat, class, Date, extends, Object, Owner, Pet, private, protected, public, String.
A. protected class Cat extends Owner
B. public class Cat extends Object
C. public class Cat extends Pet
D. private class Cat extends Pet
You have been given a design document for a veterinary registration system for
implementation in Java. It states

"A pet has an owner, a registration date, and a vaccination-due date. A cat is a pet that has
a flag indicating whether it has been neutered, and a textual description of its markings."

Given that the Pet class has already been defined, which of the following fields would be
appropriate for inclusion in the Cat class as members? (Choose all that apply.)
A. Pet thePet;
B. Date registered;
C. Date vaccinationDue;
D. Cat theCat;
E. boolean neutered;
F. String markings;
public class Test{
public static void main(String[] args){
String s1 = "xyz";
String s2 = "xyz";
if (s1 == s2)
System.out.println("Line 4");
if (s1.equals(s2)) System.out.println("Line 6");
}
}
What is the output?
A. Line 4
Line 6
B. Line 4
C. Line 6
D. No output, compile error
E. No output
https://youtu.be/cFXbWRlTTF8
public class Test{
public static void main(String[] args){
Object ob1= new Object();
Object ob2= ob1;
if(ob1.equals(ob2)) System.out.println("ob1 equals ob2");
if(ob1==ob2) System.out.println("ob1==ob2"); System.out.println("Have a nice day!");
}
}
What is the output?
A. ob1 equals ob2
ob1==ob2
Have a nice day!
B. ob1 equals ob2
Have a nice day!
C. ob1==ob2
Have a nice day!
D. Have a nice day!
https://youtu.be/2cgLTZfmy44
A

Given the following:


List<String> names =new ArrayList<String>();
Which of the following statements are legal? (Select two)
A. Iterator<String> iter = names.iterator();
B. for (String s:names)
C. while (String s:names)
D. int sizes = names.getSize();
https://youtu.be/OvnbyHALlnY
Which of the following statements is true?
A. An interface can only contain method and not variables
B. Interfaces cannot have constructors
C. A class may extend only one other class and implement only one interface
D. Interfaces are the Java approach to addressing its lack of multiple inheritance, but requir
classes to create the functionality of the Interfaces.

An interface cannot contain a constructor (as it cannot be used to create objects)


An Interface in Java doesn't have a constructor because all data
members in interfaces are public static final by default, they are
constants (assign the values at the time of declaration). There are
no data members in an interface to initialize them through the
constructor.

What will be the result when you attempt to compile and run the
following code?.
public class Conv{
public static void main(String argv[]){
Conv c=new Conv();
String s=new String("ello");
c.amethod(s);
}
public void amethod(String s){
char c='H';
c+=s;
System.out.println(c);
}
}
A. Compilation and output the string "Hello"
B. Compilation and output the string "ello"
C. Compilation and output the string elloH
D. Compile time error
String không cộng trực tiếp đc vs char
https://youtu.be/q17a_oZbAI0

What is the range of values that can be assigned to a variable of type short?
A. Depends on the underlying hardware
B. 0 through 2^16-1
C. 0 through 2^32 - 1
D. -2^15 through 2^15-1
E. -2^31 through 2^31-1

All objects belonging to the same class have the same characteristics and possible actions
A. TRUE
B. FALSE
Class chỉ là khuôn mẫu thôi nên, các object cùng class vẫn có thể có các tính chất khác
nhau tùy theo người dùng định nghĩa

class Dogl{
String mat;
String mui;

public Dog(String mat, String mui) {


this.mat = mat;
this.mui = mui;
}
}

Dog a = new Dog("xanh", "cao");


Dog b = new Dog("den", "thap");

Is the following interface valid?


public interface NewInterface{}
A. NO
B. YES

Đây là cách khai báo interface, có thể thêm ; hoặc không


What happens when you try to compile and run this application?
1. import java.util.*;
2.
3. public class Apple {
4. public static void main(String[] a) {
5. Set<Apple> set = new TreeSet<Apple>();
6.set.add(new Apple());
7.set.add(new Apple());
8. set.add(new Apple());
9. }
10.}
A. No exception is thrown.
B. An exception is thrown at line 7 (Apple cannot be cast to java.lang.Comparable)..
C. Compiler error.
D. An exception is thrown at line 8 (Apple cannot be cast to java.lang.Comparable)..
E. An exception is thrown at line 6 (Apple cannot be cast to java.lang.Comparable).
https://youtu.be/YSNBW2_bPeU
Given:
11. public static void foo(String str) {
12. try {
13. float x = Float.parseFloat(str);
14.} catch (NumberFormatException e) {
15. x = 0;
16.} finally {
17. System.out.println(x);
18.)
19.}
20. public static void main(String[] args) {
21. foo("invalid");
22.}
What is the result?
A. 0.0
B. Compilation fails at line 15 with message about variable x not found.
C. A ParseException is thrown by the foo method at runtime.
D. A NumberFormatException is thrown by the foo method at runtime
###1

public class Example {


public static void foo(String str) {
float x;
try {
x = Float.parseFloat(str);
} catch (NumberFormatException e) {
x = 0;
} finally {
System.out.println(x);
}
}

public static void main(String[] args) {


foo("invalid");
}
}

Suppose prime is an int and wrapped is an Integer. Which of the following are legal Java stal
A. prime = wrapped;
B. wrapped = prime;
C. prime = new Integer(9);
D. wrapped = 9;
E. All the others
Given:
55. int []x= {1, 2,3,4, 5};
56. int y []=x;
57. System.out.println(y[2]);
Which is true?
A. Line 57 will print the value 2.
B. Line 57 will print the value 3.
C. Compilation will fail because of an error in line 55.
D. Compilation will fail because of an error in line 56
###2
Which of the following declarations is INCORRECT?
A. int[] ar = new int(3);
B. double d = 1.3E + 21;
C. double d = 1.3D;
D. String s = "Hi!";

String s = "Hi!";
int[] ar = new int(3);
int[] ar = new int[3];
double d =1.3E+21;
double d =1.3D;

OOP

Inheritance

The ability to define a class or object as an extension of another class or object is


A. Polymorphism
B. Inheritance
C. Encapsulation
D. Abstraction
E. Overloading
F. Overriding
Abstraction

The process of identifying common features of objects and methods is


A. Polymorphism
B. Inheritance
C. Encapsulation
D. Abstraction
E. Overloading
F. Overriding

Polymorphism

The ability of a programming language to process objects differently depending on their type
is

a. Inheritance
b. Overloading
c. Polymorphism
d. Abstraction
e. Encapsulation
f. Overriding

Encapsulation

____ is the process of identifying and grouping attributes and actions related to a particular
entity as relevant to the application at hand
A. Persistence
B. Construction
C. Polymorphism
D. Data abstraction
E. Inheritance
F. Encapsulation

=====================

Is this code snippet INCORRECT?


List<String> myIntList = new LinkedList<String>();
myIntList.add(0);

A. TRUE
B. FALSE
Is it possible to define a class called Thing so that the following method can return true under
certain circumstances?
boolean weird(Thing s) {
Integer x = new Integer(5);
return s.equals(x);
}

A. Yes
B. No

Dùng toString

The _______ escape sequence brings the cursor to the beginning of the current line.
A. \n
B. \r
C. \t
D. \\
E. \b
F. Which sequence depends on the particular implementation of the Java Virtual
Machine
Java OCA OCP Practice Question 66 (java2s.com)
This question concerns the following class definition:
1. package one
2
3. public class Bird (
4 protected static int k = 0;
5. public Bird() (k++; }
6. protected void fly() {}
7. static int getValue() { return(k);)
8.)
Which statement is true about class Bird and the following class Grebe?
1. package two,
2.
3. class Parrot extends one Bird (
4. Parrot() (k++)
5.
6. public static void main(String args[]) (
7. System.out.print("Before: " + k);
8. Parrot x = new Parrot();
9. System.out.println(" After: " + k):
10. x.fly):
11.}
12.}
A. The program will compile and execute. The output will be Before: 0 After: 2
B. The program will compile and execute. The output will be Before: 0 After: 1.
C. Compilation of Parrot will fail at line 4 because static members cannot be
overridden
D. Compilation of Parrot will fail at line 10 because method fly() is protected in the
superclas
###3

package one;

public class Bird {

protected static int k = 0;

public Bird() {
k++;
}

protected void fly() {


}

static int getValue() {


return (k);
}
}

package two;

public class Parrot extends one.Bird {

Parrot() {
k++;
}

public static void main(String args[]) {


System.out.println("Before: " + k);
Parrot x = new Parrot();
System.out.println(" After: " + k);
x.fly();
}
}

Given the following class definition


public class Upton{
public static void main(String argv[]){
}
public void amethod(int i){}
//Here
}
Which of the following would be illegal to place after the comment //Here?
A. public int amethod(int z){}
B. public int amethod(int i, int j){return 99;}
C. protected void amethod(long I){}
D. private void anothermethod(){}
###4
Which of the following statement(s) is (are) true?
1)An abstract class cannot have any final methods.
2)A final class may not have any abstract methods.
A. Only statement 1
B. Only statement 2
C. Both statement 1 and 2
D. None of them
Given a string constructed by calling s = new String("xyzzy"), which of the calls modifies the
string
A. s.append("aaa");
B. s.trim();
C. s.substring(3);
D. s.replace('z', 'a');
E. s.concat(s);
F. None of the others

String thì không có modify gì nhé


https://coderanch.com/t/196043/certification/String

Which of the following modifiers does not allow a variable to be modified its value once it was
initialized.
A. final
B. static
C. private
D. transient – lasting for only a short time; temporary:
Question:Execute the following code in an empty directory. What is the result?

1. File f1 = new File("dirname");

2. File f2 = new File(f1, "filename");

A. A new directory called dirname is created in the current working directory.

B. A new directory called dirname is created in the current working directory. A new file called

filename is created in the directory.

C. A new directory called dirname and a new file called filename are created, both in the

current working directory.

D. A new file called filename is created in the current working directory.

E. No directory is created, and no file is created.

Answer:E is correct. Constructing an instance of the File class has no effect on the local file

system.

https://www.java-samples.com/showtutorial.php?tutorialid=715
Given the following class definition, which of the following statements would be legal
after the comment //Here (select two)
class InOut{
String s= new String("Between");
public void amethod(final int iArgs){
int iam;
class Bicycle{
public void sayHello(){
//Here
}
}//end of bicycle class
}//end of amethod
public void another(){
int iOther;
}
}
A. System.out.println(s);
B. System.out.println(iOther); //
C. System.out.println(iam); // chưa khởi tạo
D. System.out.println(iArgs);
public class InOut {

String s = new String("Between");

public void amethod(final int iArgs) {


int iam;
class Bicycle {
public void sayHello() {
System.out.println(s);
// System.out.println(iOther);
System.out.println(iam);
System.out.println(iArgs);
}
}//end of bicycle class
}//end of amethod
public void another() {
int iOther;
}
}

(Choose 1 answer) Which of the following may legally appear as the new type
(between the parentheses) in a cast operation?
A. Primitives
B. All of the others
C. Abstract classes
D. Final classes

Int x = (int)2.0
Which of the following statements is true?
A. An abstract class may be instantiated.
B. An abstract class must contain at least one abstract method.
C. An abstract class must contain at least one abstract data field.
D. An abstract class must declare that it implements an interface.
E. An abstract class may not have any abstract method
Java OCA OCP Practice Question 73 (java2s.com)

An abstract class
A. can contain all concrete methods.
B. must contain at least one abstract method.
C. must contain all abstract method.
D. can not contain any data field
If you need a Set implementation that provides value-ordered iteration, which class
should you use?
A. HashSet
B. LinkedHashSet
C. TreeSet
D. None of them
Answers to Questions and Exercises: (The Java™ Tutorials > Collections >
Implementations) (oracle.com)

Which one statement is true about the following code fragment? (choose 1)
1. import java.lang.Math;
2. Math myMath = new Math();
3. System.out.println("cosine of 0.123 = " + myMath.cos( 0.123 ) );

A. Compilation fails at line 2.


B. Compilation fails at line 3.
C. Compilation succeeds, although the import on line 1 is not necessary. During
execution, an exception is thrown at line 3.
D. Compilation succeeds. The import on line 1 is necessary. During execution, an
exception is thrown at line 3.
E. Compilation succeeds and no exception is thrown during execution.

Math không phải khởi tạo

B
Math thì không thể extend,
Math là private inteface nên nó cũng không new được
Given:
11. public abstract class Shape {
12. int x;
13. int y;
14. public abstract void draw();
15. public void setAnchor(int x, int y) {
16. this.x = x;
17. this.y = y;
18. }
19.}
and a class Circle that extends and fully implements the Shape class.
Which is correct?
A. Shape s = new Shape(); s.setAnchor (10,10); s.draw();
B. Circle c = new Shape(); c.setAnchor (10,10); c.draw();
C. Shape s = new Circle(); s.setAnchor (10,10); s.draw();
D. Circle c = new Circle(); c.Shape.setAnchor (10,10); c.Shape.draw();

###5

public abstract class Shape {


int x;
int y;

public abstract void draw();

public void setAnchor(int x, int y) {


this.x = x;
this.y = y;
}
}

public static void main(String[] args) {


//Shape s = new Shape() {}; s.setAnchor (10,10); s.draw();
//Circle c = new Shape(); c.setAnchor (10,10); c.draw();
Shape s = new Circle(); s.setAnchor (10,10); s.draw();
//Circle c = new Circle(); c.Shape.setAnchor (10,10); c.Shape.draw();
}

A(n) is a characteristic that describes an object


A. Method
B. Operation
C. Attribute
D. Message
E. Event
B

What interfaces can be implemented in order to create a class that can be serialized?
A. No interfaces need to be implemented. All classes can be serialized.
B. implements java.io.Serializable. There are no methods in the interface.
C. implements java.io.Serializable, which defines two methods: readObject and writeObject.
D. implements java.io.Externalizable, which defines two methods: readObject and
writeObject.
E. implements java.io.Externalizable, which defines two methods: readExternal and
writeExternal

http://www.java2s.com/ref/java/java-oca-ocp-practice-question-169.html

Suppose a source file contains a large number of import statements. How do the imports
affect the time required to compile the source file?
a. Compilation takes no additional time.
b. Compilation takes slightly more time.
c. Compilation takes significantly more time.
d. Compilation takes slightly less time.
Java OCA OCP Practice Question 1001 (java2s.com)
Java OCA OCP Practice Question 1241 (java2s.com) – Class loading takes no
additional time.
#PRO192 SPRING 2023 ca 16h10

Given:
20. public class CreditCard {
22. private String cardID;
23. private Integer limit;
24. public String ownerName;
26. public void setCardInformation(String cardID,
27. String ownerName,
28. Integer limit) {
29. this.cardID = cardID;
30. this.ownerName = ownerName;
31. this.limit = limit;
32. }
33. }
Which is true?
A. The class is fully encapsulated.
B. The code demonstrates polymorphism.
C. The ownerName variable breaks encapsulation.
D. The cardID and limit variables break polymorphism

Thuộc tính phải là private

What will happen when you attempt to compile and run this code?
class Base{
public final void amethod(){
System.out.println("amethod");
}
}
public class Fin extends Base{
public static void main(String argv[]){
Base b = new Base();
b.amethod();
}
}
A. Compile time error indicating that a class with any final methods must be declared final its
B. Compile time error indicating that you cannot inherit from a class with final methods
C. Run time error indicating that Base is not defined as final
D. Success in compilation and output of "amethod" at run time.
hand side

Which of the following may appear on the left-hand side of an instanceof operator?
A. A reference
B. A class
C. An interface
D. A variable of primitive type

Which of the following may appear on the right-hand side of an instanceof operator?
(Choose all that apply.)
A. A reference
B. A class
C. An interface
D. A variable of primitive type
E. The name of a primitive type

Thẻ ghi nhớ: 3 | Quizlet


B (đã làm)

Given:
1. public interface A {
2. String DEFAULT_GREETING = "Hello World";
3. public void method1();
4.}
A programmer wants to create an interface called B that has A as its parent. Which interface
correct?
A. public interface B extends A {}
B. public interface B implements A {}
C. public interface B instanceOf A {}
D. public interface B inheritsFrom A {}
DURGA SOFTWARE SOLUTIONS
In order to use the TreeSet class, the class that describes elements must implement the..... i
A. java.lang.Comparable
B. java.lang.Comparing
C. java.util.Comparable
D. java.util.treeset.Compare

Which one statement is true about the following code?


1. String s1 = "abc" + "def";
2. String s2 = new String(s1);
3. if (s1 == s2)
4. System.out.println("== succeeded");
5. if (s1.equals(s2))
6. System.out.println(".equals() succeeded");
A. Lines 4 and 6 both execute.
B. Line 4 executes and line 6 does not.
C. Line 6 executes and line 4 does not.
D. Neither line 4 nor line 6 executes

11. public class Person {


12. int age;
13. String name;
14.
15. public Person() {
16. this("Peter");
17. System.out.print("first ");
18. }
19.
20. public Person (String name) {
21. this(42, "Peter");
22. System.out.print("second ");
23. }
24.
25. public Person (int age, String name) {
26. this.age = age;
27. this.name = name;
28. System.out.print("third ");
29. }
30.
31. public static void main (String[] args) {
32. Person b = new Person();
33. System.out.print(b.name + " " + b.age);
34. }
35. }
What is the result?
A. Peter 42 third second first
B. third second first Peter 42
C. first second third Peter 42
D. third first second Peter 42
E. Peter 42 first second third

● The default constructor public Person() is called.


● Inside the default constructor, the this("Peter") statement is executed, which
calls the public Person(String name) constructor.
● Inside the public Person(String name) constructor, the this(42, "Peter")
statement is executed, which calls the public Person(int age, String name)
constructor.
● Inside the public Person(int age, String name) constructor, the age and name
fields are assigned, and the "third " is printed to the console.
● After the public Person(int age, String name) constructor completes, the
"second " is printed to the console.
● Finally, the "first " is printed to the console.

public class Person {


int age;
String name;

public Person(){
this("Peter");
System.out.print("first ");
}

public Person(String name) {


this(42, "Peter");
System.out.print("second ");
}

public Person(int age, String name) {


this.age = age;
this.name = name;
System.out.print("third ");
}

public static void main(String[] args) {


Person b = new Person();
System.out.print(b.name + " " + b.age);
}
}

Given:
11. public interface Status {
12./* insert code here */ int MY_VALUE = 10;
13.}
Which three are valid on line 12? (Select three)
A. final
B. static
C. native
D. public
E. protected
F. abstract

B (đã làm)

C
Select the correct statement:
A. An object reference cannot be cast to an interface reference
B. An object reference can be cast to an interface reference when the object implement all
methods of the referenced interface.
C. An object reference can be cast to an interface reference when the object implements the
referenced interface.
D. An object reference can always be cast to an interface reference.
are methods which are in the same class and have the same name but different parar
A. Overloaded methods
B. Overridden methods
C. Override able methods
D. Overload able methods
E. Shared methods
F. Shadowing methods

Same class → overload


Khác class -> overriden

Method overloading: overloading means two or more methods in one class have the same
method name but different parameters.
https://www.quora.com/Are-methods-with-the-same-name-in-different-classes-and-different-
signature-overloading-Java-OOP-overloading-development

An/A ___ declaration contains signatures, but no implementations, for a set of me also contain
constant definitions.
A. class
B. object
C. data type
D. abstract class
E. interface
A (đã làm)

D (đã làm)
B C (đã làm)

Which of the following is true about Wrapped classes?


A. Wrapped classes are classes that allow primitive types to be accessed as objects.
B. Wrapper classes are: Boolean, Character, Byte, Integer, Long, Float, and Double – thiếu
Short
C. Wrapper classes are: Boolean, Char, Byte, Short, Integer, Long, Float, and Double.

Wrapper Classes in Java | Baeldung


What is the output when you try to compile and run the following program?
public class Main {
static void foo(String x){System.out.println("String");}
static void foo(StringBuffer y){System.out.println("StringBuffer");}
static void foo(Integer z){System.out.println("Integer");}
public static void main(String argv[]){
f(null);
System.out.println();
}
}

A. No output, compile-time error.


B. StringBuffer
C. String
D. The code runs with no output.
E. Integer

A class defines an entity, while an object is the actual entity


A. True
B. False
anar

What will happen if you try to compile and run the following code?
public class Q {

public static void main(String argv[]) {


int anar[] = new int[5];
System.out.println(anar[0]);
}
}

A. Error anar is referenced before it is initialized


B. null
C. 0
D. 5

public class Q {

public static void main(String argv[]) {


int anar[] = new int[]{1, 2, 3};
System.out.println(anar[1]);
}
}

C – chưa thực thi amethod

What will be the result of attempting to compile and run the following code?
abstract class MineBase {
abstract void amethod();
static int i;
}
public class Mine extends MineBase {
public static void main(String argv[]){
int[] ar=new int[5];
for(i=0;i < ar.length;i++)
}
}
A. a sequence of 5 0's will be printed
B. Error: ar is used before it is initialized
C. Error Mine must be declared abstract
D. IndexOutOfBoundes Error

=============
What is the output of the program below ?

public class Main {


public static void main(String[] args) {
try {
System.out.println("ABC1");
int i = 0;
float t1 = 1 /i;
System.out.println("ABC2");
System.out.println("ABC3");
} catch (Exception e) {
System.out.println("Exception");
} finally {
System.out.println("finally 1");
}
System.out.println("last1");
}
}

A. ABC1
Exception
finally 1
last1
B. ABC1
ABC2
ABC3
Exception

A Java source code will be compiled to........


A. Java bytecode.
B. Machine code.
C. Assembly code.
D. Operation system code

Câu nào có bytecode thì chọn


What will happen when you attempt to compile and run the following code?

class Base {

Base() {
System.out.println("Base");
}
}

public class Checket extends Base {

public static void main(String argv[]) {


Checket c = new Checket();
super();
}
Checket() {
System.out.println("Checket");
}
}
A. Compile time error
B. Checket followed by Base
C. Base followed by Checket
D. runtime error

Super phải ở đầu của constructor

Which statement is true about this application?


public class StaticStuff {
static int x = 10;
static { x += 5;}

public static void main(String args[]) {


System.out.println("x = " + (x++));
}
static { x /= 5;}
}

A. Lines 5 and 12 will not compile because the method names and return types are missing.
B. Line 12 will not compile because you can only have one static initializer.
C. The code compiles and execution produces the output x = 10.
D. The code compiles and execution produces the output x = 15
E. The code compiles and execution produces the output x = 3

Chạy static trước


D (đã làm)
When does the string created on line 2 become eligible for garbage collection?
1. String s = "aaa";
2. String t = new String(s);
3. t += "zzz";
4. t = t.substring(0);
5. t = null;
A. After line 3
B. After line 4
C. After line 5
D. The string created on line 2 does not become eligible for garbage collection in this code

Java OCA OCP Practice Question 1 (java2s.com)

In order for objects in a List to be sorted, those objects must implement which
interface and method?
a. Comparable interface and its compare method
b. Comparable interface and its compareTo method
c. Comparable interface and its equals method
d. Compare interface and its compareTo method
Given the following code, what will be the outcome?
10. public class Funcs extends java.lang. Math {
11. public int add(int x, int y) {
12. return x + y;
13. }
14. public int sub(int x, int y) {
15. return x - y;
16. }
17. public static void main(String[] a) {
18. Funcs f = new Funcs();
19. System.out.println("" + f.add(1, 2) + " " + f.sub(3,4));
20. }
21.}
A. The code compiles but does not output anything.
B. "3-1" is printed out to the console.
C. The line 10 causes compile-time error.
D. "3 1" is printed out to the console.
The process of identifying common features of objects and methods is
A. Polymorphism
B. Inheritance
C. Encapsulation
D. Abstraction
E. Overloading
F. Overriding

D (đã làm)
Suppose the declared type of x is a class, and the declared type of y is an interface.
When is the assignment x = y; legal?
● A. When the type of x is Object
● B. When the type of x is an array
● C. Always
● D. Never
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-240.html

Which statement is true about the following method?


public static int selfXor(int i) {
return i ^ i;
}

A. It always returns 0.
B. It always returns 1.
C. It always an int where every bit is 1.
D. The returned value varies depending on the argument

Làm việc với bit


Giống nhau thì =0

Select INCORRECT statement about serialization. (choose 1)


a. The process of writing an object is called serialization.
b. To serialize an object, first create an instance of java.io.ObjectOutputStream.
c. When an Object Output Stream serializes an object that contains references
to another object, every referenced object is not serialized along with the original
object.
d. When an object is serialized, it will probably be deserialized by a different
The ability of a programming language to process objects differently depending on their type
is

a. Inheritance
b. Overloading
c. Polymorphism
d. Abstraction
e. Encapsulation
f. Overriding

B (đã làm)

How do you use the File class to list the contents of a directory?
A. String contents = myFile.list();
B. File contents = myFile.list();
C. StringBuilder contents = myFile.list();
D. The File class does not provide a way to list the contents of a directory.
Java OCA OCP Practice Question 548 (java2s.com)

What happens when you try to compile and run the following program?
import java.util.*;
public class Main{
public static void main(String argv[]){
Vector<Integer> t = new Vector<Integer>();
t.add(12);
t.add(2);
t.add(5);
t.add(2);
Iterator<Integer> i = t.iterator();
int sum=0;
while(i.hasNext()) sum += i.next();
System.out.println(sum);
}
}
A. The program will print out: 19
B. The program will print out: 21
C. The program will print out: 17
D. The program has a compile error
import java.util.*;

public class Main {

public static void main(String argv[]) {


Vector<Integer> t = new Vector<Integer>();
t.add(12);
t.add(2);
t.add(5);
t.add(2);
Iterator<Integer> i = t.iterator();
int sum = 0;
while (i.hasNext()) {
sum += i.next();
}
System.out.println(sum);
}
}

D (đã làm)

After the following code fragment ran, what is the value of variable a?
String s;
int a;
s = "Foolish boy.";
a = s.indexOf("fool");

A. -1
B. 0
C. 4
D. random value
E. 1
import java.util.*;

public class Main {


public static void main(String argv[]) {
String s;
int a;
s = "Foolish boy.";
a = s.indexOf("fool");
System.out.println(a);
}
}

Is this declaration is correct?


MyList<Point> list = new MyList()<Point>
A. TRUE
B. FALSE
Thiếu dấu ; & thứ tự của ()<> bị sai

What will be the result when you attempt to compile this program?

public class Rand {


public static void main(String argv[]) {
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}

A. Compile time error referring to a cast problem


B. A random number between 1 and 10
C. A random number between 0 and 1
D. A compile time error about random being an unrecognised method
Which of the statements below are true?
A. To change the current working directory, call the setWorkingDirectory() method of
the
File class.
B. To change the current working directory, call the cd() method of the File class.
C. To change the current working directory, call the changeWorkingDirectory()
method of the File class.
D. To check whether the file denoted by the abstract pathname is a directory or not,
call the method of the File class

Khum change the current working directory được

An instance of the java.util.Scanner class can read data from the keyboard (1), a file
(2), a string of characters (3).
(1)is ............ ,(2) is.............. ,and (3) is................
A. true, true, true
B. true, true, false
C. true, false, true
D. None of the others.
E. true, false, false

B (đã làm)

which of the following is legal loop construction


A.
int j = 0;
for (int k = 0; j + k != 10; j++, k++) {
System.out.println("j=" + j + ". k=" + k);
}

B.
int j=0;
do {
System.out.println("j=" + j++);
if(j==3) continue loop;
} while (j<10);

C.
int i = 3;
while (i) {
System.out.println("i is " + i);
}

D.
while (int i<7) {
i++;
System.out.println("i is " + i);
}


B (đã làm)
When is it appropriate to pass a cause to an exception's constructor?
● A. Always
● B. When the exception is being thrown in response to catching of a different
exception type
● C. When the exception is being thrown from a public method
● D. When the exception is being thrown from a private method
http://www.java2s.com/ref/java/java-oca-ocp-practice-question-473.html

What does the following code do?


A. Prints "Value is 5".
B. Throws an exception.
C. Compile error
D. Prints nothing

B, do khi check i.intValue() nó sẽ check khi i đang null, nên throw nullpointer exception
Given the following code
import java.io.*;
public class Ppvg {

public static void main(String argv[]) {


Ppvg p = new Ppvg();
p.flition();
}

public int flition() {


try {
FileInputStream din = new FileInputStream("Ppvg.java");
din.read();
} catch (IOException ioe) {
System.out.println("flytwick");
return 99;
} finally {
System.out.println("fliton");
}
return -1;
}
}

Assuming the file Ppvg.java is available to be read which of the following statements
is true if you try to compile and run the program?
A. An error will occur at compile time because the method fliton attempts to return
two values
B. The program will run and output only"fliton" and"flytwick"
C. The program will run and output only"flytwick"
D. The program will run and output only"fliton"
What happens when you attempt to compile and run these two files in the same directory?

//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
//File P2.java
public class P2 extends P1{
public static void main(String argv[]){
P2 p2 = new P2();
p2.afancymethod();
}
}

1) Both compile and P2 outputs "What a fancy method" when run


2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time

Khác package nên 1 cái chạy đc 1 cái không


Java Programmer Certification Mock Exam No. 2 (jchq.net)
B (đã làm)
#PRO192 ca 14h30 FA23

class Van {
String driver;
int rate;

Van() {
driver = "unknown";
rate = 5;
}

Van(String driver, int rate) {


this.driver = driver;
this.rate = rate;
}

public String toString() {


return (driver + "," + rate);
}
}

class SpecVan extends Van {


int type;

SpecVan() {
super();
}

SpecVan(String driver, int rate, int type) {


super(driver, rate);
this.type = type;
}

void display() {
String s = "(" + super.toString() + "," + type + ")";
System.out.println(s);
}
}

public class Main {


public static void main(String[] args) {
SpecVan x = new SpecVan();
SpecVan y = new SpecVan("Hoa", 20, 10);
x.display();
y.display();
System.out.println();
}
}

B -done

B
class Base {
Base(int i) {
System.out.println("Base");
}
}

class Seven extends Base {


public static void main(String argv[]) {
Seven s = new Seven();

Seven() {
System.out.println("Seven");
}
}

import java.util.*;

public class Main {

public static void main(String argv[]) {


String x = "ABC$PQUV";
int k = x.indexOf("$");
String y = x.substring(0, k);
String z = new String(new char[]{'A', 'B', 'C'});
System.out.print(y + "");
System.out.println(y.equals(z));
}
}

A -done
A -done

A. Comparable
B. Comparable<Student>
C Comparator<Student>
D. Comparator

B
C

B. Package

C
B không được protected

D - super phải ở đầu


class Vase {

String color;
int price;

Vase() {
price = 5;
}

Vase(String color, int price) {


this.color = color;
this.price = price;
}

public String toString() {


return (color + "," + price);
}
}

class SpecVase extends Vase {

int type;

SpecVase() {
type = 5;
}

SpecVase(String color, int price, int type) {


this.type = type;
super(color, price);

void display() {
String s = "(" + super.toString() + "," + type + ")";
System.out.println(s);
}
}

public class Main {

public static void main(String[] args) {


SpecVase x = new SpecVase();
SpecVase y = new SpecVase("Hoa", 20, 10);
x.display();
y.display();
System.out.println();
}
}
A
Ghi đè

B
C

Abe

C
D

D
interface A {
void foo();
void fun();
}

class B implements A {
public void foo() {
System.out.print("B1");
}

public void fun() {


System.out.print("B2");
}
}

public class Main {


public static void main(String[] args) {
A t = new B();
t.foo();
t.fun();
}
}

C - ko co dau phay
C

interface Eating {

public void getHour();

public int getMeals();


}

abstract class Meal implements Eating { //(1)

public void getHour() {


System.out.println(getMeals());
}
}

public class Main1 {

public static void main(String[] args) {


Eating e = new Meal() { //(2)
@Override
public int getMeals() {
return 3;
}
};
e.getHour(); //(3)
}
}
A. 3
B. Compilation error in line (2)
C. Compilation error in line (1)
D. Compilation error in line (3)

https://youtu.be/D8E-3hjl7Xk

Given the following class definition


public class Droitwich{
class one{
private class two{
public void main(){
System.out.println("two");
}
}
}
}
Which of the followiung statements is true?
A. The code will not compile because class two is marked as private.
B. The code will compile without error.
C. The code will compile and output the string two at runtime.
D. The code will not compile because the classes are nested to more than one level

What is the output when you try to compile and run the following program?

public class Main{


void f(String t) {System.out.println("String");}
void f(StringBuffer h) {System.out.println("StringBuffer");}
public static void main(String argv[]){
f("ABC");
System.out.println();
}
}

A. String
B. No output, compile-time error
C. The code runs with no output
D. StringBuffer

Method phải là static


public class Main{
static void f(String t) {System.out.println("String");}
static void f(StringBuffer h) {System.out.println("StringBuffer");}
public static void main(String argv[]){
f("ABC");
System.out.println();
}
}
Nếu static thì in ra “String”

Assuming any exception handling has been set up, which of the following will
create an instance of the RandomAccessFile class?

1) RandomAccessFile raf = new RandomAccessFile("myfile.txt","rw");


2) RandomAccessFile raf = new RandomAccessFile( new DataInputStream());
3) RandomAccessFile raf = new RandomAccessFile("myfile.txt");
4) RandomAccessFile raf = new RandomAccessFile( new File("myfile.txt"));

The Java.io package (jchq.net)


A

given that you have a method scale defined as follows, where scalex and scaley are
constants

public Point scale( int x, int y ){


return new Point(
( int )(x / scalex ),
( int )( y / scaley ) ) ;
}
what will happen when you call this method with double primitives instead of int, as in the
following fragment?

1. double px = 10.02 ;
2. double py = 20.34;
3. Point thePoint = scale( px, py ) ;
A. The compiler objects to line 1.
B. The program compiles and runs
C. The program compiles but a runtime cast exception is thrown.
D. A compiler error occurs in line 3
Double → int

public class Main {


private static final double scalex = 2.0;
private static final double scaley = 3.0;

public static void main(String[] argv) {


double px = 10.02;
double py = 20.34;
Point thePoint = scale(px, py);
System.out.println("Scaled point: (" + thePoint.x + ", " + thePoint.y + ")");
}

public static Point scale(int x, int y) {


return new Point((int) (x / scalex), (int) (y / scaley));
}
}

class Point {
public int x;
public int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}
}

Class SomeException:
1. public class SomeException {
2. }

Class A:
1. public class A {
2. public void doSomething() { }
3. }

Class B:
1. public class B extends A {
2. public void doSomething() throws SomeException { }
3. }

Which is true about the two classes? (Choose one.)


a. Compilation of both classes will fail.
b. Compilation of both classes will succeed.
c. Compilation of class A will fail. Compilation of class B will succeed.
d. Compilation of class B will fail. Compilation of class A will succeed.

What will happen when you attempt to compile and run this code?

class Base {

abstract public void myfunc();

public void another() {


System.out.println("Another method");
}
}

public class Abs extends Base {

public static void main(String argv[]) {


Abs a = new Abs();
a.amethod();
}

public void myfunc() {


System.out.println("My func");
}

public void amethod() {


myfunc();
}
}

A. The code will compile and run,printing out the words 'My Func"
B. The code will compile but complain at run time that the Base classs has non abstract
methods
C. The compiler will complain that the Base class is not declared as abstract
D. The compiler will complain that the method myfunc in the base class has no body

End

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy