0% found this document useful (0 votes)
3 views10 pages

AJ QB Answers

The document provides an overview of various Java concepts including TreeMap and HashMap classes, Java Generics, lambda expressions, JSP request object, custom tags, and the POJO programming model. It explains the characteristics, advantages, and examples of each concept, highlighting their importance in Java programming. Additionally, it compares different dependency injection methods and discusses the effectiveness of the POJO model.

Uploaded by

jiteshkadam2003
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)
3 views10 pages

AJ QB Answers

The document provides an overview of various Java concepts including TreeMap and HashMap classes, Java Generics, lambda expressions, JSP request object, custom tags, and the POJO programming model. It explains the characteristics, advantages, and examples of each concept, highlighting their importance in Java programming. Additionally, it compares different dependency injection methods and discusses the effectiveness of the POJO model.

Uploaded by

jiteshkadam2003
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/ 10

5 Marks Questions

1. Explain TreeMap and HashMap classes of the collection framework.

• TreeMap:

o Implements the NavigableMap interface.

o Stores key-value pairs in a sorted order based on keys.

o Underlying data structure: Red-Black Tree.

o Not thread-safe.

o Supports methods like subMap(), headMap(), and tailMap().

• HashMap:

o Implements the Map interface.

o Stores key-value pairs in an unordered manner.

o Underlying data structure: Hash Table.

o Allows one null key and multiple null values.

o Not thread-safe.

3. What are Java Generics?

• Java Generics allow type-safe code by enabling classes, interfaces, and methods to operate
on specific types while providing compile-time type checking.

• Key Features:

o Eliminate runtime type casting issues.

o Promote code reusability.

o Example:

List<String> list = new ArrayList<>();

list.add("Hello");

String s = list.get(0); // No casting needed.

5. What are Java lambda expressions? What are the advantages of them?

• Lambda Expressions: Introduced in Java 8, lambdas are used to implement functional


interfaces concisely. Syntax:
(parameters) -> expression.

• Advantages:

o Improve readability and conciseness of code.


o Facilitate functional programming.

o Reduce boilerplate code (e.g., replacing anonymous inner classes).

Example:

Runnable r = () -> System.out.println("Lambda Expression!");

new Thread(r).start();

7. Demonstrate the request implicit object of JSP with an example.

• Explanation:

o The request object in JSP represents the HTTPServletRequest.

o It is used to fetch form data, request parameters, headers, or attributes.

• Example:

<form action="welcome.jsp" method="post">

<input type="text" name="username" />

<input type="submit" />

</form>

In welcome.jsp:

<%

String username = request.getParameter("username");

