Week 6 Flashcards

1
Q

What is a functional interface in Java?

A

A functional interface is an interface that contains only one abstract method. It may have multiple default or static methods but should have just one abstract method to be functional. It’s often used as a target for lambda expressions or method references.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do functional interfaces differ from regular interfaces?

A

Functional interfaces have exactly one abstract method, allowing them to be implemented by lambda expressions. Regular interfaces can have multiple abstract methods, making them unsuitable for lambda expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can you give an example of a built-in functional interface in Java?

A

One example is java.util.function.Predicate, which represents a boolean-valued function of one argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you implement a functional interface using a lambda expression?

A

A functional interface can be implemented using a lambda like this:

Predicate<Integer> isEven = (x) -> x % 2 == 0;</Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the purpose of the @FunctionalInterface annotation?

A

This annotation is used to indicate that an interface is intended to be a functional interface. It also ensures that the compiler will generate an error if the interface has more than one abstract method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a default method in a functional interface?

A

A default method is a method in an interface that has an implementation. It is not abstract, so it does not need to be implemented by a class that uses the interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can a functional interface extend another functional interface?

A

Yes, a functional interface can extend another functional interface, provided that it does not add any new abstract methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the significance of the java.util.function package?

A

This package contains functional interfaces commonly used for lambda expressions and method references, such as Predicate, Consumer, Function, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a lambda expression in Java?

A

A lambda expression is a short block of code that takes parameters and returns a value. Lambda expressions are used primarily to define the behavior of functional interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can you describe the syntax of a lambda expression?

A

The basic syntax is
(parameters) -> expression
or
(parameters) -> { statements }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does a lambda expression differ from an anonymous inner class?

A

Lambda expressions are more concise and focus on defining a method’s behavior, while anonymous inner classes require more boilerplate code. Also, lambdas do not have access to this in the same way that anonymous inner classes do.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the advantages of using lambda expressions?

A

Conciseness and readability
Facilitation of functional programming
Encourages the use of higher-order functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In what scenarios would you use lambda expressions?

A

Lambda expressions are useful in scenarios like passing behavior as a parameter (e.g., sorting, filtering, or event handling).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a lambda expression’s target type?

A

The target type of a lambda expression is the type of the functional interface it is assigned to.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can a lambda expression throw checked exceptions?

A

Yes, but the functional interface’s method must declare the exception in its signature.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does a method reference differ from a lambda expression?

A

A method reference is more concise when the method already exists, while a lambda expression defines new behavior inline.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a method reference in Java?

A

A method reference is a shorthand notation of a lambda expression that refers to a method by name. It allows existing methods to be passed as lambda expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the different types of method references?

A

Static method reference: ClassName::staticMethod
Instance method reference of a particular object: instance::method
Instance method reference of an arbitrary object of a particular type: ClassName::method
Constructor reference: ClassName::new

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can you provide an example of a static method reference?

A

Function<String, Integer> parseInt = Integer::parseInt;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you create an instance method reference?

A

If you have an instance of a class, you can reference its method like this:

MyClass obj = new MyClass();
Supplier<String> methodRef = obj::someMethod;</String>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the syntax for using a constructor reference?

A

Supplier<MyClass> constructorRef = MyClass::new;</MyClass>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does REST stand for?

A

REST stands for Representational State Transfer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the key principles of RESTful architecture?

A

Statelessness
Client-server separation
Uniform interface
Resource-based interaction
Cacheability
Layered system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does REST differ from SOAP?

A

REST is simpler, stateless, and typically uses JSON or XML over HTTP, while SOAP is a protocol that uses XML messaging and provides more features like built-in error handling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the common HTTP methods used in REST?

A

GET: Retrieve data
POST: Create new data
PUT: Update data
DELETE: Remove data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the purpose of a resource in REST?

A

A resource represents a piece of data that can be accessed and manipulated using RESTful API endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Can you explain the concept of statelessness in REST?

A

Each request from the client to the server must contain all the information needed to understand and process the request, as no session state is stored on the server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is Javalin, and what are its primary use cases?

A

Javalin is a lightweight web framework for Java and Kotlin, primarily used to build RESTful APIs and web applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How does Javalin compare to other web frameworks like Spring?

A

Javalin is simpler and more lightweight compared to Spring, which is more feature-rich and comes with a larger ecosystem.

26
Q

Can you explain how to set up a basic Javalin application?

A

Javalin app = Javalin.create().start(7000);
app.get(“/”, ctx -> ctx.result(“Hello World”));

27
Q

What are Javalin’s built-in features for handling requests and responses?

A

Javalin provides simple handlers for processing requests (GET, POST, PUT, DELETE, etc.), context handling for responses, query parameters, path parameters, form data, JSON serialization/deserialization, and WebSocket support.

28
Q

How do you configure a Javalin application?

A

You can configure a Javalin application using the Javalin.create() method, where you can pass a configuration block for things like setting the port, enabling CORS, adding exception handlers, or static file locations:

Javalin app = Javalin.create(config -> {
config.addStaticFiles(“/public”);
}).start(7000);

29
Q

What are the common configuration options available in Javalin?

A

Setting the server port
Enabling or disabling CORS
Configuring static file serving

30
Q

How can you set up CORS in a Javalin application?

A

You can enable CORS (Cross-Origin Resource Sharing) like this:

Javalin app = Javalin.create(config -> {
config.enableCorsForAllOrigins();
}).start(7000);

31
Q

What is a handler in Javalin?

A

A handler in Javalin is a functional interface (lambda) that processes incoming HTTP requests. Handlers respond to client requests and generate appropriate responses.

32
Q

Can you explain the difference between a handler and a middleware in Javalin?

A

Handler: Processes the request directly and returns a response.
Middleware: Intercepts the request before it reaches a handler or manipulates the response after it leaves the handler (e.g., logging, authentication, etc.).

32
Q

How can you handle query parameters in Javalin?

A

Query parameters can be accessed using the ctx.queryParam() method:

app.get(“/search”, ctx -> {
String query = ctx.queryParam(“q”);
ctx.result(“Search for: “ + query);
});

33
Q

What is the importance of exception handling in RESTful services?

A

Proper exception handling ensures that clients receive meaningful error messages and appropriate HTTP status codes when something goes wrong in the API.

33
Q

How do you create a GET handler in Javalin?

A

You can create a GET handler like this:

app.get(“/hello”, ctx -> ctx.result(“Hello World”));

34
Q

How can you implement global exception handling in a Javalin application?

A

You can implement global exception handling by adding an exception handler:

app.exception(Exception.class, (e, ctx) -> {
ctx.status(500);
ctx.result(“An error occurred: “ + e.getMessage());
});

35
Q

What is the difference between checked and unchecked exceptions in Java?

A

Checked exceptions must be either caught or declared in the method signature (IOException, SQLException).
Unchecked exceptions (subclasses of RuntimeException) do not need to be explicitly handled (NullPointerException, IllegalArgumentException).

36
Q

What is JSON, and why is it commonly used in RESTful APIs?

A

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for both humans and machines to read and write. It’s commonly used in REST APIs due to its simplicity and wide language support.

37
Q

How can you parse JSON data in Java?

A

You can use libraries like Jackson, Gson, or org.json to parse JSON data:

ObjectMapper mapper = new ObjectMapper();
MyClass obj = mapper.readValue(jsonString, MyClass.class);

38
Q

What libraries are available for working with JSON in Java?

A

Jackson
Gson
org.json
JSON-B (Java EE standard for JSON binding)

39
Q

How do you serialize a Java object to JSON?

A

Using Jackson:

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(myObject);

40
Q

How do you expose a RESTful API endpoint in Javalin?

A

You can expose an endpoint in Javalin like this:

app.post(“/users”, ctx -> {
User user = ctx.bodyAsClass(User.class);
// Process user
ctx.status(201).result(“User created”);
});

41
Q

What is the role of URL path parameters in RESTful APIs?

A

Path parameters are used to identify specific resources within a collection. For example, /users/{id} allows the client to specify the user ID in the URL.

42
Q

How can you consume a RESTful API using Java?

A

You can use libraries like HttpURLConnection, Apache HttpClient, or OkHttp to consume RESTful APIs. Example with HttpURLConnection:

