0% found this document useful (0 votes)
7 views5 pages

Java Clean1

The document contains a series of programming questions and answers related to Java concepts, including the command pattern, exception handling, multithreading, and file processing. It addresses various scenarios such as serialization, stream operations, and thread synchronization using AtomicBoolean. The content is structured as a quiz format, providing correct and incorrect options for each question.

Uploaded by

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

Java Clean1

The document contains a series of programming questions and answers related to Java concepts, including the command pattern, exception handling, multithreading, and file processing. It addresses various scenarios such as serialization, stream operations, and thread synchronization using AtomicBoolean. The content is structured as a quiz format, providing correct and incorrect options for each question.

Uploaded by

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

1. When using the command pattern, which class performs an operation?

Receiver

2. What will the following code print?


List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
list.stream()
.peek(num -> System.out.print(num + " "))
.filter(x -> x > 5)
.findAny()
.get();

1 10

3. You serialized a Person object as follows:


public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private final Integer id;
private final String name;

public Person(Integer id, String name) {


this.id = id;
this.name = name;
}

public Integer getId() {


return id;
}

public String getName() {


return name;
}

@Override
public String toString() {
return id + " " + name;
}
}
You add a new field to this class.
private final String nickname;
You try to deserialize the previously serialized Person object with the modified
version of class Person. What happens?

It works without error and the new field in the deserialized object is set to null.

4. When the following method is called, it opens a ServerSocket that will wait for
a client to connect on port 9000, then it sends back "Hello" to the client and
closes the connection and the ServerSocket.
public void hello() throws IOException {
try (ServerSocket ss = new ServerSocket(9000);
OutputStream out = ss.accept().getOutputStream()) {
out.write("Hello".getBytes(StandardCharsets.US_ASCII));
out.flush();
}
}
The network connection gets disturbed and the out.write(...) call throws an
exception A. But closing the output stream also throws an exception B. What exactly
happens to the exceptions A and B?

Exception A is thrown out of the method and exception B is suppressed. Code


handling exception A can get exception B by calling getSuppressed() on exception A.

5. What is the main reason to use Java's exception chaining mechanism?


Your choice: correct -
To provide error information so an implementation-specific exception is wrapped up
in a more general exception with the original exception as the cause

6. In large, complicated pieces of software, when a stack trace is finally logged,


the original exception has been caught and wrapped in a different exception
multiple times. What is the best approach to understand such a stack trace?

The root cause is the exception that was thrown first, which you can find near the
bottom of the stack trace.

7. You are writing a program that reads a large comma-separated values (CSV) file
and inserts a row in a database for each line. To make the program faster, you make
it multi-threaded. You create and start four threads that each read a line from the
CSV file and insert a record into the database in a loop in both cases. What
problems are you likely to experience with this approach?

The program will not be much faster than the single-threaded version because
input/output (I/O) bandwidth limits performance.

8. What is an example of code reuse?

Calling the .toString() method on a non-primitive object

9. You are writing a web application in which you want logged in users to be able
to see which other users are currently logged in. You use a list to keep track of
the currently logged in users, as follows:
List<User> currentUsers = new CopyOnWriteArrayList<>();

You have a "Current users" page that lists the currently logged in users by
producing an HTML list:
public void outputCurrentUsers(PrintWriter out) {
out.println("<ul>");
for (User user : currentUsers) {
out.println("<li>" + user.getName() + "</li>");
}
out.println("</ul>");
}
What happens when a user logs out and is removed from the list while in another
thread the outputCurrentUsers() method is iterating over the list? (Assume that
execution has reached the body of the for-loop at least once).

The outputCurrentUsers() method will finish normally, no exception occurs; the name
of the user who just logged out will definitely appear in the list.
10. Which relationship between classes A and B must be fulfilled to decide that B
must perform delegation to an A?

B HAS-A A

11. You run the following program:


public class ThreadsDemo {
public static void main(String[] args) {
final AtomicInteger counter = new AtomicInteger();

Runnable task = new Runnable() {


@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(counter.incrementAndGet());
}
}
};

Thread thread1 = new Thread(task);


Thread thread2 = new Thread(task);

thread1.run();
thread2.run();
}
}
What does it print?

The numbers 1 through 10, each on a new line

12. The "test.txt" file does not exist. InputStream.readAllBytes() is a method that
was added in Java 9. It may throw an IOException. What happens when you try to
compile and run the following code?
try {
InputStream in = new FileInputStream("test.txt");
System.out.println(new String(in.readAllBytes(),StandardCharsets.UTF_8));
in.close();
} catch (IOException e) {
System.out.println("Error while opening file");
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (Exception e) {
System.out.println("Unknown error");
}

The code does not compile, because the FileNotFoundException catch block is
unreachable code.

13. Which operation refers to taking a stream and replacing the results with the
contents of a mapped stream by applying the provided mapping function to each
element?

flatMap()

14. Which pattern reuses the already created objects?


Flyweight

15. The following line of code initializes a list:


List<String> list = new ArrayList<>();
Which line will execute without throwing an exception?
Incorrect -
list.stream().collect(
Collectors.maxBy(
(s1, s2) -> s1.length() - s2.length()
)
).orElseThrow(RuntimeException::new);
Incorrect -
list.stream().collect(
Collectors.maxBy(
Comparator.comparing(String::length)
)
).get();
Your choice: correct -
list.stream().collect(
Collectors.maxBy(
(s1, s2) -> s1.length() - s2.length()
)
).orElse("No value");

16. Which stream method receives a predicate written as a lambda expression?


Your choice: correct -
allMatch()

17. What would you use to implement the command pattern?

One functional interface with a method that different lambda expressions will
define; each lambda expression will represent a command

18. You can use AtomicBoolean for lock-free thread synchronization. You are
implementing a class FileProcessor and want to ensure that only one thread at a
time processes the file. Your code looks like the following. What implementation of
the process() method correctly implements lock-free synchronization?
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class FileProcessor {


private static final AtomicBoolean flag = new AtomicBoolean(false);
private final File file;

public FileProcessor(File file) {


this.file = file;
}

public void process() throws IOException {


// Choose one of the answers
}

private void processImpl() throws IOException {


// ... implementation omitted
}
}
Your choice: correct -
public void process() throws IOException {
if (flag.compareAndSet(false, true)) {
try {
processImpl();
} finally {
flag.set(false);
}
}
}

19. What must you do to initialize certain fields of an object of a class that you
wrote with special values when such an object is deserialized?
Correct -
Implement a method with the following signature in your class that initializes the
fields the way you want:

private void readObject(java.io.ObjectInputStream in) throws IOException,


ClassNotFoundException;

20. The following anonymous class intends to filter all files from the current
folder that have ".txt" as the extension:
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
};
File[] files = new File(".").listFiles(filter);
Which attempt at an equivalent rewrite of the code above will result in a syntax
error?

FileFilter filter = new FileFilter() {


@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
};

File[] files = new File(".").listFiles(FileFilter::accept);

You might also like