Advance Java - BIS402 Lab Manual
Advance Java - BIS402 Lab Manual
2023-2024
ADVANCED JAVA
Laboratory Manual
BIS402
Compiled by:
Dr Veena R S (Associate Professor)
Prof. Ashwini R (Assistant Professor)
Prof. Namitha K V (Assistant Professor)
TABLE OF CONTENTS
SL.
Lab Experiments
No.
Implement a java program to demonstrate creating an ArrayList, adding elements,
removing elements, sorting elements of ArrayList. Also illustrate the use of toArray()
1. method.
Develop a program to read random numbers between a given range that are multiples of 2
2. and 5, sort the numbers according to tens place using comparator.
Implement a java program to illustrate the use of different types of string class constructors.
4.
5. Implement a java program to illustrate the use of different types of character extraction,
string comparison, string search and string modification methods.
Implement a java program to illustrate the use of different types of String Buffer methods
6.
.
8.
A program to display greeting message on the browser “Hello UserName”, “How
Are You?”, accept username from the client using servlet.
A servlet program to display the name, USN, and total marks by accepting
9.
student detail
A Java program to create and read the cookie for the given cookie name as
10.
“EMPID” and its value as “AN2356”.
Write a JAVA Program to insert data into Student DATA BASE and retrieve info
11.
based on particular queries(For example update, delete, search etc...).
A program to design the Login page and validating the USER_ID and PASSWORD
12.
using JSP and DataBase.Additional Lab Experiments
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT
(Affiliated to Visvesvaraya Technological University,Belagavi & Approved by AICTE,New Delhi) Opp.
Art of Living, Udayapura, Kanakapura Road, Bangalore – 560082 DEPARTMENT OF
INFORMATION SCIENCE & ENGINEERING
Accredited by NBA, New Delhi
To strive at creating the institution a center of highest caliber of learning, so as to create an overall
intellectual atmosphere with each deriving strength from the other to be the best of engineers, scientists
with management &design skills.
To serve its region, state, the nation and globally by preparing students to make
meaningful contributions in an increasing complex global society challenges.
To encourage, reflection on and evaluation of emerging needs and priorities with state of
art infrastructure at institution.
To support research and services establishing enhancements in technical, health, economic, human
and cultural development.
To establish inter disciplinary center of excellence, supporting/ promoting student’s implementation.
To increase the number of Doctorate holders to promote research culture on campus.
To establish IIPC, IPR, EDC, innovation cells with functional MOU’s supporting student’s quality
growth.
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT
(Affiliated to Visvesvaraya Technological University,Belagavi & Approved by AICTE,New Delhi) Opp.
Art of Living, Udayapura, Kanakapura Road, Bangalore – 560082 DEPARTMENT OF
INFORMATION SCIENCE & ENGINEERING
Accredited by NBA, New Delhi
QUALITY POLICY
(Affiliated to Visvesvaraya Technological University, Belagavi & Approved by AICTE, New Delhi)
Impart magnificent learning atmosphere establishing innovative practices among the students aiming to
strengthen their software application knowledge and technical skills.
M2: To nurture teamwork in order to transform individual as responsible leader and entrepreneur for
future trends.
M3: To inculcate research practices in teaching thus ensuring research blend among students.
M5: To inculcate the core information science engineering practices with hardware blend by providing
advanced laboratories.
PEO1: Graduates shall have successful careers as information science engineers and will be able to lead and
manage teams across the globe.
PEO2: Graduates shall be professional in engineering practice and shall demonstrate good problem solving,
communication skills and contribute to address societal issues.
PEO3: Graduates shall be pursuing distinctive education, entrepreneurship and research in an excellent
environment which helps in the process of life-long learning.
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT
(Affiliated to Visvesvaraya Technological University,Belagavi & Approved by AICTE,New Delhi) Opp. Art
of Living, Udayapura, Kanakapura Road, Bangalore – 560082 DEPARTMENT OF
INFORMATION SCIENCE & ENGINEERING
Accredited by NBA, New Delhi
PO3. 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 the public health and safety,
and the cultural, societal, and environmental considerations.
PO4. 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.
PO5. 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.
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 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 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.
PO10. Communication: Communicate effectively on complex engineering activities with the engineering community and
with society at large, such as, being able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions. PO11. 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.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage independent and life-long
learning in the broadest context of technological change.
\
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & ANAGEMENT
(Affiliated to Visvesvaraya Technological University,Belagavi & Approved by
AICTE,New Delhi) Opp. Art of Living, Udayapura, Kanakapura Road,
Bangalore- 560082
Course Outcomes
At the end of the course the student will be able to:
CO4 Implementation web based applications using Java servlets, JSP and JDBC to
build database applications
SL.
Lab Experiments
No.
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.
import java.util.ArrayList;
import java.util.Collections;
Output:
Java program demonstrating creating an ArrayList, adding elements, removing elements, sorting
elements of ArrayList, and using the toArray() method:
This program creates an ArrayList of strings, adds elements to it, sorts the elements, removes an
element, and then converts the ArrayList to an array using the 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.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Random;
@Override
System.out.println("Original list:");
System.out.println();
numbers.sort(new TensPlaceComparator());
Output:
Original list:
Sorted list based on tens place:
Java program that reads random numbers between a given range, filters out the numbers that are
multiples of 2 and 5, sorts the numbers according to their tens place using a custom comparator:
This program generates random numbers between a given range, filters out the numbers that are
multiples of 2 and 5, and then sorts these numbers according to their tens place using a custom
comparator (TensPlaceComparator).
3. Implement a java program to illustrate storing user defined classes in collection
import java.util.ArrayList;
class Person {
age) {
this.name = name;
this.age = age;
return name;
return age;
@Override
'}';
main(String[] args) {
Person objects
ArrayList<Person>
to the list
peopleList.add(new
Person("Alice", 30));
peopleList.add(new
Person("Bob", 25));
peopleList.add(new
Person("Charlie", 35));
the list
System.out.println("People
in the list:");
peopleList) {
System.out.println(person);
Output:
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=35}
Java program illustrating storing user-defined classes in a collection. In this example, we'll create a Person
In this program:
In the Main class, we create an ArrayList named peopleList to store Person objects.
Finally, we iterate over the peopleList and print out each Person object using their
toString() method.
4. Implement a java program to illustrate the use of different types of string class constructors
The most commonly used constructors of the String class are as follows:
: Java program that illustrates the use of different types of constructors available in the String class:
In this program
The char array constructor creates a string from the given character array.
The byte array constructor creates a string from the given byte array using the default
character encoding (UTF-8 in most cases).
The byte array constructor with specified encoding and length creates a string from a
subset of the byte array.
The StringBuilder constructor creates a string from the contents of the StringBuilder
object.
The StringBuffer constructor creates a string from the contents of the StringBuffer
object.
5. Implement a java program to illustrate the use of different types of character extraction, string
comparison, string search and string modification methods.
// String comparison
String str1 = "hello";
String str2 = "HELLO";
System.out.println("str1.equals(str2): " + str1.equals(str2));
System.out.println("str1.equalsIgnoreCase(str2): " + str1.equalsIgnoreCase(str2));
// String search
String sentence = "The quick brown fox jumps over the lazy dog";
boolean containsFox = sentence.contains("fox");
boolean startsWithThe = sentence.startsWith("The");
boolean endsWithDog = sentence.endsWith("dog");
int indexOfFox = sentence.indexOf("fox");
int lastIndexOfThe = sentence.lastIndexOf("The");
System.out.println("Contains 'fox': " + containsFox);
System.out.println("Starts with 'The': " + startsWithThe);
System.out.println("Ends with 'dog': " + endsWithDog);
System.out.println("Index of 'fox': " + indexOfFox);
System.out.println("Last index of 'The': " + lastIndexOfThe);
// String modification
String originalString = " Hello, World! ";
String trimmedString = originalString.trim();
String lowerCaseString = originalString.toLowerCase();
String upperCaseString = originalString.toUpperCase();
String replacedString = originalString.replace("World", "Universe");
String substring = originalString.substring(7, 12); // Extract substring from index 7 to 11
System.out.println("Trimmed string: \"" + trimmedString + "\"");
System.out.println("Lowercase string: \"" + lowerCaseString + "\"");
System.out.println("Uppercase string: \"" + upperCaseString + "\"");
System.out.println("Replaced string: \"" + replacedString + "\"");
System.out.println("Substring: \"" + substring + "\"");
}
}
Output:
First character: H
Last character: !
str1.equals(str2): false
str1.equalsIgnoreCase(str2): true
Contains 'fox': true
Starts with 'The': true
Ends with 'dog': true
Index of 'fox': 16
Last index of 'The': 0
Trimmed string: "Hello, World!"
Lowercase string: " hello, world! "
Uppercase string: " HELLO, WORLD! "
Replaced string: " Hello, Universe! "
Substring: "o, Wo"
// Append method
stringBuffer.append(" World");
System.out.println("After appending: " + stringBuffer);
// Insert method
stringBuffer.insert(6, ", ");
System.out.println("After inserting: " + stringBuffer);
// Delete method
stringBuffer.delete(5, 7);
System.out.println("After deleting: " + stringBuffer);
// Reverse method
stringBuffer.reverse();
System.out.println("After reversing: " + stringBuffer);
// Replace method
stringBuffer.replace(5, 11, "Java");
System.out.println("After replacing: " + stringBuffer);
// Length method
System.out.println("Length of the StringBuffer: " + stringBuffer.length());
// Capacity method
System.out.println("Capacity of the StringBuffer: " + stringBuffer.capacity());
// SetLength method
stringBuffer.setLength(5);
System.out.println("After setting length: " + stringBuffer);
// EnsureCapacity method
stringBuffer.ensureCapacity(30);
System.out.println("After ensuring capacity: " + stringBuffer);
// TrimToSize method
stringBuffer.trimToSize();
System.out.println("After trimming to size: " + stringBuffer);
}
}
Output:
After appending: Hello World
After inserting: Hello , World
After deleting: Hello World
After reversing: dlroW olleH
After replacing: dlroWJava
Length of the StringBuffer: 9
Capacity of the StringBuffer: 21
After setting length: dlroW
After ensuring capacity: dlroW
After trimming to size: dlroW
append(String str): Appends the specified string to the end of the StringBuffer.
insert(int offset, String str): Inserts the specified string at the specified position.
delete(int start, int end): Deletes characters from the start index to the end - 1
index.
replace(int start, int end, String str): Replaces characters from the start index to
the end - 1 index with the specified string.
length(): Returns the length (number of characters) of the StringBuffer .
setLength(int newLength): Sets the length of the StringBuffer to the specified new length.
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() {
// Create a new JFrame container.
});
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
ServletException,IOException
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
String msg=req.getParameter("t1");
HTML code
<html>
<body>
</form>
</body>
</html>
OUTPUT:
hello CEC how are you
To create a servlet that accepts a username from the client and displays a greeting message on
the browser, you'll need to follow these steps:
This configuration maps the GreetingServlet class to the /greet URL pattern.
Now, when a client sends a request to /greet with a username parameter, the servlet will extract
the username, construct the greeting message, and send it back as the response.
9. A servlet program to display the name, USN, and total marks by accepting student detail
<html>
<body>
<fieldset>
<fieldset>
</fieldset>
</fieldset>
<div align=center>
</div>
</form>
</body>
</html>
This servlet expects the client to send a POST request with three parameters: name, usn
(University Serial Number), and totalMarks. It extracts these parameters from the request,
constructs an HTML response containing the student details, and sends it back to the client.
Make sure to map this servlet in the web.xml deployment descriptor or use annotations for
servlet mapping depending on your servlet container version. Also, ensure that your HTML form
submits the data using the POST method to the URL pattern that corresponds to this servlet.
10. A Java program to create and read the cookie for the given cookie name as “EMPID” and its value as
“AN2356”.
out.println(“name=”+Name);
out.println(“Value=”+Value);
}
Output:
name= EMPID
Value=AN2356
This program creates a CookieManager, gets its CookieStore, creates a cookie with the name "EMPID"
and value "12345", adds the cookie to the store, and then prints all the cookies in the store. Finally, it reads the
cookie with the name "EMPID" from the store and prints its name and value.
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…).
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
// Create a statement
System.out.println("Creating statement...");
stmt = conn.createStatement();
// Insert data into the database
String sql = "INSERT INTO STUDENT_INFO (ID, NAME, AGE) VALUES (101, 'John', 20)";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("ID");
// Display values
rs.close();
stmt.executeUpdate(updateSql);
stmt.executeUpdate(deleteSql);
// Clean-up environment
stmt.close();
conn.close();
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
} // Nothing we can do
try {
se.printStackTrace();
System.out.println("Goodbye!");
}
Output:
java.lang.ClassNotFoundException:
com.mysql.jdbc.Driver
at
java.base/jdk.internal.loader.BuiltinCla
ssLoader.loadClass(BuiltinClassLoader.j
ava:581)
at
java.base/jdk.internal.loader.ClassLoad
ers$AppClassLoader.loadClass(ClassLo
aders.java:178)
at
java.base/java.lang.ClassLoader.loadCl
ass(ClassLoader.java:527)
at
java.base/java.lang.Class.forName0(Na
tive Method)
at
java.base/java.lang.Class.forName(Clas
s.java:315)
at
StudentDatabaseExample.main(Studen
tDatabaseExample.java:16)
Goodbye!
This program connects to a MySQL database named "STUDENT" running on localhost. You need to replace
"username" and "password" with your MySQL username and password. The program inserts data into a
table named "STUDENT_INFO", retrieves data from it, updates a record, and then deletes the record. Make sure
you have the MySQL JDBC driver (mysql-connector-java.jar) in your classpath. Adjust the SQL queries
and table structure as per your database schema.
12. A program to design the Login page and validating the USER_ID and PASSWORD using JSP and
DataBase
1. 1. 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>
OUTPUT:
In this example:
The login.jsp file contains the login form with fields for user ID and password.
The LoginServlet.java servlet receives the form data, validates the user ID and
password against hardcoded values, and redirects to the appropriate page
based on the validation result.