Advanced Java Lab Manual Upd
Advanced Java Lab Manual Upd
Name :
USN :
Batch: Section :
Prepared &Reviewed By
Ms.BHAVANA C D
Assistant Professor
Dept of CSE &ISE
ADVANCED JAVA Semester IV
Course Code BIS402 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 3:0:2:0 SEE Marks 50
Total Hours of Pedagogy 40 hours Theory + 8-10 Lab slots Total Marks 100
Credits 04 Exam Hours
Examination nature (SEE) Theory/
Note- Students who have not opted for Java course in earlier semester, student has to undergo a bridge
course on basics of java before the commencement of 4th sem
Course objectives:
CLO 1. Understanding the fundamentals of collection framework
CLO 2. Demonstrate the fundamental concepts of String operations and Swing applications
CLO 3. Design and develop web applications using Java servlets and JSP
CLO 4. Apply database interaction through Java database Connectivity
MODULE-1
The collections and Framework: Collections Overview, The Collection Interfaces, The Collection Classes,
Accessing a collection Via an Iterator, Storing User Defined Classes in Collections, The Random Access
Interface, Working With Maps, Comparators, The Collection Algorithms, Arrays,, The legacy Classes and
Interfaces, Parting Thoughts on Collections.
MODULE-2
String Handling :The String Constructors, String Length, Special String Operations, Character Extraction,
String Comparison, Searching Strings, Modifying a String, Data Conversion Using valueOf( ), Changing the
Case of Characters Within a String, joining strings, Additional String Methods, StringBuffer , StringBuilder
Text Book 1: Ch 18
MODULE-3
Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key
Swing Features, The MVC Connection, Components and Containers, The Swing Packages, A Simple Swing
Application, Event Handling, Painting in Swing,
Exploring Swing : JLabel and ImageIcon,JTextField,The Swing Buttons-JButton, JToggleButton, Check
Boxes, Radio Buttons
@# 16032024
Text Book 1: Ch 32 and Ch. 33
MODULE-4
Introducing servlets: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development; A
simple Servlet; The Servlet API; The Jakarta. Servlet Package; Reading Servlet Parameter; The
Jakarta.servlet.http package; Handling HTTP Requests and Responses; Using Cookies; Session Tracking.
Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, Control statements, Loops, Request
String, Parsing other information, User sessions, Cookies, Session Objects.
Text Book 1: Ch 36
Text Book 2: Ch 11
MODULE-5
JDBC Objects: The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the JDBC
process; Database Connection; Associating the JDBC/ODBC Bridge with the Database; Statement Objects;
ResultSet; Transaction Processing; Metadata, Data types; Exceptions.
Text Book 2: Ch 06
@# 16032024
PRACTICAL COMPONENT OF IPCC(May cover all / major modules)
Sl.N Experiments
O
1 Implement a java program to demonstrate creating an ArrayList, adding elements, removing elements,
sorting elements of ArrayList. Also illustrate the use of toArray() method.
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.
3
Implement a java program to illustrate storing user defined classes in collection.
4
Implement a java program to illustrate the use of different types of string class constructors.
5 Implement a java program to illustrate the use of different types of character extraction, string
comparison, string search and string modification methods.
6
Implement a java program to illustrate the use of different types of StringBuffer methods
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.
8 A program to display greeting message on the browser “Hello UserName”, “How Are You?”, accept
username from the client using servlet.
9
A servlet program to display the name, USN, and total marks by accepting student detail
10 A Java program to create and read the cookie for the given cookie name as “EMPID” and its value as
“AN2356”.
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…).
12 A program to design the Login page and validating the USER_ID and PASSWORD using JSP and
DataBase.
Course outcomes (Course Skill Set):
At the end of the course, the student will be able to:
CO 1. Apply appropriate collection class/interface to solve the given problem
CO 2. Demonstrate the concepts of String operations in Java
CO 3. Apply the concepts of Swings to build Java applications
CO 4. Develop web based applications using Java servlets and JSP
CO 5. Use JDBC to build database applications
CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two Tests,
@# 16032024
each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other assessment methods
mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the syllabus and the second test
after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.
CIE for the practical component of the IPCC
● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for the
test to be conducted after the completion of all the laboratory sessions.
● On completion of every experiment/program in the laboratory, the students shall be evaluated including
viva-voce and marks shall be awarded on the same day.
● The CIE marks awarded in the case of the Practical component shall be based on the continuous evaluation
of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all experiments’
write-ups are added and scaled down to 15 marks.
● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for
50 marks and scaled down to 10 marks.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory
component of IPCC for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.
SEE for IPCC
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for
the course (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum
of 3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scoredby the student shall be proportionally scaled down to 50 Marks
The theory portion of the IPCC shall be for both CIE and SEE, whereas the practical portion will have a
CIE component only. Questions mentioned in the SEE paper may include questions from the practical
component.
Suggested Learning Resources:
Books
1. Y. Daniel Liang: Introduction to JAVA Programming, 7th Edition, Pearson Education, 2007.
2. Stephanie Bodoff et al: The J2EE Tutorial, 2nd Edition, Pearson Education,2004.
3. Uttam K Roy, Advanced JAVA programming, Oxford University press, 2015.
@# 16032024
Advanced java Lab - (BIS402)
INDEX
PAGE
S.NO EXPERIMENTS
NO
Aim : The program aims to demonstrate the basic operations of Java's ArrayList class,
including creation, addition, removal, sorting, and conversion to an array. It shows how to
manage String and Integer elements, and how to perform arithmetic operations on integer
arrays.
Definition:
ArrayList Creation: Creates an ArrayList object for storing elements of a specified type.
Adding Elements: Inserts elements at the end or a specific index of the ArrayList.
Removing Elements: Deletes elements either by value or index from the ArrayList.
Sorting Elements: Arranges elements in the ArrayList in natural order using
Collections.sort().
Converting to Array: Converts the ArrayList to an array using the toArray()
method and displays its contents.
Program:
import java.util.*;
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
al.remove("F");
al.remove(2);
array = al.toArray(array);
intList.add(1);
intList.add(2);
intList.add(4);
intArray = intList.toArray(intArray);
int sum = 0;
for (int i : intArray) sum += i;
Input/Output:
Program 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
Aim: To find The program aims to generate a list of random integers within a specified range, filter out
numbers that are multiples of both 2 and 5, and then sort these filtered numbers based on their tens
place using a custom comparator. Finally, it displays the generated, filtered, and sorted numbers.
Definition:
Generate Random Numbers: Creates a list of random integers within a given range.
Filter Multiples: Extracts numbers that are multiples of both 2 and 5.
Custom Comparator: Defines a comparator to sort numbers based on their tens place value.
Sort Numbers: Orders the filtered numbers according to their tens place using the custom
comparator.
Display Results: Outputs the generated, filtered, and sorted numbers to the console.
Program:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
output:
Generated Numbers: [23, 46, 75, 91, 62, 44, 31, 57, 66, 99, 55, 80, 73, 52, 35, 25, 85, 40, 10, 28]
Filtered Numbers: [40, 10]
Sorted Numbers: [10, 40]
Program 3
Implement a java program to illustrate storing user defined classes in collection.
Aim: The aim of this Java program is to demonstrate how to store and manage user-defined
class objects within a collection. Specifically, it uses a LinkedList to store instances of the
Address class, and then prints out each address to illustrate how custom objects can be handled
in a collection.
Definition:
User-Defined Class: Address represents a custom class with attributes like name, street, city,
state, and code.
Constructor: Initializes Address objects with specific values for their attributes.
toString() Method: Provides a formatted string representation of an Address object.
LinkedList: A collection used to store multiple Address objects.
Iteration: The program iterates over the LinkedList to print each Address object
using its overridden toString() method.
Program A:
import java.util.LinkedList;
class Address {
private String name;
private String street;
private String city;
private String state;
private String code;
class MailList {
public static void main(String[] args) {
// Creating a LinkedList to store Address objects
Department of ISE, AIT Tumkur Page 8
Advanced java Lab - (BIS402)
LinkedList<Address> ml = new LinkedList<>();
Ralph Baker
1142 Maple Lane
Mahomet IL 61853
Tom Carlton
867 Elm St
Champaign IL 61820
Program 4 Implement a java program to illustrate the use of different types of string class
constructors.
Aim:To find The aim of this Java program is to illustrate the various constructors provided by the
String class for creating strings from different data types and sources. It demonstrates creating strings
from empty strings, character arrays, byte arrays, StringBuffer, StringBuilder, Unicode code
points, and string literals. Additionally, it shows how to create strings using these constructors and print
the results.
Definition:
Empty String Constructor: Creates an empty string using the default String constructor.
Character Array Constructor: Constructs a string from a character array, optionally
specifying a substring of the array.
Byte Array Constructor: Constructs a string from a byte array, with optional start index and
length.
StringBuffer/StringBuilder Constructor: Creates a string from StringBuffer or
StringBuilder objects.
Unicode Code Points Constructor: Creates a string from an array of Unicode code
points.
Program:
public class StringConstructorsExample {
public static void main(String[] args) {
Output:
Empty String: ""
String from char array: "abc"
Substring from char array: "cde"
String from another String: "abc"
String from byte array: "ABCDEF"
Substring from byte array: "CDE"
String from StringBuffer: "Hello"
String from Unicode code points: "abcde"
String from StringBuilder: "World"
Concatenated String: "Hello World"
Program 5
Aim: The aim of this Java program is to demonstrate various string operations provided by the String
class. It covers character extraction, string comparison, string searching, and string modification
methods. Each section illustrates different methods such as charAt(), substring(), equals(),
indexOf(), and replace(), showcasing how these methods are used to manipulate and analyze strings
in Java.
Definition:
Character Extraction Methods: Methods like charAt(), substring(), and toCharArray() are
used to extract specific characters or substrings from a String or convert it to a character array.
String Comparison Methods: Methods like equals(), equalsIgnoreCase(), regionMatches(),
and compareTo() compare strings for equality or order, handling case sensitivity and substring
matching.
String Searching Methods: Methods like indexOf() and lastIndexOf() find the positions of
substrings or characters within a String.
String Modification Methods: Methods such as concat(), replace(), and trim() modify a
String by concatenation, character replacement, or trimming whitespace.
Sorting Strings: The compareTo() method is used for sorting strings alphabetically, demonstrated
here with a bubble sort example.
Program
public class StringOperationsDemo {
public static void main(String[] args) {
System.out.println("Implementing Java program to illustrate different types of string operations.\n");
Output:
Implementing Java program to illustrate different types of string operations.
Example of substring():
This is a test. This is, too.
This was a test. This is, too.
This was a test. This was, too.
This was a test. This was, too.
This was a test. This was, too.
b) Example of regionMatches()
Region matches from index 7: true
d) Example of equals() vs ==
Hello equals Hello -> true
Hello == Hello -> true
e) Example of compareTo()
Sorted array:
all aid come country for good is men now the time to to
b) Example of replace()
Replaced string: Hewwo
c) Example of trim()
Trimmed string: "Hello World"
Program 6 Implement a java program to illustrate the use of different types of StringBuffer
methods.
Aim: The aim of this Java program is to demonstrate the various methods available in the
StringBuffer class for manipulating and querying string buffers. It illustrates how to use
methods to manage buffer capacity, modify characters, append, insert, delete, reverse, and
replace parts of the buffer, and extract substrings.
Definition:
The program StrinBufferDemo showcases different functionalities of the StringBuffer class. It
performs operations such as checking buffer length and capacity, adjusting capacity, modifying
individual characters, appending and inserting text, reversing content, deleting or replacing segments,
and extracting substrings. Each section of the program highlights specific StringBuffer methods and
their effects, providing a practical understanding of how to use StringBuffer for efficient string
manipulations.
PROGRAM:
public class StrinBufferDemo {
public static void main(String[] args) {
// A. length() and capacity()
StringBuffer sb = new StringBuffer("Hello");
System.out.println("A. length() and capacity()");
System.out.println("Initial buffer: " + sb);
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());
System.out.println();
// B. ensureCapacity()
sb.ensureCapacity(30);
System.out.println("B. ensureCapacity()");
System.out.println("Updated capacity after ensureCapacity(30): " + sb.capacity());
System.out.println();
// C. setLength()
sb.setLength(2);
System.out.println("C. setLength()");
System.out.println("Buffer after setLength(2): " + sb);
System.out.println();
// E. getChars()
char[] target = new char[5];
Department of ISE, AIT Tumkur Page 18
Advanced java Lab - (BIS402)
sb.getChars(0, 2, target, 0);
System.out.println("E. getChars()");
System.out.print("Characters copied into target array: ");
System.out.println(target);
System.out.println();
// F. append()
sb.append(" World!");
System.out.println("F. append()");
System.out.println("Buffer after append: " + sb);
System.out.println();
// G. insert()
sb.insert(6, "Beautiful ");
System.out.println("G. insert()");
System.out.println("Buffer after insert: " + sb);
System.out.println();
// H. reverse()
sb.reverse();
System.out.println("H. reverse()");
System.out.println("Reversed buffer: " + sb);
System.out.println();
// J. replace()
sb.replace(5, 9, "was");
System.out.println("J. replace()");
System.out.println("Buffer after replace(5, 9, \"was\"): " + sb);
System.out.println();
// K. substring()
String substring = sb.substring(5);
System.out.println("K. substring()");
System.out.println("Substring from index 5: " + substring);
}
}
Input/Output:
B. ensureCapacity()
Updated capacity after ensureCapacity(30): 30
C. setLength()
Buffer after setLength(2): He
E. getChars()
Characters copied into target array: Hi
F. append()
Buffer after append: Hi World!
G. insert()
Buffer after insert: Hi Beautiful World!
H. reverse()
Reversed buffer: !dlroW lufituaeB iH
J. replace()
Buffer after replace(5, 9, "was"): dlroW wasH
K. substring()
Substring from index 5: WasH
Program 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.
AIM:
The aim of the EventDemo Java Swing application is to demonstrate event handling by creating a
simple graphical user interface (GUI) with two buttons ("Alpha" and "Beta"). The application shows
how to handle button click events and update a label's text based on which button was clicked
Definition:
This Swing application uses the JFrame container to create a window, with a FlowLayout manager to
arrange components. It features two JButton components ("Alpha" and "Beta") that trigger
ActionListener events when clicked. Each button updates a JLabel to display a corresponding
message ("Alpha was pressed" or "Beta was pressed"). The application initializes on the Event
Dispatch Thread to ensure thread safety in GUI operations.
PROGRAM
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
Output:
Program:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Servlet Program</title>
</head>
<body>
<form action ="Greeting " method ="post">
Enter username: <input type ="text" name ="username"/>
<input type = "submit" value ="submit">
<input type ="submit" value ="submit"/>
</form>
</body>
</html>
Greeting.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Greeting
*/
@WebServlet("/Greeting")
public class Greeting extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Output:
Program 9 A servlet program to display the name, USN, and total marks by accepting student
detail.
Aim: The aim of this Java Servlet program is to collect student details (name, USN, and total
marks) via an HTML form and display these details along with the calculated percentage on a web
page. The program processes user input submitted through the form and dynamically generates an
HTML response with the student's information and computed percentage.
Definition: A Java Servlet is a server-side component that handles HTTP requests and generates responses
for web applications. In this program, the servlet processes POST requests containing student information,
computes the percentage based on total marks, and returns an HTML page displaying the student's details
and computed percentage.
program:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Details </title>
</head>
<body>
<form action ="StudentDetails" method ="post">
Student name: <input type ="text" name ="name"/> <br/> <br/>
USN: <input type ="text" name ="usn"/> <br/> <br/>
Total Marks: <input type ="text" name ="marks"/> <br/> <br/>
<input type = "submit" value ="submit">
</form>
</body>
</html>
StudentDetails.java
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet implementation class StudentDetails
*/
public class StudentDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
Program 10 A Java program to create and read the cookie for the given cookie name as
“EMPID” and its value as “AN2356”.
Aim: The aim of this Java program is to demonstrate how to create, store, and read cookies in a web
application using servlets. Specifically, it sets a cookie named "EMPID" with the value "AN2356" and
then reads and displays the cookie’s name and value from the HTTP request.
Definition:
A Java Servlet is a server-side technology used to handle HTTP requests and responses in web
applications. In this program, the servlet creates a cookie with a specified name and value, adds it to
the HTTP response, and then retrieves and displays all cookies from the HTTP request. This illustrates
the basic operations of creating and managing cookies in a web environment.
Program:
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class CookieExample
*/
@WebServlet("/CookieExample")
public class CookieExample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CookieExample() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (cookies != null) {
for (Cookie c : cookies) {
String name = c.getName();
String value = c.getValue();
out.println("<p>Name: " + name + "</p>");
out.println("<p>Value: " + value + "</p>");
}
} else {
out.println("<p>No cookies found.</p>");
}
out.println("</body>");
out.println("</html>");
}
}
Output:
Name: EMPID
Value: AN2356
Program 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…).
Aim:
The aim of this Java program is to perform basic database operations on a MySQL database,
including inserting, retrieving, updating, and deleting student records. It demonstrates how to
connect to the database, execute SQL statements, and handle results and exceptions.
Definition This Java program uses JDBC (Java Database Connectivity) to interact with a
MySQL database, executing CRUD operations on a STUDENT_INFO table. It showcases the steps
to connect to a database, execute queries, and manage database resources, including handling
potential exceptions.
Program:
import java.sql.*;
// Database credentials
static final String USER = "username"; // Replace with your MySQL username
static final String PASS = "password"; // Replace with your MySQL password
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create a statement
System.out.println("Creating statement...");
stmt = conn.createStatement();
Output:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:527)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at StudentDatabaseExample.main(StudentDatabaseExample.java:16)
Goodbye!
Program 12 A program to design the Login page and validating the USER_ID and PASSWORD using
JSP and DataBase..
Aim: The aim of this JSP (JavaServer Pages) program is to create a simple web-based login page
where users can enter their credentials (User ID and Password). The login page is designed to send
these credentials to a JSP page for validation against stored records in a database. This setup
demonstrates basic user authentication by integrating JSP with a database to verify login information.
Definition:
This JSP program includes a login page (index.jsp) where users input their User ID and Password.
When the form is submitted, it sends the credentials to login.jsp using a POST request. The
login.jsp page will handle the authentication process by querying a database to verify if the
provided credentials match any stored records. This example illustrates the use of JSP for user
interface design and basic authentication logic, integrating with a database to validate user
credentials.
Program:
index.jsp: This is the login page where users enter their credentials.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="login.jsp" method="post">
<label for="userId">User ID:</label><br>
<input type="text" id="userId" name="userId"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Input/Output:
1. What is an ArrayList?
o An ArrayList is a resizable array implementation of the List interface in Java.
2. How do you create an ArrayList?
o ArrayList<String> al = new ArrayList<String>();
3. How do you add elements to an ArrayList?
o Use the add() method, e.g., al.add("A");
4. How do you insert an element at a specific index in an ArrayList?
o Use add(index, element); e.g., al.add(1, "A2");
5. How do you remove an element by value from an ArrayList?
o Use remove(element); e.g., al.remove("F");
6. How do you remove an element by index from an ArrayList?
o Use remove(index); e.g., al.remove(2);
7. How do you sort an ArrayList?
o Use Collections.sort(list);
8. What does the toArray() method do?
o Converts the ArrayList to an array.
9. How do you convert an ArrayList to an array?
o Use toArray(new String[list.size()]);
10. How can you sum elements of an ArrayList of Integers?
o Iterate and sum each element in a loop.
Answer:
The EventDemo class demonstrates basic event handling in Java Swing. It creates a graphical user interface
(GUI) with two buttons ("Alpha" and "Beta") and a label. When either button is clicked, the label's text is
updated to show which button was pressed. This illustrates how to handle button click events using
ActionListener.
Answer:
The ActionListener interface is used to handle action events generated by GUI components like buttons.
In this program, ActionListener is implemented using anonymous inner classes. When a button is clicked,
the actionPerformed method of the associated ActionListener is invoked, which updates the text of the
label accordingly.
Answer:
SwingUtilities.invokeLater ensures that the creation and manipulation of Swing components are
performed on the Event Dispatch Thread (EDT), which is the thread responsible for handling GUI updates
in Swing applications. This approach helps avoid thread-safety issues and ensures that the GUI is updated
correctly.
Answer:
The Greeting servlet processes HTTP POST requests from a form where users enter their username. It
retrieves the username from the request parameters, generates an HTML response with a personalized
greeting message, and sends it back to the browser.
Answer:
The servlet handles form data using the HttpServletRequest object's getParameter method, which
retrieves the value of the form field named "username". This value is then used to generate a personalized
greeting message that is included in the response sent back to the client.
Department of ISE, AIT Tumkur Page 38
Advanced java Lab - (BIS402)
3. What is the importance of setting the response content type to "text/html"?
Answer:
Setting the response content type to "text/html" informs the browser that the response contains HTML
content. This allows the browser to render the response correctly as a web page.
Answer:
The StudentDetails servlet collects student details (name, USN, and total marks) from an HTML form,
computes the percentage based on total marks, and generates an HTML response displaying the student's
information along with the calculated percentage.
Answer:
The percentage is calculated by dividing the total marks by the maximum possible marks (assumed to be
600) and then multiplying by 100 to get the percentage. This is done using the formula (total / 600.0) *
100.
Answer:
In the servlet, doPost handles form submissions and processes the data sent via POST requests. The doGet
method is also defined but not used in this context; it simply responds with the context path. Typically,
doPost is used for form data handling, while doGet handles requests that do not alter server state.
Answer:
The CookieExample servlet creates a cookie named "EMPID" with the value "AN2356" and adds it to the
HTTP response using response.addCookie(). It also reads cookies from the request using
request.getCookies() and displays their names and values.
Answer:
The response.addCookie() method is used to add cookies to the HTTP response. This allows the server to
send cookies to the client's browser, where they can be stored and sent back with subsequent requests.
Answer:
The StudentDatabaseExample class performs basic database operations including inserting a record into
the database, retrieving records, updating a record, and deleting a record. It demonstrates CRUD (Create,
Read, Update, Delete) operations using JDBC.
Answer:
The program uses JDBC to connect to the MySQL database and performs operations within a try block. It
handles SQL exceptions using a catch block and ensures that database resources like Statement and
Connection are closed in the finally block to prevent resource leaks.
3. What changes need to be made if the MySQL JDBC driver class name is incorrect?
Answer:
If the MySQL JDBC driver class name is incorrect, you need to update the driver class name to the correct
one. For newer versions of MySQL Connector/J, the driver class name is com.mysql.cj.jdbc.Driver.
Ensure that the JDBC driver JAR file is included in the classpath.
1. How does the index.jsp page interact with the login.jsp page?Answer:
The index.jsp page provides a form where users can enter their User ID and Password. When the form is
submitted, the data is sent to login.jsp using a POST request. The login.jsp page then processes this
data to authenticate the user against stored records in the database.
Answer:
JSP (JavaServer Pages) allows developers to create dynamic web content by embedding Java code in
HTML. It is used to generate dynamic web pages and handle server-side logic, such as processing form data
and interacting with databases.