PRACTICAL FILE
ADVANCED JAVA
PROGRAMMING
Subject Code: CIE-306P
Submitted by: HARSH RAMRAKHIANI
Submitted to: DR. TRIPTI RATHEE
Batch: 2023-2027
1
MISSION AND VISION OF MSIT-
VISION:
To become one of the most admired centres of academic excellence in the field of
Engineering & Technology for all-round professional development of students to enable
them to meet the growing technological needs of the country.
MISSION:
Developing new paradigm in imparting education in the fields of Engineering and
Technology and to imbibe national values leading to student's empowerment, with a view
to prepare them to meet the national and global challenges.
2
MISSION AND VISION OF IT DEPARTMENT-
VISION:
To build a culture of innovation and research in students and make them capable to solve
upcoming challenges of human life using computing.
MISSION:
M1: To develop 'educational pathways' so that students can take their career towards
success
M2: To imbibe curiosity and support innovativeness by providing guidance to use the
technology effectively.
M3: To inculcate management skills, integrity, and honesty through curricular, co-
curricular, and extra-curricular activities.
PROGRAMEDUCATIONAL OBJECTIVES:
PEO1: Graduates of IT program are prepared to be employed in IT industries and be
engaged in learning, understanding, and applying new ideas.
PEO2: The graduates are prepared to perform effectively as individuals and team
members in the workplace, growing into highly technical or project management and
leadership roles.
PEO3: Graduates are prepared to apply basic principles of practices of computing
grounded in mathematics and science for successfully completing software-related
projects to satisfy customer business objectives and productively engage in research.
PEO4: Graduates are prepared to pursue higher studies so that they can contribute to the
3
teachingprofession/research and development of information technology and other allied
fields.
PROGRAM OUTCOMES:
Engineering Graduates will be able to:
• Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
• Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
• Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
needs with appropriate consideration for public health and safety, and the cultural,
societal, and environmental considerations.
• Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
• Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
• The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal, and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
• Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
• Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
• Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
• Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
4
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
• Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as
a member and leader in a team, to manage projects and in multidisciplinary
environments.
• Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of
technological change.
ProgramSpecific Outcome:
PSO-1: Abilityto understand the principles and working of hardware and software
aspects in information technology.
PSO-2: Abilityto explore and develop innovative ideas to solve real world problem using
IT skills.
5
INDEX-
SERIAL NO: DATE: EXPERIMENT: SIGN:
6
7
Practical-1
AIM: Write a program to demonstrate a concept of applet programming.
THEORY:
An applet is a small Java program that runs inside a web browser or an applet viewer. Unlike normal
Java applications, applets do not have a main () method. Instead, their execution is controlled by the
browser or applet viewer.
Applet programming is mainly used to create interactive web-based applications, such as
animations, games, and graphical demonstrations.
An applet works through the following methods:
1. init() – Called once when the applet is loaded
2. start() – Called when the applet becomes active
3. paint(Graphics g) – Used to draw graphics/text
4. stop() – Called when the applet becomes inactive
5. destroy() – Called when the applet is removed
CODE:
import [Link].*;
import [Link].*;
/*
* <applet code="SmileyApplet" width=300 height=300>
* </applet>
*/
public class SmileyApplet extends Applet {
public void init() {
[Link]("init() called");
}
public void start() {
[Link]("start() called");
}
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 50, 200, 200); // face outline
1
[Link]([Link]); // face
[Link](50, 50, 200, 200);
[Link]([Link]);
[Link](90, 100, 30, 30); // eyes
[Link](90, 100, 30, 30);
[Link](180, 100, 30, 30);
[Link](180, 100, 30, 30);
[Link](100, 150, 100, 50, 0, -180); // smile
}
public void stop() {
[Link]("stop() called");
}
public void destroy() {
[Link]("destroy() called");
}
}
Output:
2
Practical-2
AIM: Write a program to demonstrate a concept of socket programming.
THEORY:
Socket programming is a method of enabling communication between two computers over a network.
A socket is an endpoint that allows two programs (client and server) to exchange data using network
protocols like TCP or UDP.
A socket is defined by:
• IP Address – identifies the device
• Port Number – identifies the application
• Protocol (TCP/UDP) – defines the communication type
Working Principle:
In a typical client-server model:
• The server creates a socket, binds it to a port, listens, and accepts client connections.
• The client creates a socket and connects to the server.
• After connection, both can send and receive data.
• Finally, the connection is closed.
Types of Socket Communication:
1. TCP (Transmission Control Protocol)
o Connection-oriented
o Reliable and ordered communication
2. UDP (User Datagram Protocol)
o Connectionless
o Faster but less reliable
CODE SERVER:
import [Link].*;
import [Link].*;
public class DemoServer{
public static void main(String[] args) {
try{
ServerSocket s=new ServerSocket(1212);
3
[Link]("Waiting for client");
Socket obj=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
String msg=[Link]();
[Link]("Client says : "+msg);
[Link]("Hey Client I am free how are you");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
catch(Exception e){
[Link]();
[Link](e);
}
}
}
CODE CLIENT:
import [Link].*;
import [Link].*;
public class DemoClient{
public static void main(String[] args) {
try {
Socket obj=new Socket("localhost",1212);
DataOutputStream dout=new DataOutputStream([Link]());
DataInputStream din=new DataInputStream([Link]());
[Link]("Hey Server how are you? ");
[Link]();
String reply=[Link]();
[Link]("Reply is: "+reply);
[Link]();
[Link]();
[Link]();
}
catch (Exception e) {
4
[Link]();
[Link](e);
}
}
}
Output:
5
Practical-3
AIM: Write a Java program to demonstrate the concept of multi-threading.
THEORY:
Multithreading is a feature of Java that allows a program to execute multiple threads (smallest units of
a process) concurrently.
A thread is a lightweight sub-process. Multithreading helps in performing multiple tasks at the same
time, improving CPU utilization.
Why Use Multithreading?
• Better performance (parallel execution)
• Efficient CPU usage
• Faster execution of tasks
• Useful in real-world apps (games, web servers, etc.)
Ways to Create Threads in Java
1. By Extending Thread Class
• Create a class that extends Thread
• Override the run() method
• Call start() method
2. By Implementing Runnable Interface
• Create a class that implements Runnable
• Override run()
• Pass object to Thread and call start()
Thread Life Cycle
1. New
2. Runnable
3. Running
4. Blocked/Waiting
5. Terminated
6
Important Methods
• start() → starts a thread
• run() → contains code executed by thread
• sleep() → pauses thread
• join() → waits for another thread to finish
CODE
import [Link];
class Multithreading extends Thread{
public void run(){
for(int i=0;i<10;i++){
[Link]("Thread runs for: "+i);
class Multithreading2 implements Runnable{
public void run(){
for(int i=0;i<10;i++){
[Link]("Thread2 runs for: "+i);
public class Test{
public static void main(String[] args) {
7
Multithreading m1=new Multithreading();
[Link]();
[Link]("Thread1");
Multithreading2 m2=new Multithreading2();
Thread t2=new Thread(m2,"Thread2");
[Link]();
for(int i=0;i<10;i++){
[Link]("Main thread");
Output:
8
Practical-4
AIM: Write a Java program to demonstrate the use of Java Beans.
THEORY:
A JavaBean is a special type of Java class used to create reusable software components. It follows
certain conventions so that it can be easily used in applications.
Features of JavaBeans
• Must implement Serializable interface
• Should have a no-argument constructor
• Properties are accessed using getter and setter methods
• Encapsulates data (data hiding)
JavaBean Naming Conventions
• Getter → getPropertyName()
• Setter → setPropertyName()
• Boolean Getter → isPropertyName()
Advantages
• Reusable components
• Easy to maintain
• Supports encapsulation
• Platform independent
CODE
[Link];
publicclass StudentBean implements Serializable {
private int id;
private Stringname;
9
publicStudentBean() {}
publicintgetId() {
return id;
publicvoidsetId(int id) {
[Link] = id;
public StringgetName() {
returnname;
publicvoidsetName(Stringname) {
[Link] = name;
publicstaticvoidmain(String[] args) {
StudentBeanstudent = new StudentBean();
[Link](101);
[Link]("Rahul");
[Link]("Student ID: " + [Link]());
[Link]("Student Name: " +[Link]());
}
Output:
10
Practical-5
AIM: Write a Java program to insert data into a table using JSP.
THEORY:
JSP (JavaServer Pages) allows embedding Java code in HTML. To insert data into a database table
using JSP, we use JDBC (Java Database Connectivity). JSP makes it easy to build dynamic web
applications by writing Java directly inside HTML pages.
Key Steps:
1. Load the JDBC driver
2. Establish a Connection using DriverManager
3. Create a PreparedStatement with an INSERT SQL query
4. Execute the statement
5. Close the connection
CODE:
[Link]
<!DOCTYPE html>
<html>
<body>
<form action="[Link]" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
[Link]
<%@ page import="[Link].*" %>
<%
String name = [Link]("name");
int age = [Link]([Link]("age"));
Connection con = null;
try {
[Link]("[Link]");
11
con = [Link]("jdbc:mysql://localhost:3306/studentdb", "root", "password");
PreparedStatement ps = [Link]("INSERT INTO students(name, age) VALUES(?,
?)");
[Link](1, name);
[Link](2, age);
int result = [Link]();
if (result > 0) {
[Link]("<h3>Record inserted successfully!</h3>");
}
} catch (Exception e) {
[Link]("Error: " + [Link]());
} finally {
if (con != null) [Link]();
}
%>
Output:
12
Practical-6
AIM: Write JSP program to implement form data validation.
THEORY:
Form data validation ensures that user input is correct before processing. JSP can validate form fields on
the server side using Java logic inside scriptlets.
Common validations include:
• Checking if fields are empty
• Validating email format
• Checking numeric ranges
• Password length validation
CODE:
[Link]
<!DOCTYPE html>
<html>
<body>
<form action="[Link]" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
<%
String name = [Link]("name");
String email = [Link]("email");
String password = [Link]("password");
String ageStr = [Link]("age");
13
String error = "";
if (name == null || [Link]().isEmpty()) {
error += "Name is required.<br>";
}
if (email == null || ) {
error += "Valid email is required.<br>";
}
if (password == null || [Link]() < 6) {
error += "Password must be at least 6 characters.<br>";
}
try {
int age = [Link](ageStr);
if (age < 1 || age > 120) {
error += "Age must be between 1 and 120.<br>";
}
} catch (NumberFormatException e) {
error += "Age must be a number.<br>";
}
if ([Link]()) {
[Link]("<h3>Form submitted successfully!</h3>");
[Link]("Name: " + name + "<br>");
[Link]("Email: " + email + "<br>");
} else {
[Link]("<h3>Validation Errors:</h3>");
[Link](error);
}
%>
Output:
14
15
Practical-7
AIM: Write a Java program to show user validation using Servlet.
THEORY:
A Servlet is a Java class that handles HTTP requests. User validation using Servlet checks whether a
user's login credentials are correct by comparing input with stored data.
Steps for User Validation:
1. Create an HTML login form
2. Create a Servlet that processes the POST request
3. Get username and password from request parameters
4. Compare with predefined or database values
5. Send appropriate response to the client
CODE:
[Link]
<!DOCTYPE html>
<html>
<body>
<h2>User Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
16
import [Link];
import [Link];
import [Link];
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String username = [Link]("username");
String password = [Link]("password");
if ([Link]("admin") && [Link]("admin123")) {
[Link]("<h2>Login Successful</h2>");
[Link]("<h3>Welcome " + username + "</h3>");
} else {
[Link]("<h2>Invalid Username or Password</h2>");
}
}
}
Output:
17
Practical-8
AIM: Write a program to set cookie information using Servlet.
THEORY:
Cookies are small pieces of data stored on the client's browser by the server. Servlets can set and retrieve
cookies using the Cookie class provided by the [Link] package.
Cookie Operations:
• Setting a cookie: Create Cookie object, set max age, add to response
• Reading a cookie: Get all cookies from request, iterate to find desired cookie
• Deleting a cookie: Set max age to 0
CODE:
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Cookie userCookie = new Cookie("username", "HarshR");
[Link](60 * 60 * 24);
[Link](userCookie);
18
Cookie themeCookie = new Cookie("theme", "dark");
[Link](60 * 60 * 24);
[Link](themeCookie);
[Link]("<h3>Cookies have been set successfully!</h3>");
[Link]("<a href='GetCookieServlet'>Read Cookies</a>");
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/GetCookieServlet")
public class GetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Cookie[] cookies = [Link]();
if (cookies != null) {
[Link]("<h3>Cookie Information:</h3>");
for (Cookie c : cookies) {
[Link]("Name: " + [Link]() + " | Value: " + [Link]() + "<br>");
}
} else {
[Link]("<h3>No cookies found.</h3>");
}
}
}
19
Output:
20
Practical-9
AIM: Develop a small web program using Servlets, JSPs with Database connectivity.
THEORY:
A web application with Servlets, JSPs, and Database connectivity combines all Java web technologies to
build a complete data-driven application. This practical demonstrates a simple Student Management
System.
Components:
• HTML Form: For user input
• JSP Page: For display logic
• Servlet: For business logic and database operations
• MySQL Database: For persistent storage
Flow:
1. User fills HTML form
2. Form submits to Servlet
3. Servlet connects to database and performs operation
4. Servlet forwards result to JSP
5. JSP displays the result to user
CODE:
[Link]
<!DOCTYPE html>
<html>
<body>
<h2>Student Management System</h2>
<form action="StudentServlet" method="post">
Roll No: <input type="text" name="roll"><br>
Name: <input type="text" name="name"><br>
Course: <input type="text" name="course"><br>
<input type="submit" value="Add Student">
</form>
<br><a href="StudentServlet?action=view">View All Students</a>
</body>
21
</html>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentServlet extends HttpServlet {
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String pass = "password";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String roll = [Link]("roll");
String name = [Link]("name");
String course = [Link]("course");
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
PreparedStatement ps = [Link](
"INSERT INTO student(roll, name, course) VALUES(?, ?, ?)");
[Link](1, roll);
[Link](2, name);
[Link](3, course);
[Link]();
[Link]();
[Link]("[Link]?name=" + name);
} catch (Exception e) {
[Link]().println("Error: " + [Link]());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = [Link]("action");
if ("view".equals(action)) {
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
Statement st = [Link]();
22
ResultSet rs = [Link]("SELECT * FROM student");
[Link]("rs", rs);
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
[Link]();
} catch (Exception e) {
[Link]().println("Error: " + [Link]());
}
}
}
}
[Link]
<html><body>
<h3>Student <%= [Link]("name") %> added successfully!</h3>
<a href="[Link]">Go Back</a>
</body></html>
[Link]
<%@ page import="[Link].*" %>
<html><body>
<h2>All Students</h2>
<table border='1'>
<tr><th>Roll</th><th>Name</th><th>Course</th></tr>
<%
ResultSet rs = (ResultSet) [Link]("rs");
while ([Link]()) {
%>
<tr>
<td><%= [Link]("roll") %></td>
<td><%= [Link]("name") %></td>
<td><%= [Link]("course") %></td>
</tr>
<% } %>
</table>
<a href='[Link]'>Go Back</a>
</body></html>
23
Output:
24