0% found this document useful (0 votes)
134 views

MJT2019 c2 v1 With Answers PDF

The document contains a multiple choice quiz with 22 questions related to programming concepts like JSON, REST, HTTP, threading, and unit testing. It asks about valid JSON objects, JSON data types, converting an object to JSON with Gson, REST architecture concepts, HTTP methods and advantages of HTTP/2, threading concepts like deadlocks and executors, Java Stream API usage, JUnit annotations and testing with Mockito stubs and mocks.

Uploaded by

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

MJT2019 c2 v1 With Answers PDF

The document contains a multiple choice quiz with 22 questions related to programming concepts like JSON, REST, HTTP, threading, and unit testing. It asks about valid JSON objects, JSON data types, converting an object to JSON with Gson, REST architecture concepts, HTTP methods and advantages of HTTP/2, threading concepts like deadlocks and executors, Java Stream API usage, JUnit annotations and testing with Mockito stubs and mocks.

Uploaded by

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

FMI-MJT2019 Name: Fac.

#:

1. Which of the following is NOT a valid JSON object?


a. { "name": "Smiley",
"age": "20",
"phone": "888-123-4567",
"email": "[email protected]",
"happy": true }

b. { "name": "Smiley",
"age": 20,
"phone": null,
"email": null,
"happy": true }

c. { "name": "Smiley",
"age": 20,
"phone": { "888-123-4567", "888-765-4321" },
"email": "[email protected]",
"happy": true }

2. From the following, which data types are supported by JSON?


a. Number, String
b. Boolean, Array
c. Object, null
d. All of the above

3. Given the following snippet


class Song {
private String name;
private String artist;

public Song(String name, String artist) {


this.name = name;
this.artist = artist;
}
}

Song song = new Song("lovely", "Billie Eilish");

How will you convert song to json using Gson?

Gson gson = new Gson(); 
String jsonString = gson.toJson(song, Song.class);

4. REST is?
a. Architectural style
b. Protocol
c. Translated as "Ailyak" in Plovdiv
d. Web framework

5. What is a Resource in REST?


REST architecture treats every content as a resource. These resources can be
text files, html pages, images, videos or dynamic business data. REST Server
simply provides access to resources and REST client accesses and modifies the
resources. Each resource is identified by URIs/ global IDs. 

6. List the common HTTP methods and their use case

GET – gets a resource from the server 


HEAD - similar to GET, but retrieves only the headers, without the body 
POST – sends data (e.g. HTML form content) to the server for processing. The
data is contained in the body of the request
PUT – uploads a resource to the server 
DELETE – deletes a resource from the server

7. What does the following code fragment do? Comment the semantics of each
line 1-6

HttpClient client = HttpClient.newHttpClient(); // 1


HttpRequest request =
HttpRequest.newBuilder().uri(URI.create("https://www.facebook.com")).build(); // 2
client.sendAsync(request, BodyHandlers.ofString()) // 3
.thenApply(HttpResponse::headers) // 4
.thenAccept(System.out::println) // 5
.join(); // 6

(1) Creates an HttpClient instance from static factory method


(2) Creates an HttpRequest instance (GET request) with the given URI from static
builder method
(3) Send asynchronous HTTP GET request for the resource with the given URI
(4) gets the headers from the HttpResponse
(5) outputs them to the standard output and
(6) waits for the request thread to complete before resuming execution of the
current thread

8. What are the main advantages of HTTP/2 versus HTTP/1.1?

- binary instead of text → more compact


- fully multiplexed instead of ordered and blocking → achieves parallelism using
just one TCP connection between the client and the server
- uses headers compression → more compact
- allows servers to push HTTP responses proactively to the client → more
effective in asynchronous scenarios

9. Which method of the Buffer class would you use to prepare the buffer for
reading?
a. prepare()
b. clear()
c. flip()
d. read()

10. Write a java code snippet that will allow your application to listen on
port 4444 for incoming connections and to accept them. Use classes from
package java.net.
ServerSocket serverSocket = new ServerSocket(4444); 
Socket socket =  serverSocket.accept();

11. In the code below, there is one line missing. Find which line is missing
and where it should be entered. If you do not fix it, the code will enter
an endless loop.

while (true) {
int readyChannels = selector.select();
if (readyChannels == 0) continue;

Set<SelectionKey> selectedKeys = selector.selectedKeys();


Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isReadable()) {
//A channel is ready for reading
}
// missing line
keyIterator.remove(); 
}
}

12. Are there any bugs in the code fragment below? If yes, mark and fix them.

Socket connection = new ServerSocket(hostname, port);


BufferedReader input = new BufferredReader(new
InputStreamReader(connection.getInputStream()));
PrintWriter output = new
PrintWriter(connection.getOutputStream());

new Thread(() -> {


String line;
while((line = input.readLine()) != null) {
System.out.printf("Server said: %s", line);
}
}).start();
output.write("Hello, server!");

