0% found this document useful (0 votes)
25 views34 pages

Lab Manual of FSJP SE

The document outlines a series of Java programming experiments focusing on concepts such as classes, objects, inheritance, exception handling, and method overloading. Each experiment includes a problem statement, theoretical background, integrated Java program, execution flow, sample output, and viva questions. The experiments cover practical applications like a Bank Account Management System, a Calculator, a University Management System, and a Student Result Management System.
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)
25 views34 pages

Lab Manual of FSJP SE

The document outlines a series of Java programming experiments focusing on concepts such as classes, objects, inheritance, exception handling, and method overloading. Each experiment includes a problem statement, theoretical background, integrated Java program, execution flow, sample output, and viva questions. The experiments cover practical applications like a Bank Account Management System, a Calculator, a University Management System, and a Student Result Management System.
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

Lab Manual – Full Stack Java Programming

Experiment No.1: Demonstrating Classes and Objects in Java


Problem Statement

Design a Bank Account Management System in Java:

 Create a BankAccount class with attributes like accountNumber, accountHolder, and


balance.
 Implement methods for deposit(), withdraw(), and displayAccountDetails().
 Create multiple objects to simulate different bank accounts and perform operations on
them.

This program demonstrates:

1. Class definition
2. Creating objects
3. Calling methods on objects
4. Encapsulation of data

Theory

 Class: A blueprint for objects that defines attributes (fields) and behaviors (methods).
 Object: An instance of a class.
 Encapsulation: Data is hidden inside the class and accessed via methods.
 Constructor: Special method to initialize object data when it is created.

Program (Single Integrated Java Program)


// Bank Account Management System
import [Link];
class BankAccount {
// Attributes (fields)
private int accountNumber;
private String accountHolder;
private double balance;
// Constructor
public BankAccount(int accountNumber, String accountHolder, double
balance) {
[Link] = accountNumber;
[Link] = accountHolder;
[Link] = balance;
}
// Method to deposit amount
public void deposit(double amount) {
balance += amount;
[Link]("Deposited: " + amount + ", New Balance: " +
balance);
}
// Method to withdraw amount
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount + ", New Balance: " +
balance);
} else {
[Link]("Insufficient balance!");
}
}
// Method to display account details
public void displayAccountDetails() {
[Link]("\nAccount Number: " + accountNumber);
[Link]("Account Holder: " + accountHolder);
[Link]("Balance: " + balance);
}
}
public class BankApp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Create two bank account objects
BankAccount acc1 = new BankAccount(101, "Rahul", 5000);
BankAccount acc2 = new BankAccount(102, "Priya", 10000);
// Display initial details
[Link]();
[Link]();
// Perform operations on account 1
[Link]("\n--- Transactions for Rahul ---");
[Link](2000);
[Link](1500);
// Perform operations on account 2
[Link]("\n--- Transactions for Priya ---");
[Link](5000);
[Link](20000); // Attempt to withdraw more than balance
// Display final details
[Link]("\n--- Final Account Details ---");
[Link]();
[Link]();
[Link]();
}
}
Execution Flow

1. Program creates two bank account objects: acc1 and acc2.


2. Displays initial account details.
3. Performs deposit and withdrawal operations on both accounts.
4. Displays final account details after transactions.

Sample Output
Account Number: 101
Account Holder: Rahul
Balance: 5000.0

Account Number: 102


Account Holder: Priya
Balance: 10000.0

--- Transactions for Rahul ---


Deposited: 2000.0, New Balance: 7000.0
Withdrawn: 1500.0, New Balance: 5500.0

--- Transactions for Priya ---


Deposited: 5000.0, New Balance: 15000.0
Insufficient balance!

--- Final Account Details ---


Account Number: 101
Account Holder: Rahul
Balance: 5500.0

Account Number: 102


Account Holder: Priya
Balance: 15000.0

Viva Questions

1. What is the difference between a class and an object?


