Java Interview Questions and Concepts
Java Interview Questions and Concepts
[Link]
[Link]
Why Java?
What is Java?
● JDK 1.0 (1996): Initial release with basic features like applets and AWT.
● JDK 1.2 (1998): Introduction of Swing, Collections Framework.
● JDK 5.0 (2004): Added generics, enhanced for loop, and annotations.
● Java SE 8 (2014): Lambda expressions, Stream API, and new date/time API.
● Java SE 11 (2018): Long-Term Support (LTS) version with modularization
(introduced in Java 9).
● Java SE 17 (2021): Latest LTS version with features like sealed classes and pattern
matching.
Syntax Strict and Complex and Simple and Similar to Java with
verbose less strict concise .NET integration
● Compared to C++:
○ No explicit memory management.
○ Supports multithreading natively.
○ Fully object-oriented (no pointers).
● Compared to Python:
○ Better performance (Java is compiled into bytecode, whereas Python is
interpreted).
○ Stronger typing system ensures fewer runtime errors.
● Compared to C#:
○ Cross-platform support from the beginning.
○ Broader application areas, including Android development.
● Mature ecosystem with extensive tools like IntelliJ IDEA and Eclipse.
● Strong support for enterprise-level frameworks (e.g., Spring, Hibernate).
● Proven track record of reliability and scalability.
Reading materials
[Link]
[Link]
[Link]
Module 2: Introduction to Java programming environment
Install jdk
[Link]
html
[Link]
Verify Installation:
java -version
javac -version
Main Class
Main Method
Syntax:
java
public static void main(String[] args) {
// Code to execute
}
Explanation of Components:
3. [Link]
Variations:
Code:
5. Naming Conventions
Classes
Methods
Variables
● Use camelCase.
● Example: studentName, totalMarks.
Constants
Packages
6. Features of Java
Java offers several key features that make it powerful and versatile:
1. Platform Independence
2. Object-Oriented
● Everything in Java revolves around objects and classes (except for primitive data
types).
3. Simple
4. Secure
5. Multithreaded
6. Robust
● Strong error handling and garbage collection prevent crashes and memory leaks.
7. High Performance
8. Distributed
● Java provides tools like RMI and CORBA for distributed computing.
Daily Task
1. Installation Task:
○ Install Java on their system, set up the PATH, and verify using java
-version.
2. Coding Task 1:
○ Write and run a simple Java program that prints their name, favorite color, and
a fun fact about Java.
3. Coding Task 2:
Comments
4. /*
5. This is a multi-line comment
6. spanning multiple lines
7. */
9. /**
10. * This is a documentation comment
11. */
Statements
int a;
if (a > 0) {
[Link]("Positive number");
}
Identifiers
· int age;
· String $name;
· double _salary;
Keywords
Literals
Variables
● Type Casting:
1. Implicit Casting: Smaller type to larger type (automatic).
5. double d = 10.5;
6. int num = (int) d; // Explicit casting
● Default Values:
○ For primitive types: int = 0, boolean = false, char = \u0000.
○ For reference types: null.
Operators
● Definition: Control structures are used to alter the flow of program execution based
on conditions or loops.
● Purpose: To enable decision-making (conditional execution) and repetition (loops),
allowing the program to handle various scenarios efficiently.
1. if Statement
■ Syntax:
java
if (condition) {
// Code to execute if condition is true
}
java
int x = 10;
if (x > 5) {
[Link]("x is greater than 5");
}
2. if-else Statement
■ Syntax:
java
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
java
int x = 4;
if (x > 5) {
[Link]("x is greater than 5");
} else {
[Link]("x is less than or equal to 5");
}
■ Syntax:
java
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if no conditions are true
}
■ Explanation: Allows you to test multiple conditions and execute the first
block where the condition is true.
■ Example:
java
int x = 10;
if (x > 20) {
[Link]("x is greater than 20");
} else if (x == 10) {
[Link]("x is equal to 10");
} else {
[Link]("x is less than 10");
}
4. switch-case Statement
■ Syntax:
java
switch (variable) {
case value1:
// Code to execute if variable == value1
break;
case value2:
// Code to execute if variable == value2
break;
default:
// Code to execute if no case matches
break;
}
java
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
break;
}
1. for Loop
■ Syntax:
java
java
2. while Loop
■ Syntax:
java
while (condition) {
// Code to execute as long as condition is true
}
java
int i = 0;
while (i < 5) {
[Link]("i is: " + i);
i++;
}
3. do-while Loop
■ Syntax:
java
do {
// Code to execute
} while (condition);
■ Explanation: Executes the code block at least once and then checks
the condition. The loop continues as long as the condition is true.
■ Example:
java
int i = 0;
do {
[Link]("i is: " + i);
i++;
} while (i < 5);
5. Program/Interview Questions
Objective: Write a Java program that takes an integer temperature as input and classifies it
into one of the following categories based on the value:
Objective: Write a Java program that generates and prints the multiplication table of a
number entered by the user.
Requirements:
1. Prompt the user to enter an integer number for which they want to generate the
multiplication table.
2. Use a for loop to print the multiplication table from 1 to 10.
3. Format the output such that each line shows the result of multiplying the number by a
value from 1 to 10.
4. (Bonus) Allow the user to enter a new number for generating a different multiplication
table without restarting the program.
Example Output:
Input:
Enter a number: 5
Output:
css
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
● Definition: Java provides ways to take input from the user via the keyboard.
● Purpose: User input is essential for dynamic programs that require data at runtime.
Java provides different classes for capturing input from the user:
3. Scanner Class
· Overview: Scanner is a built-in class in Java used to get user input. It provides
methods for reading different data types, such as nextInt(), nextLine(),
nextDouble(), etc.
· Example:
java
import [Link];
· Common Methods:
4. BufferedReader Class
· Example:
java
import [Link].*;
· Key Methods:
5. Problem Solving
● Focus: Practice solving problems using user input in Java. Problems can range from
simple arithmetic to complex algorithms requiring data from the user.
● Important Concept: Always validate inputs (e.g., ensure the input is of the correct
type) to avoid errors during execution.
6. Java Array
● What is an Array?
○ An Array is a data structure in Java that stores a fixed-size sequence of
elements of the same type.
○ Purpose: To store multiple values in a single variable instead of declaring
individual variables for each value.
· Java:
java
○ Alternatively:
java
· C/C++:
· Key Differences:
○ Java: Arrays are objects, so they must be created using the new keyword or
initialized directly with values.
○ C/C++: Arrays are not objects, and memory is allocated statically (or
dynamically with pointers).
8. Instantiation of an Array
· Example:
java
java
· String:
java
· Character Array:
java
· Differences:
java
java
java
· Length of an Array:
java
○ Occurs when you try to access an array index that is outside the valid range
(0 to length-1).
○ Example:
java
○ Arrays in Java have a fixed size. You cannot directly increase or decrease the
size of an array after it’s created.
○ Workaround:
■ Use an ArrayList if you need dynamic resizing.
■ If you need to resize an array, create a new array with the desired size
and elements.
■ Example:
java
· ing an Array:
java
○ Syntax:
java
○ Example:
java
○ Example:
java
Daily task
Task Instructions
1. Class
java
class ClassName {
// Fields/Properties
int age;
String name;
// Methods/Behaviors
void greet() {
[Link]("Hello, " + name);
}
}
● Example:
java
class Person {
String name;
int age;
void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
}
}
2. Objects
java
● Objects in Memory: When an object is created, memory is allocated for its instance
variables (attributes) and methods.
3. Inheritance
· Key Concepts:
· Syntax:
java
class Parent {
void greet() {
[Link]("Hello from Parent!");
}
}
· Advantages of Inheritance:
○ Code Reusability.
○ Hierarchical classification of classes.
○ Enables polymorphism.
4. Abstraction
· Abstract Class:
○ An abstract class cannot be instantiated directly and can have both abstract
(without implementation) and non-abstract (with implementation) methods.
○ Syntax:
java
· Interfaces: An interface is a contract that a class must adhere to. It only contains
method signatures and constants (no implementation). A class that implements
an interface must provide concrete implementations for all methods.
○ Syntax:
java
interface Animal {
void sound(); // Interface method
}
5. Encapsulation
java
class Person {
private String name; // private variable
// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String name) {
[Link] = name;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
[Link]("John");
[Link]([Link]()); // Output: John
}
}
6. Polymorphism
· Definition: Polymorphism is the ability of one object to take many forms. In Java,
it can be achieved through method overloading (compile-time polymorphism) and
method overriding (runtime polymorphism).
■ When multiple methods with the same name exist, but with different
parameters (number or type).
■ Example:
java
class Calculator {
int add(int a, int b) {
return a + b;
}
java
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
7. Constructors
java
class Person {
String name;
int age;
// Default constructor
public Person() {
name = "Unknown";
age = 0;
}
}
class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
· this Keyword:
java
class Person {
String name;
· super Keyword:
java
class Animal {
void sound() {
[Link]("Animal sound");
}
}
Daily task
Functionalities:
OOP Principles:
Testing:
● Definition: Command-line arguments are inputs that are passed to a Java program at
the time of execution, allowing the user to provide input without modifying the code.
● Purpose: They are useful for passing configuration parameters, file names, or user
inputs without requiring interaction during runtime.
● How They Work:
○ Command-line arguments are passed to the main() method of a Java class.
○ They are stored as an array of strings (String[] args).
○ Example: Running a Java program with arguments from the command line
might look like this:
· Syntax:
○ In Java, the main method accepts a parameter String[] args, which stores
the arguments.
○ Example:
java
· Explanation:
It will output:
yaml
Arguments passed:
Hello
World
123
○ Accessing Arguments: You can access the arguments by their index in the args
array:
java
· Important Notes:
· Definition: An inner class is a class defined within another class. It has access to
the members (including private members) of the outer class.
· Purpose: Inner classes are used to logically group classes that are only used in
one place, increase readability, and allow access to the outer class’s members.
· Syntax:
java
class OuterClass {
int outerVariable = 10;
// Inner class
class InnerClass {
void display() {
[Link]("Outer variable: " + outerVariable);
}
}
}
· Explanation:
○ An inner class can directly access the variables and methods of its outer
class, even if they are private.
○ Example:
java
class Outer {
private String message = "Hello from Outer Class";
class Inner {
void showMessage() {
// Accessing outer class's private member
[Link](message);
}
}
}
○ An inner class can access all members of the outer class, including private
fields and methods, directly without needing special access methods.
3. Types of Inner Class
○ Defined inside the outer class and associated with an instance of the outer
class.
○ Can access all members of the outer class.
○ Example:
java
class Outer {
private String outerMessage = "Message from Outer class";
class Inner {
void displayMessage() {
[Link](outerMessage); // Access outer class member
}
}
}
○ A static class inside another class, not tied to an instance of the outer class.
○ It can only access the static members of the outer class.
○ Example:
java
class Outer {
static String outerMessage = "Message from Outer class";
java
class Outer {
void display() {
class LocalInner {
void show() {
[Link]("Inside Local Inner Class");
}
}
LocalInner inner = new LocalInner();
[Link](); // Output: Inside Local Inner Class
}
}
java
interface Greeting {
void sayHello();
}
Module 14: Using Predefined Package & Other Classes (Duration: 2 hrs)
1. [Link] Hierarchy
Object Class:
1. toString():
java
class Person {
String name;
int age;
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
2. equals():
java
class Person {
String name;
int age;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Person person = (Person) obj;
return age == [Link] && [Link]([Link]);
}
}
3. hashCode():
○ Returns a hash code for the object. It should be consistent with equals().
○ Example:
java
@Override
public int hashCode() {
return [Link](name, age);
}
4. clone():
java
class Person implements Cloneable {
String name;
int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return [Link]();
}
}
5. finalize():
java
@Override
protected void finalize() throws Throwable {
[Link]("Object is being garbage collected");
[Link]();
}
3. Using Runtime Class, Process Class to Play Music, Video from Java
Program
Runtime Class:
import [Link];
java
5. Math Class
Example:
java
String Class:
Example:
java
8. Wrapper Classes
● Wrapper classes provide methods to convert between primitive types and their
corresponding objects.
● Example:
java
Example:
java
Example:
java
2. Static Import
● Allows direct access to static members of a class without using the class name.
Example:
java
import static [Link].*; // Import all static methods from Math class
3. Instance of Operator
Example:
java
Example:
java
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
● JAR files are compressed files used to package Java classes and other resources.
● Creating JAR: jar cf [Link] *.class
● Extracting JAR: jar xf [Link]
● Automatic memory management process where the Java Virtual Machine (JVM)
removes unused objects from memory to free up space.
4. Java API
1. Introduction to Exceptions
2. Effects of Exceptions
8. Chained Exception
1. Generics (Templates)
● Definition: Generics provide a way to define classes, interfaces, and methods with
type parameters, enabling the use of different types while ensuring type safety at
compile-time.
● Purpose: Avoids the need for casting and enables code reusability.
Example:
java
// Generic class
class Box<T> {
private T value;
public T getValue() {
return value;
}
}
2. What is a Generic?
● Generic Type: A placeholder for a data type to be defined later. This allows classes
or methods to operate on objects of different types while providing compile-time type
safety.
● Advantages of Generics:
○ Type safety: Reduces runtime errors due to class type mismatches.
○ Code reusability: Same code can be applied to different types.
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
}
5. Collection
● Collection Interface: The root interface in the collection framework. It defines basic
methods for adding, removing, and manipulating elements.
● Types of Collections:
○ List: Ordered collection (e.g., ArrayList, LinkedList).
○ Set: Unordered collection with no duplicates (e.g., HashSet, TreeSet).
○ Queue: Collection that represents a queue (e.g., PriorityQueue).
○ Map: Collection of key-value pairs (e.g., HashMap, TreeMap).
Example:
java
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
○
● Vector: Similar to ArrayList, but synchronized.
● Stack: A last-in-first-out (LIFO) collection. Inherits from Vector.
Example:
java
Stack<Integer> stack = new Stack<>();
[Link](1);
[Link](2);
[Link](); // Removes 2
○
● LinkedList: A doubly linked list implementation of the List and Deque interfaces.
Example:
java
LinkedList<String> list = new LinkedList<>();
[Link]("A");
[Link]("B");
○
9. Using Collections Class for Sorting
The Collections class provides static methods for manipulating collections (e.g., sorting,
reversing, etc.).
Example:
java
List<Integer> numbers = [Link](4, 2, 8, 5);
[Link](numbers); // Sorts in ascending order
[Link](numbers); // Output: [2, 4, 5, 8]
●
● HashMap: Stores key-value pairs and allows fast lookups. Keys are unique, but
values can be duplicated.
Example:
java
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "One");
[Link](2, "Two");
○
● Hashtable: Synchronized version of HashMap. Generally slower than HashMap.
● TreeMap: A Map that orders keys based on their natural ordering or a custom
comparator.
● LinkedHashMap: Maintains the insertion order of keys.
● SortedMap: A map that guarantees the keys are sorted.
● Iterator: Provides methods for iterating over collections (e.g., hasNext(), next(),
remove()).
Example:
java
Iterator<String> iter = [Link]();
while ([Link]()) {
[Link]([Link]());
}
○
● Enumerator: Older interface for traversing collections (now replaced by Iterator).
● HashSet: A collection that does not allow duplicate elements and does not guarantee
any specific order.
● TreeSet: A Set that orders elements according to their natural ordering or a
comparator.
● LinkedHashSet: A Set that maintains the insertion order.
Example:
java
Random rand = new Random();
int randomNum = [Link](100); // Generates a random number
between 0 and 99
○
○
● You can create your own data structure by using user-defined classes that implement
the appropriate interfaces, such as List, Set, or Map.
Example:
java
Date date = new Date();
[Link](date);
○
● SimpleDateFormat: Used to format and parse dates.
Example:
java
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = [Link]("21/01/2025");
○
1. Java 8 Features
● Lambda Expressions: Provide a clear and concise way to express instances of
single-method interfaces (functional interfaces).
Example:
java
List<String> list = [Link]("apple", "banana", "cherry");
[Link](s -> [Link](s)); // Lambda expression
○
● Streams API: Allows functional-style operations on streams of data (filter, map,
reduce, etc.).
● Default Methods in Interfaces: Interfaces can now have default methods with a
body.
● Functional Interfaces: Interfaces with a single abstract method (e.g., Runnable,
Callable).
2. Java 9 Features
● Module System: Introduced the module system for better code encapsulation and
dependency management.
● JShell: A command-line REPL (Read-Eval-Print Loop) for interactive testing and
exploration of Java code.
3. Java 10 Features
● Local Variable Type Inference: The var keyword allows local variables to be
declared without explicitly specifying their type.
Example:
java
var list = new ArrayList<String>();
○
● Improved Container Awareness: Java 10 introduced more JVM optimizations for
containers (e.g., Docker).
Advanced Java Concepts: JDBC and Servlets
1. Introduction to JDBC
● JDBC is an API that allows Java programs to connect and interact with relational
databases (like MySQL, PostgreSQL, Oracle, etc.).
● It provides a standard interface for database operations like querying, updating, and
managing data.
2. JDBC Architecture
3. JDBC Components
Example:
java
[Link]("[Link]");
○
2. Establish a Database Connection:
Example:
java
Connection con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"username", "password");
○
3. Create a Statement Object:
Example:
java
Statement stmt = [Link]();
○
4. Execute a Query:
Example:
java
ResultSet rs = [Link]("SELECT * FROM users");
○
5. Process the Result:
Example:
java
while ([Link]()) {
[Link]([Link]("name"));
}
○
6. Close Connections:
○
5. JDBC Example
java
import [Link].*;
try {
// Load the driver
[Link]("[Link]");
// Establish connection
con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
// Create statement
stmt = [Link]();
// Execute query
rs = [Link]("SELECT id, name FROM users");
// Process results
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ",
Name: " + [Link]("name"));
}
} catch (SQLException | ClassNotFoundException e) {
[Link]();
} finally {
try {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}
Servlets
1. What is a Servlet?
● A Servlet is a Java class that runs on a web server or application server and
responds to requests from a web client (such as a browser).
● Servlets are a fundamental component of Java web applications, serving as the
"controller" part of the Model-View-Controller (MVC) architecture.
● 1. Loading and Instantiation: When a request is made to a servlet, the server loads
and instantiates the servlet class.
● 2. Initialization (init method): The server calls the init() method to initialize the
servlet.
● 3. Request Handling (service method): The service() method processes
incoming requests.
● 4. Destruction (destroy method): The destroy() method is called when the
servlet is removed from memory.
● A simple Servlet:
java
import [Link].*;
import [Link].*;
import [Link].*;
// Write response
[Link]("<html><body>");
[Link]("<h1>Hello, Servlet!</h1>");
[Link]("</body></html>");
}
// Destruction method
public void destroy() {
// Cleanup code
}
}
1. Create the Servlet: Write the servlet class and define the doGet or doPost method.
2.
3. Compile and Package: Compile the servlet and package it in a .war file.
4. Deploy on a Web Server: Deploy the .war file to a servlet container (e.g., Apache
Tomcat).
5. Access the Servlet: Open a web browser and visit
[Link]
java
public class LoginServlet extends HttpServlet {
// Handling GET request
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Process GET request
}
6. Servlet vs JSP
7. Servlet Security
● Use HTTPS to secure the communication between the client and the server.
● Implement user authentication (e.g., using cookies or session management).
8. Session Management
● Session: A mechanism to maintain state (like user login) across multiple HTTP
requests.
● HttpSession Interface: Used to track user sessions.
Example:
java
// Creating a session
HttpSession session = [Link]();
[Link]("username", "admin");
● Definition: The Singleton pattern ensures that a class has only one instance and
provides a global point of access to that instance.
● Use Cases: Useful when exactly one object is needed to coordinate actions across
the system, e.g., a configuration manager or logging system.
Example:
java
● Definition: DAO is used to abstract and encapsulate all interactions with a data
source, providing an interface for the persistence layer.
● Use Cases: It allows for separation between business logic and data access logic.
Example:
java
@Override
public User getUserById(int id) {
// Code to fetch user from database
return new User();
}
}
● Definition: DTO is a simple object that is used to transfer data between layers, such
as from the data access layer to the presentation layer.
● Use Cases: When you want to pass data without exposing business logic or complex
operations.
Example:
java
Example:
● Definition: The Front Controller pattern provides a centralized entry point for
handling requests, often used in web applications.
● Use Cases: It simplifies request routing and handling in large applications.
● Definition: The Factory Method pattern provides an interface for creating objects, but
allows subclasses to alter the type of objects that will be created.
● Use Cases: When the creation of an object involves complex logic or needs to vary.
Example:
java
● Definition: The Abstract Factory pattern provides an interface for creating families of
related or dependent objects without specifying their concrete classes.
● Use Cases: Useful when you have multiple families of products or objects that need
to be created in a consistent manner.
Example:
java
// Abstract Factory
public interface AnimalFactory {
Animal createAnimal();
}
// Concrete Factory
public class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
}
Example:
java
import [Link].*;
@Before
public void setUp() {
calculator = new Calculator();
}
@Test
public void testAddition() {
[Link](5, [Link](2, 3));
}
@After
public void tearDown() {
// Clean up resources if needed
}
}
3. Assert Class
● The Assert class in JUnit provides static methods to assert the results of test cases.
○ assertEquals(expected, actual): Asserts that two values are equal.
○ assertTrue(condition): Asserts that a condition is true.
○ assertFalse(condition): Asserts that a condition is false.
○ assertNull(object): Asserts that an object is null.
○ assertNotNull(object): Asserts that an object is not null.
4. Test Cases
● A test case is a method annotated with @Test that verifies the behavior of a single
unit of code (e.g., a method in a class).
● A test suite is a collection of test cases grouped together to run as a batch.
1. What is Maven?
● Maven is a build automation tool used primarily for Java projects. It helps in
managing project dependencies, building projects, and deploying applications.
● Purpose: It simplifies the process of building and managing projects by using a
central repository for dependencies and providing standard project structures.
2. Maven Basics
● [Link]: The configuration file for a Maven project. It contains information about the
project, its dependencies, build plugins, and more.
Example of [Link]:
xml
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
● Phases: Represent stages in the build lifecycle (e.g., compile, test, package).
● Goals: Specific tasks associated with a phase (e.g., mvn clean executes the clean
goal).
●
1. Translation Phase 📝
● The JSP file is translated into a Servlet by the JSP engine.
● The .jsp file is converted into a Java .java file (a servlet class).
2. Compilation Phase 🔧
● The generated Java file (servlet) is compiled into a .class file (bytecode).
5. Destroy Phase 🛑
● When the JSP is no longer needed, jspDestroy() is called to clean up resources.
● The scriptlet tag is used to write Java code inside a JSP file.
● Code written inside the scriptlet tag is placed inside the _jspService() method of
the servlet that the JSP is translated into.
● You can use it for looping, conditionals, and calling methods.
Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
int a = 10;
int b = 20;
int sum = a + b;
[Link]("Sum: " + sum); // Outputting to response
%>
</body>
</html>
● The expression tag is used to output values directly into the response.
● It is a shortcut for [Link](), meaning whatever is inside <%= ... %> is
evaluated and written to the response.
Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<h2>Sum: <%= 10 + 20 %></h2> <!-- Prints Sum: 30 -->
<h2>Current Time: <%= new [Link]() %></h2> <!-- Prints
current date -->
</body>
</html>
● The declaration tag is used to declare methods and variables that are placed
outside the _jspService() method, making them part of the generated servlet
class.
● It is mainly used for defining class-level variables and methods.
Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%!
int square(int num) {
return num * num;
}
%>
<h2>Square of 5: <%= square(5) %></h2> <!-- Calls declared
method -->
</body>
</html>
Summary
Tag Purpose Scope