13. How can a thread exit from a deadlock with another thread?
a) by calling its own yield() method
b) by calling the other thread’s yield method
c) it cannot exit a deadlock once has occurred
d) by calling Thread.sleep()

14. Which of the statements are correct?


a) a thread can “have” several different locks during its execution
b) a thread can “have” just one lock at any given point of time during
its execution
c) a thread could acquire a second lock after having acquired another
lock, but this leads to a deadlock
d) a thread cannot acquire any lock

15. Which line(s) of code inserted at the place of the comment will start a
thread?

class X implements Runnable {


public static void main(String args[]) {
/* Insert line here */
new Thread(new X()).start();

public void run() {}


}

16. What are some benefits of using thread executors instead of creating and
starting threads manually?

Creating new threads is expensive. Because Executors uses a thread pool,


you get to easily reusable threads, resulting in better performance. 

17. How many threads will be started during the whole lifecycle of the
following program?

public class StudentTask implements Runnable {


public void run() {
System.out.println("Go to FMI");
try { Thread.sleep(1000); } catch
(InterruptedException e) { }
System.out.println("Go back home");
}

public static void main(String[] args) {


ExecutorService executor
= Executors.newFixedThreadPool(10);
new Thread(() -> {
for (int i = 0; i < 13; i++)
executor.submit(new StudentTask());
}).run();
}
}

11

18. Given the following, find the longest word of the list by using the Java
Stream API:
List<String> list = Arrays.asList("The River", "Gravity", "I Found");
list.stream().max(Comparator.comparingInt(String::length)).get();

19. In the context of functional programming what is a “side effect” and what
is the term for a function that does not cause side effects?

Side effect is any change in program state that is external to the function.


Functions without side effects are called “pure”.

20. What is the difference between @Before and @BeforeClass annotations?


Give an example of when we should use @BeforeClass instead of @Before.

The method annotated with @Before is executed before every test


case, whereas @BeforeClass is executed only once. We should use
@BeforeClass when we do not expect any change in the state of the initialized
objects.

21. Create 2 JUnit tests for the class below using Mockito or stubs. Write
just the test methods.

public class UserService {


private UserRepository repository;

public UserService(UserRepository repository) {


this.repository = repository;
}

public User register(String email, String password) {


if (repository.exists(email)) {
throw new UserAlreadyExistsException();
}
User user = new User(email, password);
repository.save(user);
return user;
}
}

@Test(expected = UserAlreadyExistsException.class)
public void testRegisterThrowsAppropriateException() {
UserRepository mock = mock(UserRepository.class);

when(mock.exists("[email protected]")).thenReturn(true);

UserService service = new UserService(mock);


service.register("[email protected]", "weak");
}

@Test
public void testRegisterSavesUser() {
UserRepository mock = mock(UserRepository.class);
when(mock.exists("[email protected]")).thenReturn(false);

UserService service = new UserService(mock);


User actual = service.register("[email protected]", "weak");

assertEquals(actual.getEmail(), "[email protected]");
assertEquals(actual.getPassword(), "weak");
}

22. What is the difference between stubbing and mocking? In which cases
mocking is preferred?

In unit testing, stubbing is creating an object for test purposes that


simulates a real object with the minimum number of methods required for a
test. For example, if your class is dependent upon database, you can use
HashMap to simulate database operation. Stub object is mostly created by
developers and their methods are implemented in a predetermined way, they
mostly return hard-coded values. They also provide methods to verify methods
to access stub's internal state, which is necessary to verify internal state
of object. Mock objects are usually created by some open source library -
mock framework like Mockito, jMock and EasyMock. These libraries help to
create, verify and stub mocks. Mock object has knowledge of how its methods
are executed in a unit test, and it verifies if methods are actually called
against the expected ones. Apart from first difference that mock objects are
usually created by mock framework, another key difference between Stub and
Mock object is how they are used. Stub object is usually used for state
verification, while mock object is mostly used for behavior verification.
Mocking is preferred when the composed class refers to an external resource
(REST API, database, file system, etc.), the logic of the composed class is
not trivial or you cannot setup the test environment in a trivial way.

23. Explain Java Exception Hierarchy

24. Provide some Java Exception Handling Best Practices


- don’t suppress / “swallow” exceptions
- don’t leave an empty catch block, or a catch with just
e.printStackTrace()
- always preserve the stack trace when wrapping the exception into a new
one by linking the original exception

25. What is wrong with the program below?

import java.io.FileNotFoundException;
import java.io.IOException;

public class TestException1 {


public static void main(String[] args) {
try {
go();
} catch (IOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}

public static void go() throws IOException, FileNotFoundException {


}
}

It will not compile. FileNotFoundException is a subclass of IOException


and should be before it in the catch chain – otherwise it’s catch block is
unreachable code.

printStackTrace() is also bad exception handling.

26. What is the fastest way to get all the unique elements from an array
using data structures in Java? Write a code snippet.

Put the elements in a Set: 

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray)); 
Set<T> mySet = Set.of(someArray); 
var mySet = Set.of(someArray);