2. What is the purpose of a constructor in Java?
3. Explain encapsulation and its benefits.
4. Can you create multiple objects of a class? Give an example.
5. How can you access private fields of a class outside the class?
Experiment No.2.: Demonstrating Method and Constructor
Overloading
Problem Statement

Create a Calculator Program in Java that demonstrates:

1. Constructor Overloading – Multiple constructors to initialize objects with different


initial values.
2. Method Overloading – Multiple methods with the same name but different parameters
to perform various arithmetic operations (addition, multiplication, subtraction).

The program should:

 Allow creation of calculator objects with different initial values.


 Perform arithmetic operations using overloaded methods.

Theory

 Constructor Overloading:
Multiple constructors with different parameter lists in the same class.
Allows objects to be initialized in different ways.
 Method Overloading:
Multiple methods with the same name but different parameters (number/type).
Improves code readability and reusability.
 Rules:
1. Must have different number or type of parameters.
2. Return type alone cannot distinguish overloaded methods.

Program (Single Integrated Java Program)


// Calculator Program demonstrating method and constructor overloading
class Calculator {
private double num1;
private double num2;
// Constructor Overloading
public Calculator() {
num1 = 0;
num2 = 0;
}
public Calculator(double n1, double n2) {
num1 = n1;
num2 = n2;
}
public Calculator(double n) {
num1 = n;
num2 = n;
}
// Method Overloading for addition
public double add(double a, double b) {
return a + b;
}
public double add(double a, double b, double c) {
return a + b + c;
}
// Method Overloading for multiplication
public double multiply(double a, double b) {
return a * b;
}
public double multiply(double a, double b, double c) {
return a * b * c;
}
// Method Overloading for subtraction
public double subtract(double a, double b) {
return a - b;
}
public double subtract(double a, double b, double c) {
return a - b - c;
}
public void displayValues() {
[Link]("Value 1: " + num1 + ", Value 2: " + num2);
}
}
public class CalculatorApp {
public static void main(String[] args) {
// Using different constructors
Calculator calc1 = new Calculator();
Calculator calc2 = new Calculator(10, 20);
Calculator calc3 = new Calculator(5);
[Link]("--- Calculator 1 ---");
[Link]();
[Link]("Addition (2 numbers): " + [Link](5, 10));
[Link]("Addition (3 numbers): " + [Link](5, 10, 15));
[Link]("\n--- Calculator 2 ---");
[Link]();
[Link]("Multiplication (2 numbers): " + [Link](2,
3));
[Link]("Multiplication (3 numbers): " + [Link](2,
3, 4));
[Link]("\n--- Calculator 3 ---");
[Link]();
[Link]("Subtraction (2 numbers): " + [Link](20,
5));
[Link]("Subtraction (3 numbers): " + [Link](20,
5, 3));
}
}
Execution Flow

1. Program creates three calculator objects using different constructors.


2. Demonstrates method overloading for addition, multiplication, and subtraction.
3. Displays results and values stored in each object.

Sample Output
--- Calculator 1 ---
Value 1: 0.0, Value 2: 0.0
Addition (2 numbers): 15.0
Addition (3 numbers): 30.0

--- Calculator 2 ---


Value 1: 10.0, Value 2: 20.0
Multiplication (2 numbers): 6.0
Multiplication (3 numbers): 24.0

--- Calculator 3 ---


Value 1: 5.0, Value 2: 5.0
Subtraction (2 numbers): 15.0
Subtraction (3 numbers): 12.0

Viva Questions

1. What is constructor overloading and why is it used?


2. How does method overloading improve code readability?
3. Can you overload a method based on return type only?
4. Give an example of method overloading in real-life applications.
5. Explain the difference between constructor overloading and method overloading.
Experiment No 3: Comprehensive Inheritance in Java
Problem Statement

Design a University Management System in Java that demonstrates different types of


inheritance:

1. Single Inheritance – A Student inherits from Person.


2. Multilevel Inheritance – A ResearchStudent inherits from Student, which inherits
from Person.
3. Hierarchical Inheritance – Both Teacher and Student inherit from Person.
4. Hybrid Inheritance – Use interfaces to add extra features like Sports or Scholarship
to classes, since Java does not support multiple inheritance with classes.

Theory

 Inheritance allows a class (child) to acquire properties and methods of another class
(parent).
 Types of Inheritance in Java:
1. Single – One parent, one child.
2. Multilevel – Parent → Child → Grandchild.
3. Hierarchical – One parent, multiple children.
4. Hybrid – Combination of two or more types (achieved with interfaces in Java).

Program

// Comprehensive Inheritance Example: University Management System

// Hybrid Inheritance using Interface

interface Sports {

void play();

// Base Class

class Person {

String name;

int age;

Person(String name, int age) {

[Link] = name;

[Link] = age;
}

void displayInfo() {

[Link]("Name: " + name + ", Age: " + age);

// Single Inheritance: Student extends Person

class Student extends Person {

int rollNo;

Student(String name, int age, int rollNo) {

super(name, age);

[Link] = rollNo;

void showStudent() {

displayInfo();

[Link]("Roll No: " + rollNo);

// Multilevel Inheritance: ResearchStudent extends Student

class ResearchStudent extends Student {

String researchTopic;

ResearchStudent(String name, int age, int rollNo, String topic) {

super(name, age, rollNo);

[Link] = topic;

}
void showResearchDetails() {

showStudent();

[Link]("Research Topic: " + researchTopic);

// Hierarchical Inheritance: Teacher also extends Person

class Teacher extends Person {

String subject;

Teacher(String name, int age, String subject) {

super(name, age);

[Link] = subject;

void showTeacher() {

displayInfo();

[Link]("Subject: " + subject);

// Hybrid Inheritance: Student + Sports Interface

class SportsStudent extends Student implements Sports {

String sport;

SportsStudent(String name, int age, int rollNo, String sport) {

super(name, age, rollNo);

[Link] = sport;

}
public void play() {

[Link](name + " plays " + sport);

public class InheritanceLab {

public static void main(String[] args) {

[Link]("=== Single Inheritance ===");

Student s1 = new Student("Rahul", 20, 101);

[Link]();

[Link]("\n=== Multilevel Inheritance ===");

ResearchStudent rs = new ResearchStudent("Priya", 24, 201, "Artificial Intelligence");

[Link]();

[Link]("\n=== Hierarchical Inheritance ===");

Teacher t1 = new Teacher("Dr. Sharma", 45, "Data Science");

[Link]();

[Link]("\n=== Hybrid Inheritance (with Interface) ===");

SportsStudent ss = new SportsStudent("Arjun", 21, 301, "Cricket");

[Link]();

[Link]();

}
Output
=== Single Inheritance ===
Name: Rahul, Age: 20
Roll No: 101

=== Multilevel Inheritance ===


Name: Priya, Age: 24
Roll No: 201
Research Topic: Artificial Intelligence

=== Hierarchical Inheritance ===


Name: Dr. Sharma, Age: 45
Subject: Data Science

=== Hybrid Inheritance (with Interface) ===


Name: Arjun, Age: 21
Roll No: 301
Arjun plays Cricket

Viva Questions

1. What is inheritance in Java?


2. Why does Java not support multiple inheritance with classes?
3. How is hybrid inheritance implemented in Java?
4. Difference between extends and implements keywords.
5. Give real-world examples of multilevel and hierarchical inheritance.
Experiment No 4: Comprehensive Exception Handling
Problem Statement

Write a Java program to simulate a Student Result Management System that:

 Takes student details and marks as input.


 Handles invalid inputs (negative marks / marks > 100) using user-defined exceptions.
 Handles division by zero error when calculating average marks.
 Demonstrates multiple catch blocks.
 Uses a finally block to display a completion message.
 Uses throw and throws keywords where applicable.

Theory

 Exception: Runtime error that disturbs normal program flow.


 Types: Checked & Unchecked.
 Handling mechanisms:
o try–catch → handles exceptions.
o finally → block always executes.
o throw → explicitly throws an exception.
o throws → declares exceptions in method signature.
o User-defined exception → custom class extending Exception.

Program

import [Link];

// User-defined Exception

class InvalidMarksException extends Exception {

public InvalidMarksException(String message) {

super(message);

public class ExceptionHandlingLab {

// Method to validate marks


static void validateMarks(int marks) throws InvalidMarksException {

if (marks < 0 || marks > 100) {

throw new InvalidMarksException("Marks should be between 0 and 100.");

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

try {

// Input student details

[Link]("Enter Student Name: ");

String name = [Link]();

[Link]("Enter number of subjects: ");

int n = [Link]();

int marks[] = new int[n];

int sum = 0;

// Input marks

for (int i = 0; i < n; i++) {

[Link]("Enter marks for subject " + (i + 1) + ": ");

marks[i] = [Link]();

validateMarks(marks[i]); // may throw exception

sum += marks[i];

// Average calculation

int avg = sum / n; // risk: division by zero


[Link]("\nStudent Name: " + name);

[Link]("Total Marks: " + sum);

[Link]("Average Marks: " + avg);

} catch (InvalidMarksException e) {

[Link]("Custom Exception: " + [Link]());

} catch (ArithmeticException e) {

[Link]("Error: Cannot divide by zero (no subjects entered).");

} catch (Exception e) {

[Link]("General Exception: " + e);

} finally {

[Link]("\n--- Program Execution Completed ---");

[Link]();

}
Input/Output

Case 1: Valid Input

Enter Student Name: Rahul


Enter number of subjects: 3
Enter marks for subject 1: 80
Enter marks for subject 2: 90
Enter marks for subject 3: 70

Student Name: Rahul


Total Marks: 240
Average Marks: 80

Case 2: Invalid Marks

Enter Student Name: Priya


Enter number of subjects: 2
Enter marks for subject 1: 105
Custom Exception: Marks should be between 0 and 100.

Case 3: Division by Zero

Enter Student Name: Arjun


Enter number of subjects: 0
Error: Cannot divide by zero (no subjects entered).

Viva Questions

1. What is the difference between throw and throws?


2. Why is finally block used?
3. Explain checked vs unchecked exceptions with examples.
4. How can we create a user-defined exception in Java?
5. Can a try block execute without a catch block?
Experiment No. 5: Generic Data Handling with HTTP Servlet
Problem Statement

Create a Student Information Web Application using Java Generics and HTTP Servlets.

 Use Generics to store and manage student details in a type-safe collection.


 Implement an HTTP Servlet that accepts student data (name, roll number, marks) via a
web form and displays it back to the user.
 Demonstrate Generics + Servlet integration in a single application.

Theory

Generics in Java

 Allow writing type-safe classes and methods.


 Reduce runtime errors by checking types at compile time.
 Example: ArrayList<String> ensures only strings are stored.

Servlet in Java

 A Servlet is a Java program that runs on a server and handles HTTP requests and
responses.
 HttpServlet provides methods:
o doGet() → handles GET requests.
o doPost() → handles POST requests.

Programs

File 1: [Link] (Generic Class)

// Generic Student Class

public class Student<T1, T2, T3> {

private T1 name;

private T2 rollNo;

private T3 marks;

public Student(T1 name, T2 rollNo, T3 marks) {

[Link] = name;

[Link] = rollNo;

[Link] = marks;
}

public void display() {

[Link]("Name: " + name + ", Roll No: " + rollNo + ", Marks: " + marks);

public String getDetails() {

return "Name: " + name + ", Roll No: " + rollNo + ", Marks: " + marks;

File 2: [Link] (HTTP Servlet using Generics)

import [Link].*;

import [Link].*;

import [Link].*;

// Servlet that uses Generics

public class StudentServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Get data from HTML form

String name = [Link]("name");

int rollNo = [Link]([Link]("rollNo"));

double marks = [Link]([Link]("marks"));

// Using Generics

Student<String, Integer, Double> s1 = new Student<>(name, rollNo, marks);

// Send response

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html><body>");

[Link]("<h2>Student Information</h2>");

[Link]("<p>" + [Link]() + "</p>");


[Link]("</body></html>");

File 3: [Link] (Input Form)

<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="student" method="post">
Name: <input type="text" name="name"><br><br>
Roll No: <input type="text" name="rollNo"><br><br>
Marks: <input type="text" name="marks"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

File 4: [Link] (Servlet Mapping)

<web-app xmlns="[Link] version="3.1">


<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>StudentServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>
</web-app>
Output:

Input Form ([Link]):

Name: Rahul
Roll No: 101
Marks: 88.5

Servlet Output (StudentServlet):

Student Information
Name: Rahul, Roll No: 101, Marks: 88.5

Viva Questions

1. What are Generics in Java? Why are they useful?


2. Difference between Servlet and HttpServlet.
3. Explain the lifecycle of a Servlet.
4. Why does Java not support multiple inheritance for Servlets?
5. How can Generics improve servlet-based web applications?
Experiment No. 6 : Login System using JSP, JDBC, and Servlet

Problem Statement

Design and implement a Login Web Application where:

1. A JSP page provides a login form.


2. The credentials are validated from a database (MySQL/Oracle) using JDBC.
3. If login is successful, a Servlet is called to handle user operations (e.g., Welcome
message, session handling, logout).
4. If login fails, the user is redirected back to the login page with an error message.

Theory

 JSP (Java Server Pages): Used for creating dynamic web pages with embedded Java
code.
 JDBC (Java Database Connectivity): API to connect and execute queries on databases.
 Servlets: Java programs that run on a server and handle HTTP requests/responses.
 Integration Flow:
1. User submits login form (JSP).
2. Servlet handles request → validates using JDBC.
3. Redirects user to appropriate page based on result.

Program (Single Integrated Example)

Database Table (MySQL Example)

CREATE DATABASE userdb;


USE userdb;

CREATE TABLE users (


id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);

INSERT INTO users (username, password) VALUES ('admin', 'admin123'), ('user',


'user123');

[Link] (Login Form JSP)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
<p style="color:red;">
<%= [Link]("errorMessage") != null ?
[Link]("errorMessage") : "" %>
</p>
</body>
</html>

📌 [Link] (Validation + Redirect using JDBC)

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

String uname = [Link]("username");


String pass = [Link]("password");

try {
// Load JDBC Driver
[Link]("[Link]");

// Connect to DB
Connection con = [Link](
"jdbc:mysql://localhost:3306/userdb", "root", "password");

PreparedStatement ps = [Link](
"SELECT * FROM users WHERE username=? AND password=?");
[Link](1, uname);
[Link](2, pass);

ResultSet rs = [Link]();

if ([Link]()) {
// Success → forward to Welcome Servlet
HttpSession session = [Link]();
[Link]("username", uname);
[Link]("WelcomeServlet");
} else {
// Failure → back to [Link]
[Link]("errorMessage", "Invalid Username or
Password!");
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
📌 [Link] (Handles Operations after Login)

import [Link].*;
import [Link].*;
import [Link].*;

public class WelcomeServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

HttpSession session = [Link](false);


[Link]("text/html");
PrintWriter out = [Link]();

if (session != null && [Link]("username") != null) {


String uname = (String) [Link]("username");
[Link]("<html><body>");
[Link]("<h2>Welcome, " + uname + "!</h2>");
[Link]("<form action='LogoutServlet' method='post'>");
[Link]("<input type='submit' value='Logout'>");
[Link]("</form>");
[Link]("</body></html>");
} else {
[Link]("[Link]");
}
}
}

📌 [Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class LogoutServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = [Link]();
[Link](); // End session
[Link]("[Link]");
}
}

📌 [Link] (Servlet Mapping)

<web-app xmlns="[Link] version="3.1">

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>

Sample Execution

1. Open [Link]
2. Username: admin
3. Password: admin123
4. If valid → WelcomeServlet
5. Welcome, admin!
6. [Logout]
7. If invalid → Back to [Link]
8. Invalid Username or Password!

Viva Questions

1. Difference between JSP and Servlet.


2. Explain JDBC architecture and drivers.
3. What is the difference between sendRedirect() and [Link]()?
4. How does session management work in Servlets?
5. Why is PreparedStatement preferred over Statement in JDBC?
Experiment No.7: Demonstrating Implicit and Explicit
Objects in JSP

Problem Statement

Create a JSP program that demonstrates the use of implicit objects (request, response,
session, out, etc.) and an explicit object (by creating an object manually using Java code inside
JSP). The program should take user details through a form, display them using implicit
objects, and also create an explicit object (custom class) to process/display data.

Theory

 Implicit Objects in JSP


JSP provides 9 implicit objects that are available by default in every page without explicit
declaration.
1. request – Represents HTTP request.
2. response – Represents HTTP response.
3. session – Provides session tracking.
4. application – Provides application-level data.
5. out – Used to write output to the client.
6. config – Servlet config object.
7. pageContext – Provides page-specific context.
8. page – Refers to current JSP page (like this).
9. exception – Used for error handling.
 Explicit Objects in JSP
Explicit objects are the ones manually created in JSP using Java code (e.g., new
keyword or JavaBean objects).

Program (Single Integrated Example)

📌 [Link] (Form Page)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<h2>Enter Your Details</h2>
<form action="[Link]" method="post">
Name: <input type="text" name="uname" required><br><br>
Age: <input type="number" name="age" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
📌 [Link] (Using Implicit + Explicit Objects)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<%@ page import="[Link]" %>
<!DOCTYPE html>
<html>
<head>
<title>Display User</title>
</head>
<body>
<h2>Using Implicit Objects</h2>
<%
// Accessing request implicit object
String name = [Link]("uname");
int age = [Link]([Link]("age"));

// Using session implicit object


[Link]("userName", name);

// Using application implicit object


[Link]("appMessage", "Application-wide data
available!");

[Link]("<p>Hello " + name + ", your age is " + age + ".</p>");


[Link]("<p>Session ID: " + [Link]() + "</p>");
[Link]("<p>Application Message: " +
[Link]("appMessage") + "</p>");
%>

<h2>Using Explicit Object</h2>


<%
// Creating explicit object
User userObj = new User(name, age);
[Link]("<p>User Object: " + [Link]() + "</p>");
%>
</body>
</html>

📌 [Link] (Explicit Object Class)

package mypackage;

public class User {


private String name;
private int age;

public User(String name, int age) {


[Link] = name;
[Link] = age;
}

public String getDetails() {


return "Name: " + name + ", Age: " + age;
}
}
Execution Flow

1. Open [Link] → Enter details.


2. On submit → Redirects to [Link].
3. request, session, and application implicit objects are used to display values.
4. An explicit object (User class) is created and used to display formatted user details.

Output

Input ([Link]):

Name: Meerhan
Age: 21

Output ([Link]):

Using Implicit Objects:


Hello Meerhan, your age is 21.
Session ID: 4F123XABC09
Application Message: Application-wide data available!

Using Explicit Object:


User Object: Name: Meerhan, Age: 21

Viva Questions

1. What are implicit objects in JSP? Name all 9.


2. Difference between implicit and explicit objects.
3. Why do we need session and application objects in JSP?
4. How do you create a JavaBean and use it in JSP?
5. Can we use both implicit and explicit objects together?
Experiment No 8 : Design and Implementation of a
Responsive Website
Problem Statement

Design and implement a Personal Portfolio Website using HTML, CSS, and JavaScript.
The website should contain:

 A Home Page with a welcome message.


 An About Section displaying details about the user.
 A Contact Form with basic validation using JavaScript.
 Styling and responsive layout using CSS.

Theory

 HTML (HyperText Markup Language): Used to define the structure of web pages.
Elements like headings, paragraphs, forms, and links are defined using HTML.
 CSS (Cascading Style Sheets): Used to apply styles (colors, fonts, layouts,
responsiveness) to HTML elements.
 JavaScript: A scripting language that enables interactivity in web pages, like form
validation, dynamic content updates, etc.

Program (Single Integrated Example)

📌 [Link]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Personal Portfolio</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<!-- Navigation -->
<nav>
<h2>My Portfolio</h2>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>

<!-- Home Section -->


<section id="home">
<h1>Welcome to My Portfolio</h1>
<p>This is a sample website created using HTML, CSS, and
JavaScript.</p>
</section>

<!-- About Section -->


<section id="about">
<h2>About Me</h2>
<p>Hello! I am a web development enthusiast. This project
demonstrates a simple portfolio website using HTML, CSS, and JavaScript.</p>
</section>

<!-- Contact Section -->


<section id="contact">
<h2>Contact Me</h2>
<form id="contactForm">
<label>Name:</label>
<input type="text" id="name" required><br><br>

<label>Email:</label>
<input type="email" id="email" required><br><br>

<label>Message:</label>
<textarea id="message" required></textarea><br><br>

<button type="submit">Submit</button>
</form>
<p id="output"></p>
</section>

<script src="[Link]"></script>
</body>
</html>

📌 [Link]

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

/* Navigation Bar */
nav {
background-color: #333;
color: white;
padding: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
nav ul {
list-style: none;
display: flex;
gap: 20px;
}
nav ul li a {
color: white;
text-decoration: none;
}
nav ul li a:hover {
text-decoration: underline;
}

/* Sections */
section {
padding: 50px;
text-align: center;
}
#home {
background: #f4f4f4;
}
#about {
background: #ddd;
}
#contact {
background: #f4f4f4;
}

/* Form Styling */
form {
max-width: 400px;
margin: auto;
}
input, textarea, button {
width: 100%;
padding: 10px;
margin-top: 10px;
}
button {
background-color: #333;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #555;
}

📌 [Link]

// JavaScript Form Validation


[Link]("contactForm").addEventListener("submit",
function(event) {
[Link]();

let name = [Link]("name").[Link]();


let email = [Link]("email").[Link]();
let message = [Link]("message").[Link]();
let output = [Link]("output");

if (name === "" || email === "" || message === "") {


[Link] = "⚠ Please fill all fields!";
[Link] = "red";
} else {
[Link] = "✅ Thank you, " + name + "! Your message has
been submitted.";
[Link] = "green";
[Link]("contactForm").reset();
}
});
Execution Flow

1. Open [Link] in a browser.


2. Navigate between Home, About, and Contact sections using the nav bar.
3. Enter details in the Contact Form.
4. JavaScript validates the input and displays success/error messages.

Output

 Home Page: Displays welcome message.( Draw it Manually)


 About Page: Shows user description. .( Draw it Manually)
 Contact Page: Form validates input before submission. .( Draw it Manually)

Viva Questions

1. What is the difference between HTML, CSS, and JavaScript?


2. How does CSS improve website design?
3. What is DOM manipulation in JavaScript?
4. What are responsive web design techniques?
5. Why is form validation important in web applications?
Experiment No.9: Validating User Email Input using
JavaScript
Problem Statement

Create a web page that allows a user to enter their email address.

 The program should validate whether the email contains both @ and . characters.
 If either is missing, the program should display an alert box reporting the error and
prompt the user to re-enter the email.
 If the email is valid, display a success message on the page.

Theory

 JavaScript is used to make web pages interactive.


 Validation is important to prevent incorrect data input.
 alert() function displays a pop-up message.
 while loop or conditional check can be used to repeatedly prompt the user until valid
input is entered.
 This example uses string methods includes() to check the presence of @ and . in the
email.

Program (Single Integrated HTML + JavaScript)

📌 email_validation.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Validation</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
input, button {
padding: 10px;
margin: 10px;
font-size: 16px;
}
p {
font-weight: bold;
}
</style>
</head>
<body>
<h2>Email Validation Form</h2>
<label for="email">Enter your Email:</label>
<input type="text" id="email" placeholder="example@[Link]">
<button onclick="validateEmail()">Submit</button>
<p id="message"></p>
<script>
function validateEmail() {
let email = [Link]("email").[Link]();
let message = [Link]("message");

// Check if email contains '@' and '.'


if (![Link]("@") || ![Link](".")) {
alert("Invalid Email! Please include '@' and '.' in your
email.");
[Link]("email").value = ""; // Clear input
[Link] = "";
} else {
[Link] = "green";
[Link] = "✅ Email is valid: " + email;
}
}
</script>
</body>
</html>

Execution Flow

1. Open email_validation.html in a web browser.


2. Enter an email address and click Submit.
3. If invalid: Alert box appears → Input is cleared → Prompt user to re-enter.
4. If valid: Success message is displayed on the page.

Sample Output

Case 1 – Invalid Email:

 Input: [Link]
 Alert: Invalid Email! Please include '@' and '.' in your email.

Case 2 – Valid Email:

 Input: user@[Link]
 Page displays: ✅ Email is valid: user@[Link]

Viva Questions

1. What is the purpose of JavaScript in form validation?


2. How does the includes() function work?
3. Difference between client-side and server-side validation.
4. Why is it important to validate email addresses?
5. Can we use regular expressions to validate emails more accurately?
Experiment No. 10: Automatic Background Color Change
Using DOM
Problem Statement

Create a web page that automatically changes its background color every 5 seconds.

 Use JavaScript to manipulate the DOM (Document Object Model).


 Demonstrate dynamic interaction with the webpage by modifying styles
programmatically.

Theory

 DOM (Document Object Model): A programming interface for HTML and XML
documents.
 Allows JavaScript to access and manipulate elements and styles dynamically.
 setInterval() method is used to repeatedly execute a function after a specified time
interval.
 Inline style changes can dynamically modify page appearance.

Program (Single HTML + JavaScript)

📌 background_change.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Automatic Background Color Change</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
transition: background-color 1s; /* smooth transition */
}
h1 {
margin-bottom: 50px;
}
</style>
</head>
<body>
<h1>Automatic Background Color Changer</h1>
<p>The background color of this page changes every 5 seconds.</p>

<script>
// Array of colors
const colors = ["#FF5733", "#33FF57", "#3357FF", "#F3FF33",
"#FF33A8", "#33FFF3"];
let index = 0;
function changeBackgroundColor() {
// Access the body element using DOM
[Link] = colors[index];
index = (index + 1) % [Link]; // loop back to first color
}

// Change background every 5 seconds (5000 milliseconds)


setInterval(changeBackgroundColor, 5000);
</script>
</body>
</html>

Execution Flow

1. Open background_change.html in a web browser.


2. Every 5 seconds, the background color of the page changes automatically.
3. The color cycles through the predefined array of colors indefinitely.

Sample Output

 Page starts with a default background.


 After 5 seconds: color changes to #FF5733 (red-orange).
 After 10 seconds: color changes to #33FF57 (green).
 After 15 seconds: color changes to #3357FF (blue), and so on.

Viva Questions

1. What is the DOM and why is it important in web development?


2. What does setInterval() do in JavaScript?
3. How can you stop the interval once it starts?
4. How is [Link] modifying the DOM?
5. How can you make the background color change smoothly?

You might also like