Detailed Answers: Java, JSP, Hibernate, Spring, Maven
& Selenium
Define Stream.
In Java, a Stream is an abstraction over an
ordered sequence of elements supporting sequential and parallel aggregate
operations. In the I/O context, streams represent data flows between sources
and destinations, such as files or network sockets. The java.io package
provides InputStream and OutputStream for byte streams, and Reader and Writer
for character streams, facilitating reading and writing data with buffering and
decoration options.
List three streams for Java I/O.
1. System.in: A standard byte-based
InputStream for reading from console input.
2. System.out: A standard byte-based PrintStream for writing to console output.
3. System.err: A standard byte-based PrintStream for writing error messages to
console, typically unbuffered.
Review a Java program to read/write a text file.
Below is a robust example using
try-with-resources for automatic resource management:
```java
import java.io.*;
public class FileReadWriteExample {
public static void main(String[]
args) {
// Write to file
try (BufferedWriter bw = new
BufferedWriter(new FileWriter("example.txt"))) {
bw.write("This is a
sample text.");
} catch (IOException e) {
e.printStackTrace();
}
// Read from file
try (BufferedReader br = new
BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine())
!= null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Define serialization and deserialization.
Serialization is the process of converting
an object's state into a byte stream for storage or transmission.
Deserialization reconstructs the object from the byte stream, restoring its
original state. Java's java.io.Serializable interface marks classes whose
instances can be serialized, and custom readObject/writeObject methods allow
fine-grained control over the process.
List advantages of generics.
1. Type Safety: Enables compile-time type
checking, reducing runtime ClassCastException.
2. Elimination of Casts: Generic code does not require explicit casting when
retrieving elements.
3. Code Reusability: Write a single generic class or method to handle multiple
types.
4. Improved Readability: Generic signatures document the intended types.
5. Support for Algorithm Generalization: Algorithms can operate on various
types.
Distinguish between ArrayList and Vector.
ArrayList and Vector both implement List
and support dynamic arrays, but key differences include:
• Synchronization: Vector methods are synchronized (thread-safe) by default,
whereas ArrayList is not, leading to better performance in single-threaded
contexts.
• Growth Policy: ArrayList grows by 50% of its size when full, while Vector
doubles its size, potentially causing memory overhead.
• Legacy: Vector is legacy from Java 1.0; ArrayList was introduced in Java 1.2
as part of the Collections Framework.
Difference and similarities between HashSet and TreeSet.
Both HashSet and TreeSet implement the Set
interface and do not allow duplicate elements. HashSet is backed by a HashMap,
offers constant-time performance for basic operations but does not guarantee
order. TreeSet uses a Red-Black tree, provides log(n) time cost for operations,
and maintains elements in sorted (natural or comparator-defined) order. TreeSet
does not permit null if comparator is used, whereas HashSet allows one null
element.
Distinguish between Iterator and Enumeration.
Enumeration and Iterator both traverse
collections, but Iterator offers improved functionality:
• Removal: Iterator supports remove() during iteration; Enumeration does not.
• Fail-Fast: Iterator implementations in the Collections Framework throw
ConcurrentModificationException if the collection is modified; Enumeration is
not fail-fast.
• Method Names: Enumeration uses hasMoreElements() and nextElement(), while
Iterator uses hasNext() and next().
Describe the I/O classes in Java.
Java's I/O is based on streams within the
java.io and java.nio packages.
- Byte Streams: InputStream and OutputStream handle raw bytes.
- Character Streams: Reader and Writer convert bytes to characters using
encoding.
- Buffered Streams: BufferedInputStream/BufferedOutputStream and
BufferedReader/BufferedWriter add buffering for efficiency.
- Data Streams: DataInputStream/DataOutputStream read/write primitive types.
- Object Streams: ObjectInputStream/ObjectOutputStream for serialization.
- NIO Channels and Buffers: java.nio.channels and java.nio.ByteBuffer for
non-blocking I/O and memory-mapped files.
Explain different types of JDBC drivers.
1. Type 1 (JDBC-ODBC Bridge): Translates
JDBC calls to ODBC; platform-dependent and deprecated.
2. Type 2 (Native-API): Uses database vendor library; faster than Type 1 but
platform-specific.
3. Type 3 (Network Protocol): JDBC calls sent to a middleware server that
translates to database protocol; offers database independence.
4. Type 4 (Thin Driver): Pure Java driver communicating directly with the
database using its protocol; high performance and platform-independent.
Demonstrate Generic method and class with example.
Generic Class Example:
```java
public class Box
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
```
Generic Method Example:
```java
public class Util {
public static void print(U
u) {
System.out.println(u);
}
}
```
Illustrate Collection and collection framework.
The Collection Framework is a set of
interfaces and classes to represent groups of objects. Key interfaces:
Collection, List, Set, Queue, Deque, SortedSet, and Map for key-value pairs.
Implementations include ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue,
and HashMap. Framework provides algorithms for searching, sorting, and
synchronization wrappers.
Describe annotations and its types with example.
Annotations provide metadata for code,
processed at compile time or runtime.
Built-in annotations: @Override (compile-time check), @Deprecated (marks
deprecated elements), @SuppressWarnings.
Custom annotation example:
```java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
@MyAnnotation("example")
public class AnnotatedClass {}
```
Explain about lambda expression and its uses.
Lambda expressions are anonymous functions
enabling functional programming in Java. Syntax: (parameters) -> expression
or block. They implement functional interfaces (interfaces with a single
abstract method), streamlining code for event handlers, comparators, and stream
operations. Example: `list.stream().filter(s -> s.length() >
3).collect(Collectors.toList());`
Define Servlet.
A Servlet is a Java class extending
javax.servlet.http.HttpServlet to handle HTTP requests in a web container. It
follows the servlet lifecycle: init(), service(), and destroy(), supports
multithreading, and interacts with request and response objects to generate
dynamic web content.
List the advantages of servlet.
1. Platform Independence: Runs on any
servlet container.
2. Performance: Persistent in memory, faster than CGI.
3. Scalability: Supports multithreading.
4. Robustness: Exception handling and garbage collection.
5. Integration: JDBC, EJB, and other APIs.
Define session and cookies.
Session: Server-side storage of
user-specific data across multiple requests, identified via a session ID.
Cookies: Small key-value pairs stored client-side in the browser, sent with
each HTTP request to maintain state or track preferences.
Outline the advantages of JSP over servlet.
1. Simplified Writing of HTML: Embed Java
code directly in HTML.
2. Rapid Development: Less Java code and more declarative tags.
3. Separation of Concerns: Presentation logic separated from business logic
using MVC.
4. Built-in Objects and Tag Libraries: Facilitates dynamic content.
List the three types of scripting elements in JSP.
1. Scriptlet (<% code %>) – Embed
Java code.
2. Expression (<%= expression %>) – Output the result.
3. Declaration (<%! declarations %>) – Declare variables or methods.
List out the JSP directives.
1. <%@ page %> – Defines
page-dependent attributes (language, buffer).
2. <%@ include %> – Includes static resources.
3. <%@ taglib %> – Declares custom tag libraries.
List out the JSP action tags.
1.
references a JavaBean.
2.
3.
4.
5.
Define JavaBean.
A JavaBean is a reusable software component
following conventions: a public no-argument constructor, private properties
with public getters and setters, and implements java.io.Serializable for
persistence.
Name some JSTL core tags.
c:out, c:if, c:choose, c:forEach, c:set
Name some JSTL function tags.
fn:contains, fn:length, fn:toUpperCase,
fn:substring, fn:replace
Outline the advantages of MVC.
1. Separation of Concerns: Distinct roles
for Model, View, Controller.
2. Maintainability: Easier to update individual components.
3. Testability: Controllers and models can be unit tested.
4. Reusability: Models and views are loosely coupled.
Explain the Servlet Life Cycle and its architecture.
Lifecycle: init() initializes servlet,
service() handles requests, destroy() cleans up. Architecture: Servlet
Container loads servlet, manages request threads, and passes
HttpServletRequest/Response objects to service method.
Illustrate the Session tracking techniques.
1. Cookies: Store session ID client-side.
2. URL Rewriting: Append session ID to URLs.
3. Hidden Form Fields: Embed session ID in forms.
4. HttpSession API: Server-side session storage with getSession().
Explain JSP implicit objects.
Nine built-in objects: request, response,
out, session, application, config, pageContext, page, exception. They provide
easy access to servlet context, HTTP data, and error information.
Explain about JSP directives.
Directives alter JSP page settings:
• page: Language, buffering, error pages.
• include: Static inclusion at translation time.
• taglib: Declares custom tag libraries.
Outline 5 types of JSTL tags.
1. Core Tags (c:forEach, c:if).
2. Formatting Tags (fmt:formatDate).
3. SQL Tags (sql:query).
4. XML Tags (x:parse).
5. Functions (fn:length).
Illustrate MVC architecture with neat diagram.
Refer to attached diagram: Client ->
Controller -> Model <-> Database, then Controller -> View ->
Client.
Outline the advantages of hibernate framework.
1. Simplifies CRUD with ORM.
2. Database independence via HQL.
3. First and second level caching for performance.
4. Transparent lazy loading.
5. Transaction management integration.
Define ORM.
Object-Relational Mapping (ORM) maps
object-oriented classes to relational database tables, abstracting SQL and
improving productivity.
List the supported databases and technologies for
hibernate.
Supports MySQL, Oracle, PostgreSQL, SQL
Server, H2, and integrates with JPA, XML-based, and annotation-based mappings.
List the properties of hibernate.
hibernate.dialect, hibernate.show_sql,
hibernate.hbm2ddl.auto, connection.pool_size, cache.provider_class.
Define HQL.
Hibernate Query Language (HQL) is an
object-oriented query language similar to SQL but works with persistent objects
and their properties.
List out the advantages of HQL.
1. Database independence.
2. Polymorphic queries.
3. Supports joins and fetch strategies.
4. Integrates with the session cache.
Define hibernate caching. List its types.
Caching reduces database load by storing
entity data:
• First-Level Cache: Session-specific.
• Second-Level Cache: SessionFactory-wide.
• Query Cache: Caches result sets of queries.
Interpret HCQL.
Assuming HCQL refers to Hibernate Criteria
Query Language, it uses the Criteria API for type-safe, programmatic query
building without string-based HQL.
Define batch fetching.
Batch fetching retrieves a group of related
entities or collections in a single query to minimize database round trips,
configured via batch-size attribute.
List out cache provider in HQL.
Common providers: Ehcache, Infinispan,
OSCache, JBoss Cache, Hazelcast.
What is JPA?
Java Persistence API (JPA) is the Java EE
standard for ORM, providing EntityManager, annotations, and query capabilities
via JPQL.
Define JPQL.
Java Persistence Query Language (JPQL) is
similar to HQL, operates on entity objects and their fields rather than tables
and columns.
Tabulate the features of JPQL.
Supports SELECT, UPDATE, DELETE on
entities; named queries; support for polymorphism; joins and fetch joins;
aggregate functions.
Illustrate Hibernate architecture with diagram.
Refer to attached diagram: Configuration
-> SessionFactory -> Session -> JDBC -> Database.
Demonstrate multi level cache scheme in hibernate.
Hibernate caching levels: first-level (per
session), second-level (shared), and query cache on top, improving performance
by reducing database hits.
Explain JPA ORM and its framework, mapping types.
JPA framework comprises EntityManager,
Persistence Unit; mapping via annotations (@Entity, @Table, @Id) or XML
descriptors.
Tabulate basic HQL operations and advanced operations.
Basic: SELECT, FROM, WHERE; Advanced: JOIN
FETCH, subqueries, GROUP BY, aggregate functions, CASE expressions.
Define IOC.
Inversion of Control (IoC) is a design
principle where control flow is inverted; a container manages object creation
and dependencies.
List the applications of spring framework.
Spring is used for web applications (Spring
MVC), RESTful services (Spring Boot), batch processing, security (Spring
Security), and integration (Spring Integration).
Illustrate the advantages of Spring framework.
1. Lightweight container.
2. Loosely-coupled via dependency injection.
3. Aspect-Oriented Programming support.
4. Transaction management.
5. Modular architecture.
Define Dependency lookup and its problem.
Dependency Lookup requires code to search
container for dependencies, leading to tight coupling and boilerplate.
Define Dependency Injection.
Dependency Injection is a pattern where the
container injects dependencies into objects, improving testability and
decoupling.
Define Spring Boot.
Spring Boot provides auto-configuration,
embedded servers, and opinionated conventions, accelerating Spring application
development.
What is Autowiring? What are the features in it?
Autowiring lets Spring automatically
resolve and inject collaborating beans. Modes: byName, byType, constructor,
autodetect.
Define AOP. Why use AOP?
Aspect-Oriented Programming separates
cross-cutting concerns (e.g., logging, transactions) into aspects, improving
modularity and reducing code duplication.
Outline the advantages of Spring MVC framework.
1. Clear separation between controller,
model, and view.
2. Flexible view resolution.
3. REST support.
4. Built-in validation and data binding.
Define REST.
Representational State Transfer (REST) is
an architectural style using HTTP methods to operate on resources identified by
URIs.
List the advantages of RESTful webservice.
1. Statelessness.
2. Caching.
3. Uniform interface.
4. Scalability.
5. Layered system.
Illustrate Spring framework architecture.
Refer attached diagram: Core, Beans,
Context, AOP, Data Access, Transaction, MVC modules.
Explain about AOP and its uses.
AOP in Spring uses proxies to apply advice
(before, after, around) at join points, enabling modular cross-cutting
concerns.
Outline Spring MVC architecture.
DispatcherServlet -> HandlerMapping
-> Controller -> Service -> Repository -> Model -> ViewResolver
-> View.
Define Spring Boot.
Already covered above; simplifies Spring
with starters, auto-configuration, and embedded servers.
Difference between Spring framework and Spring Boot.
Spring is a comprehensive framework
requiring configuration; Spring Boot builds on Spring with auto-configuration
and opinionated setup.
What are all the tasks of Maven.
Maven handles project building, dependency
management, documentation generation, reporting, and release management through
lifecycles and plugins.
Distinguish between ANT and Maven.
Ant uses imperative build scripts; Maven
uses declarative POM with conventions and dependency management.
Illustrate briefly about Maven elements and its sub
elements.
POM elements: project, modelVersion,
groupId, artifactId, version, packaging, dependencies, build, repositories.
Define POM.
Project Object Model (POM) is an XML file
defining project configuration, dependencies, and build plugins in Maven.
What is the use of JUnit functional testing?
JUnit automates unit testing of Java code,
allowing assertions and test fixtures to verify functionality and regressions.
Outline the automation testing tools for functional
automation.
Selenium WebDriver, UFT/QTP, TestComplete,
Robot Framework, Katalon Studio.
List the automation testing tools for non functional
automation.
JMeter, LoadRunner, Gatling, Locust,
N|Solid.
What is Selenium WebDriver?
Selenium WebDriver is an API for automating
browser interactions using native browser drivers across multiple languages.
Describe Maven project and its advantages.
Maven standardizes project structure
(src/main/java, src/test/java), automates dependencies, builds, and reports,
enhancing reproducibility.
Explain different types of Maven repository.
1. Local: on developer machine.
2. Central: Maven Central remote repository.
3. Internal: company-hosted.
4. Third-party: external repositories like JBoss or Spring releases.
Explain Maven directory structure.
Standard layout: src/main/java,
src/main/resources, src/test/java, src/test/resources, target directory for
build outputs.
Illustrate Selenium feature and limitations, Tool suite.
Features: supports multiple browsers,
languages, parallel execution, integration with frameworks. Limitations: No
desktop/flash testing, requires coding skills, limited image-based testing.
Suite: IDE, WebDriver, Grid, RC (legacy).