The above can be done in several other ways.


27. We have the following Java class:

public class Book {


private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
}

What is the most suitable data structure if we want to keep books sorted
by name?
What else should be done for our solution to work?

TreeSet/TreeMap. Book class should override Comparable, or we shall


provide Book Comparator instance.

28. Given:
public class MyKeys {
Integer key;

MyKeys(Integer k) {
key = k;
}

@Override
public boolean equals(Object o) {
return ((MyKeys) o).key == this.key;
}

public static void main(String[] args) {


Map m = new HashMap();
MyKeys m1 = new MyKeys(1);
MyKeys m2 = new MyKeys(2);
MyKeys m3 = new MyKeys(1);
MyKeys m4 = new MyKeys(new Integer(2));
m.put(m1, "car");
m.put(m2, "boat");
m.put(m3, "plane");
m.put(m4, "bus");
System.out.print(m.size());

}
}

What is the result?


a. 2
b. 3
c. 4
d. Compilation Fails.
29. Check whether clean code principles are applied and correct the code
where necessary.
/**
* Checks if all numbers in the array are contained at least 'occ'
times
*/
public static boolean findOccuraences(int[] a, int n, int occ) // name
should be a verb // maybe give more meaningful param names
{
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < a.length; i++){ // missing space before ( and
after ). This has to be fixed at many places below also
if(map.containsKey(a[i])){
map.put(a[i],map.get(a[i]++)); // missing space after ,
}
else if(!map.containsKey(a[i])) { // this if is not needed: it
checks the negated condition of the if above
map.put(a[i], 1);
}
}
boolean flag = true;
for (int i : map.values()) {
if(i<occ) { // missing spaces
flag = false; // better directly return false here, no
need to continue looping and checking
}
}
// you can directly return true here.
// in any case, the “if” below is equivalent to “return flag;”.
if(flag == true) {
return true;
} else {
return false;
}
}

30. JSON is an alternative to

a. SOAP
b. JAX-RS
c. HTML
d. XML
e. HTTP
f. AJAX
g. CSS
h. YAML

31. JSON stands for

a. JavaScript Object Notation


b. Java Object Notation
c. JSON Object Notation
d. None Of The Above

32. What will be the output of the following code?

public class MyClass {


public static void main(String[] args) {
try {
methodThrowingRuntimeException();
System.out.print("A");
} catch (RuntimeException ex1) {
System.out.print("B");
} catch (Exception ex2) {
System.out.print("C");
} finally {
System.out.print("D");
}
System.out.print("E");
}

public static void methodThrowingRuntimeException() {


throw new RuntimeException();
}
}

a. BD
b. BCD
c. BDE
d. BCDE

33. Are there any bugs in the following code fragment? Identify and fix, if
any

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;

public class HttpResponseBodyLengthRetriever {


public static void main(String... args) throws Exception {
HttpClient client = new HttpClient();
HttpRequest request =
HttpRequest.newBuilder().uri("https://www.youtube.com/").build();
System.out.println(client.request(request,
BodyHandlers.ofByteArray()).length);
}
}

1. HttpClient cannot be instantiated with new → use the static factory method or
the static builder method
2. uri() is not applicable to String, it requires URI
instance: URI.create("https://www.youtube.com/")
3. client.request instead of client.send
4. missing .body() before .length

34. List HTTP’s status code groups and their use cases.

 1xx – informational response 


 2xx – the request was successfully processed 
 3xx – the requested resource is available elsewhere  
 4xx – client error 
 5xx – server error

35. What is the default port of HTTP?


a. 80
b. 8080
c. 4444
d. 8000

36. Write the text of a simple HTTP request.

GET / HTTP/1.1

( or as String, "GET / HTTP/1.1\r\n")

37. Which three are methods of the Object class?


a. notify();
b. notifyAll();
c. isInterrupted();
d. interrupt();
e. wait(long msecs);
f. sleep(long msecs);

38. What is printed to the standard output executing the following code?

public class MyThread extends Thread {

public static void main(String[] args) {


Thread t = new Thread(new MyThread());
Thread t2 = new Thread(new MyThread());
Thread t3 = new Thread(new MyThread());
t.start();
t2.start();
t3.start();
t.setPriority(1);
t3.setPriority(3);
}

public void run(){


System.out.print(Thread.currentThread().getPriority() + " ");
}
}

a. The output could be "1 3 0".


b. The output could be "3 0 1".
c. The output could be "1 9 3".
d. The output could be "3 5 1".
e. The output could be "3 0 3".
f. The output could be "3 1".
g. This program does not compile.

39. What is a daemon thread?

 Daemon thread is a low priority thread (in context of JVM) that runs in
background to perform tasks that do not prevent the JVM from exiting (even if
the daemon thread itself is running) when all the user threads (non-daemon
threads) finish their execution.

40. Which of these are thread-safe collections?

a. Vector
b. HashMap
c. ArrayList
d. Hashtable
e. BlockingQueue
f. TreeSet

You might also like