URL url = new URL(“https://api.example.com/resource”);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(“GET”);

43
Q

What are the best practices for designing RESTful API endpoints?

A

Use nouns in URLs to represent resources (e.g., /users, /orders)
Use HTTP methods appropriately (GET, POST, PUT, DELETE)
Use status codes to indicate the outcome of requests
Ensure stateless communication
Provide pagination for large datasets

44
Q

What is a REST resource, and how is it represented in a URL?

A

A REST resource is any information that can be named and represented in a RESTful system. It is typically represented in a URL as a noun:

/users/123 // Resource: user with ID 123

45
Q

What are the conventions for naming RESTful endpoints?

A

Use plural nouns for collections (e.g., /users)
Use singular nouns for individual resources (e.g., /users/123)
Use HTTP methods to define the action (e.g., GET /users, POST /users)

46
Q

How do you construct URLs for nested resources in REST?

A

Use hierarchical paths to represent relationships:

/users/123/orders/456 // Orders for user 123

47
Q

How can you implement authentication in a RESTful API?

A

You can use methods like token-based authentication (e.g., JWT) or session-based authentication to verify user credentials.

47
Q

What is the difference between authorization and authentication?

A

Authentication is the process of verifying a user’s identity.
Authorization is the process of verifying what resources or actions the user is allowed to access.

48
Q

What are some common methods of authorization in REST APIs?

A

Role-based access control (RBAC)
OAuth 2.0
Token-based authentication (JWT)

49
Q

How do you configure Logback in a Java application?

A

Logback is configured using an XML file (logback.xml), typically placed in the classpath.

49
Q

What is Logback, and how does it compare to other logging frameworks like Log4j?

A

Logback is a logging framework that is a successor to Log4j, known for its performance improvements and configurability. It is widely used and integrated with SLF4J.

50
Q

What are the different logging levels provided by Logback?

A

TRACE
DEBUG
INFO
WARN
ERROR

51
Q

How can you control logging output based on severity levels in Logback?

A

You can configure the log level in logback.xml:

<root>
<appender-ref></appender-ref>
</root>

52
Q

What is Test-Driven Development (TDD), and what are its main principles?

A

TDD is a software development approach where tests are written before the actual code. The main principles are:

Write a test
Write just enough code to make the test pass
Refactor the code to improve its structure

53
Q

What is JUnit, and why is it important for Java development?

A

JUnit is a widely-used testing framework for Java that helps developers write repeatable tests. It is important because it enables unit testing, which ensures code correctness and helps detect bugs early in the development process.

54
Q

How do you set up a JUnit testing environment in a Java project?

A

To set up JUnit in a Java project:

Add the JUnit dependency (for example, JUnit 5) to your pom.xml if you’re using Maven:

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>

55
Q

What are the most commonly used annotations in JUnit?

A

@Test: Marks a method as a test method.
@BeforeEach: Executed before each test method in the class.
@AfterEach: Executed after each test method in the class.
@BeforeAll: Executed once before all test methods (must be static).
@AfterAll: Executed once after all test methods (must be static).
@Disabled: Temporarily disables a test method.

56
Q

Can you explain the difference between @Before and @BeforeEach in JUnit 5?

A

@Before: In JUnit 4, this is used to execute code before each test method.
@BeforeEach: In JUnit 5, this replaces @Before and performs the same function of running code before each test method.

56
Q

How do you create a mock object using Mockito?

A

You can create a mock object in Mockito using the mock() method:

MyClass mockObject = Mockito.mock(MyClass.class);

57
Q

How do you use assertions in JUnit tests?

A

Assertions are used to verify expected outcomes in tests. Some commonly used assertions in JUnit 5 include:

Assertions.assertEquals(expected, actual);
Assertions.assertTrue(condition);
Assertions.assertNotNull(object);
Assertions.assertThrows(Exception.class, () -> methodCall());

58
Q

What is Mockito, and what role does it play in unit testing?

A

Mockito is a popular mocking framework for unit tests in Java. It allows you to create mock objects for dependencies, enabling isolated unit tests without requiring actual implementations of external systems like databases or web services.

59
Q

What is a Data Access Object (DAO), and why is it used?

A

A DAO is a design pattern used to abstract and encapsulate access to a data source (such as a database). It is used to separate the business logic from data access logic, promoting clean and maintainable code.

60
Q

How can you use Mockito to mock a DAO in your tests?

A

You can mock a DAO using Mockito.mock() and define the behavior of its methods using when():

MyDAO mockDAO = Mockito.mock(MyDAO.class);
when(mockDAO.getData()).thenReturn(someData);

60
Q

What are the benefits of mocking in unit tests?

A

Isolation: You can test the functionality of a class without depending on its real dependencies.
Faster tests: Mocks prevent interaction with slow external systems like databases.
Flexibility: Mocks allow you to simulate different scenarios, including exceptions and edge cases.