if (username != null && !username.isEmpty()) {

out.println("Welcome, " + username + "!");

} else {

out.println("Username is missing!");

%>

10. Demonstrate the creation of custom tags with an example for formatting dates.

• Steps:

1. Create a tag handler class:

package customtags;

import java.io.IOException;
import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.SimpleTagSupport;

public class FormatDateTag extends SimpleTagSupport {

private Date date;

private String pattern;

public void setDate(Date date) { this.date = date; }

public void setPattern(String pattern) { this.pattern = pattern; }

@Override

public void doTag() throws JspException, IOException {

SimpleDateFormat formatter = new SimpleDateFormat(pattern);

getJspContext().getOut().print(formatter.format(date));

2. Declare the tag in tld file:


<tag>
<name>formatDate</name>
<tag-class>customtags.FormatDateTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>date</name>
<required>true</required>
</attribute>
<attribute>
<name>pattern</name>
<required>true</required>
</attribute>
</tag>

3. Use it in JSP:
<%@ taglib uri="customtags.tld" prefix="custom" %>
<custom:formatDate date="<%= new Date() %>" pattern="yyyy-MM-dd HH:mm a" />
12. What is the POJO Programming Model?

• POJO: Stands for Plain Old Java Object, representing simple Java classes without any specific
constraints (e.g., no inheritance or annotations).

• Example:

public class Customer {

private int id;

private String name;

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

Advantages:

• Simplifies development.

• Framework-agnostic and lightweight.

• Easily integrates with frameworks like Spring and Hibernate.

7 Marks Questions

2. Compare the TreeMap and HashMap classes of the collection framework.


6. Analyze how lambda expressions improve code readability and efficiency.

• Readability:
Lambdas reduce verbose code by replacing anonymous inner classes.
Example:

// Without lambda

Runnable r1 = new Runnable() {

@Override

public void run() { System.out.println("Hello"); }

};

// With lambda

Runnable r2 = () -> System.out.println("Hello");

Efficiency:

• Lambdas execute faster due to bytecode optimizations.

• Enable functional programming and parallel stream processing.


Example:

Example:

List<String> names = Arrays.asList("Alice", "Bob");

names.forEach(name -> System.out.println(name));


8. Create a JSP page that uses the request implicit object to retrieve form data.

• Problem: Create a JSP page with fields for email and username, and display a personalized
welcome message.

• Solution:

HTML Form (form.jsp):

<form action="welcome.jsp" method="post">

<label>Email:</label>

<input type="email" name="email" required />

<br />

<label>Username:</label>

<input type="text" name="username" required />

<br />

<input type="submit" value="Submit" />

</form>

Processing JSP (welcome.jsp):

<%

String email = request.getParameter("email");

String username = request.getParameter("username");

if (email != null && !email.isEmpty() && username != null && !username.isEmpty()) {

%>

<h1>Welcome, <%= username %>!</h1>

<p>Your registered email is: <%= email %></p>

<%

} else {

%>

<h1>Error: Missing information!</h1>

<%

%>
• Explanation:

o The request.getParameter("name") method fetches data from form fields.

o Conditional checks ensure that fields are not missing or empty.

9. Explain how the request object helps in processing form data.

• request Object: An instance of HttpServletRequest provided implicitly in JSP.

• Key Uses:

1. Retrieve Form Data:

String value = request.getParameter("fieldName");

2. Fetch Header Information:


String userAgent = request.getHeader("User-Agent");

3. Access Query Parameters:


String param = request.getQueryString();

Handling Missing Fields:

• Validate input using isEmpty() or null checks.

• Provide default values for optional fields.


14. Compare Setter Dependency Injection with Constructor Dependency Injection.

8 Marks Questions

4. Analyze how Java Generics help prevent runtime errors.

• Problem with Non-Generics:

List list = new ArrayList();

list.add("Text");

list.add(100); // Compiles, but may cause runtime error later.

String s = (String) list.get(1); // Runtime error!

• Solution Using Generics:


List<String> list = new ArrayList<>();
list.add("Text");
// list.add(100); // Compile-time error
String s = list.get(0); // Safe, no casting required.

Key Benefits:

1. Compile-Time Type Safety: Prevents invalid data types.

2. Improved Code Readability: Removes unnecessary casting.

3. Code Reusability:

public <T> void printList(List<T> list) {

for (T item : list) {

System.out.println(item); } }
11. Create a reusable custom JSP tag <formatDate> to display a date.

• Implementation Steps: See details under 5 Marks Question 10.

• Example Usage in JSP:

<%@ taglib uri="customtags.tld" prefix="custom" %>

<custom:formatDate date="<%= new Date() %>" pattern="yyyy-MM-dd HH:mm a" />

• Output:
2024-11-11 10:15 AM

13. Evaluate the effectiveness of the POJO Programming Model.

• Effectiveness:

1. Lightweight and Framework Agnostic: Simplifies integration with frameworks like


Spring and Hibernate.

2. Encapsulation: Promotes clean code with getters and setters.

3. Testability: POJOs can be unit tested easily without requiring complex setups.

4. Flexibility: No strict requirements (like extending a class or implementing an


interface).

• Example in Spring Framework:

public class Customer {

private int id;

private String name;

// Getters and Setters

In Spring Configuration:

<bean id="customer" class="com.example.Customer">

<property name="id" value="1" />

<property name="name" value="Alice" />

</bean>
15. Evaluate Setter vs Constructor Dependency Injection with a code snippet.

• Constructor Injection:

15. Evaluate Setter vs Constructor Dependency Injection with a code snippet.

• Constructor Injection:

public class Service {

private final Repository repository;

public Service(Repository repository) {

this.repository = repository;

Pros: Dependencies are immutable.

Cons: Hard to inject optional dependencies.

• Setter Injection:
public class Service {
private Repository repository;

public void setRepository(Repository repository) {


this.repository = repository;
}
}

Pros: Allows optional dependencies.


Cons: Can lead to inconsistent state if not all dependencies are set.

You might also like