Advanced Java Lab Manual
Advanced Java Lab Manual
Davanagere, Karnataka-570003
“ADVANCED JAVA”
(BIS402)
PREPARED BY:
Program Outcomes
Information Science & Engineering Graduates will be able to:
PO2 Problem analysis: Identify, formulate, review research literature, and analyze
complex computer engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern computer engineering and IT tools including prediction and modeling to
complex computer engineering activities with an understanding of the limitations.
PO6 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.
PO7 Environment and sustainability: Understand the impact of the professional
computer engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the computer engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
PO12 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.
ADVANCED JAVA BIS402
import java.util.ArrayList;
import java.util.Collections;
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
fruits.remove("Banana");
System.out.println("ArrayList after removing 'Banana': " + fruits);
Collections.sort(fruits);
System.out.println("ArrayList after sorting: " + fruits);
Output:
ArrayList after adding elements: [Apple, Banana, Orange, Mango]
ArrayList after removing 'Banana': [Apple, Orange, Mango]
ArrayList after sorting: [Apple, Mango, Orange]
Array obtained from ArrayList:
Apple
Mango
Orange
2. Develop a program to read random numbers between a given range that are
multiples of 2 and 5, sort the numbers according to tens place using comparator.
import java.util.*;
class MailList {
public static void main(String[] args) {
LinkedList<Address> ml = new LinkedList<Address>();
Ralph Baker
1142 Maple Lane
Mahomet IL 61853
Tom Carlton
867 Elm St
Champaign IL 61820
4. Implement a java program to illustrate the use of different types of string class
constructors.
import java.util.*;
import java.io.*;
import java.util.*;
char ch = str.charAt(7);
System.out.println("Character at index 7: " + ch);
stringBuffer.append(" Java");
stringBuffer.append('!');
System.out.println("Appended String: " + stringBuffer);
stringBuffer.replace(1, 3, "i");
System.out.println("String after replacement: " + stringBuffer);
stringBuffer.reverse();
System.out.println("Reversed String: " + stringBuffer);
stringBuffer. ensureCapacity(20);
System.out.println("New Capacity of StringBuffer: " + stringBuffer.capacity());
stringBuffer.setLength(20);
System.out.println("StringBuffer length after setting length to 20: " + stringBuffer.length());
}
}
Output:
Length of StringBuffer: 5
Capacity of StringBuffer: 21
Appended String: Hello Java!
Character at index 6: J
StringBuffer after setCharAt: Hello Wava!
Characters from index 1 to 4: ell
Inserted String: Hello Awesome Wava!
7. Demonstrate a swing event handling application that creates 2 buttons Alpha and
Beta and displays the text “Alpha pressed” when alpha button is clicked and “Beta
pressed” when beta button is clicked.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
jfrm.add(jlab);
jfrm.setVisible(true);
}
Output:
8. A program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., GreetingApp), choose the server (e.g., Apache Tomcat), and
click Finish.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Greeting Servlet";
}
}
Output:
9. A servlet program to display the name, USN, and total marks by accepting student
detail.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., StudentApp), choose the server (e.g., Apache Tomcat), and
click Finish.
<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h1>Enter Student Details</h1>
<form action="DisplayDetailsServlet" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="usn">USN:</label>
<input type="text" id="usn" name="usn"><br><br>
<label for="marks">Total Marks:</label>
<input type="number" id="marks" name="marks"><br><br>
<input type="submit" value="Submit">
</form>
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 16
ADVANCED JAVA BIS402
</body>
</html>
@WebServlet(urlPatterns = {"/DisplayDetailsServlet"})
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Student Details Display Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Student Details " + request.getContextPath() + "</h1>");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Student Details";
}
}
Step 4: Deploy and Test the Application
1. Right-click on the project name and select Run.
2. The browser should open with the URL of your application.
3. Fill in the form and submit it to see the student details displayed by the servlet.
Output:
10. A Java program to create and read the cookie for the given cookie name as
“EMPID” and its value as “AN2356”.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., CookieApp), choose the server (e.g., Apache Tomcat), and
click Finish.
@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("SetCookieServlet called");
Cookie empidCookie = new Cookie("EMPID", "AN2356");
empidCookie.setMaxAge(24 * 60 * 60);
response.addCookie(empidCookie);
response.setContentType("text/html");
response.getWriter().println("Cookie 'EMPID' with value 'AN2356' has been set.");
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ReadCookieServlet")
public class ReadCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ReadCookieServlet called");
Cookie[] cookies = request.getCookies();
String empidValue = "Cookie not found";
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("EMPID".equals(cookie.getName())) {
empidValue = cookie.getValue();
break;
}
}
}
response.setContentType("text/html");
response.getWriter().println("EMPID Cookie Value: " + empidValue);
}
}
Output:
11. Write a JAVA Program to insert data into Student DATA BASE and retrieve info
based on particular queries (For example update, delete, search etc…).
1. Create the MySQL Database
(i). Start XAMPP
Open the XAMPP Control Panel.
Start the Apache and MySQL modules by clicking on the "Start" buttons next to
them.
StudentDBApp.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
ps.setString(3, grade);
ps.executeUpdate();
System.out.println("Student inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updateStudent(int id, String name, int age, String grade) {
String query = "UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, name);
ps.setInt(2, age);
ps.setString(3, grade);
ps.setInt(4, id);
ps.executeUpdate();
System.out.println("Student updated successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
do {
System.out.println("1. Insert Student");
System.out.println("2. Update Student");
System.out.println("3. Delete Student");
System.out.println("4. Search Student");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter name: ");
scanner.close();
}
}
Output:
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Abhay
Enter age: 24
Enter grade: A
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Bharath
Enter age: 20
Enter grade: B
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Chetan
Enter age: 19
Enter grade: C
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 2
Enter student ID to update: 2
Enter new name: Deepak
Enter new age: 20
Enter new grade: A
Student updated successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 3
Enter student ID to delete: 3
Student deleted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 4
Enter student ID to search: 1
ID: 1
Name: Abhay
Age: 24
Grade: A
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 4
Enter student ID to search: 4
Student not found.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 5
Exiting...
12. A program to design the Login page and validating the USER_ID and PASSWORD
using JSP and DataBase.
1. Create the MySQL Database
(i). Start XAMPP
Open the XAMPP Control Panel.
Start the Apache and MySQL modules by clicking on the "Start" buttons next to
them.
String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, userID);
pst.setString(2, password);
rs = pst.executeQuery();
if(rs.next()) {
out.println("Login successful! Welcome, " + userID);
} else {
out.println("Invalid user ID or password. Please try again.");
}
} catch (Exception e) {
e.printStackTrace();
out.println("Error occurred while connecting to the database.");
} finally {
try {
if(rs != null) rs.close();
if(pst != null) pst.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
</body>
</html>
Output: