BIS402(JAVA) Programs_AMC
BIS402(JAVA) Programs_AMC
AIM: To implement creating of ArrayList, adding elements, removing elements, sorting elements of
ArrayList using Java Programming.
PROGRAM:
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo
{
public static void main(String[] args)
{
// Creating an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// Adding elements to the ArrayList
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
arrayList.add("Mango");
arrayList.add("Grapes");
// Displaying elements of the ArrayList
System.out.println("ArrayList elements: " + arrayList);
// Removing an element from the ArrayList
arrayList.remove("Orange");
System.out.println("After removing Orange: " + arrayList);
// Sorting elements of the ArrayList
Collections.sort(arrayList);
System.out.println("After sorting: " + arrayList);
// Using toArray() method to convert ArrayList to array
String[] array = arrayList.toArray(new String[0]);
// Displaying elements of the array
System.out.print("Array elements: ");
OUTPUT
ArrayList elements: [Apple, Banana, Orange, Mango, Grapes]
After removing Orange: [Apple, Banana, Mango, Grapes]
After sorting: [Apple, Banana, Grapes, Mango]
Array elements: Apple Banana Grapes Mango
RESULT
This program creates an ArrayList of Strings, adds elements to it, removes an element, sorts the elements,
and finally 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.
AIM: To implement a java 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 interface.
PROGRAM
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
OUTPUT
Random Numbers:
100 70 100 50 50 90 50 80 10 100
RESULT
This program generates random numbers between a given range (`minRange` to `maxRange`) that are
multiples of both 2 and 5. Then it sorts these numbers according to the tens place using a custom
comparator (`NumberComparator`). Finally, it prints both the randomly generated numbers and the sorted
numbers.
RESULT
This Program creates the user defined class for storing and manipulation of data using List.
4. Implement a java program to illustrate the use of different types of string class constructors.
AIM: To implement a java program to illustrate the use of different types of string class constructors.
PROGRAM
public class StringConstructorsDemo {
public static void main(String[] args) {
// Using String literal
String str1 = "Hello, World!";
System.out.println("String literal: " + str1);
// Using char array
char[] charArray = {'J', 'a', 'v', 'a'};
String str2 = new String(charArray);
System.out.println("String from char array: " + str2);
// Using part of char array
String str3 = new String(charArray, 1, 2);
System.out.println("String from part of char array: " + str3);
// Using byte array
byte[] byteArray = {65, 66, 67, 68}; // ASCII values for A, B, C, D
String str4 = new String(byteArray);
System.out.println("String from byte array: " + str4);
// Using part of byte array
String str5 = new String(byteArray, 1, 2);
System.out.println("String from part of byte array: " + str5);
// Using another String object
String str6 = new String(str1);
System.out.println("String from another String object: " + str6);
// Using StringBuilder
StringBuilder sb = new StringBuilder("Hello, StringBuilder!");
String str7 = new String(sb);
System.out.println("String from StringBuilder: " + str7);
}
}
OUTPUT
String literal: Hello, World!
String from char array: Java
String from part of char array: av
String from byte array: ABCD
String from part of byte array: BC
String from another String object: Hello, World!
String from StringBuilder: Hello, StringBuilder!
RESULT
This program demonstrates how different `String` constructors can be used to create strings from various
sources such as character arrays, byte arrays, other strings, and `StringBuilder` objects.
5. Implement a java program to illustrate the use of different types of character extraction, string
comparison, string search and string modification methods.
AIM: To implement a different types of character extraction, string comparison, string search and string
modification methods using Java programs.
PROGRAM
public class StringMethodsDemo {
public static void main(String[] args) {
String str = "Hello, World!";
// Character Extraction (charAt)
char ch1 = str.charAt(0);
System.out.println("Character at index 0: " + ch1);
// getChars
char[] charArray = new char[5];
str.getChars(7, 12, charArray, 0);
System.out.println("Characters from index 7 to 11: " + new String(charArray));
// String Comparison
String str2 = "Hello, World!";
String str3 = "hello, world!";
// equals
boolean isEqual = str.equals(str2);
System.out.println("str equals str2: " + isEqual);
// equalsIgnoreCase
boolean isEqualIgnoreCase = str.equalsIgnoreCase(str3);
System.out.println("str equalsIgnoreCase str3: " + isEqualIgnoreCase);
// compareTo
int compareToResult = str.compareTo(str3);
System.out.println("str compareTo str3: " + compareToResult);
// String Search
// indexOf
int index1 = str.indexOf('o');
System.out.println("Index of first 'o': " + index1);
// lastIndexOf
int index2 = str.lastIndexOf('o');
System.out.println("Index of last 'o': " + index2);
// contains
boolean contains = str.contains("World");
System.out.println("str contains 'World': " + contains);
// startsWith
boolean startsWith = str.startsWith("Hello");
System.out.println("str starts with 'Hello': " + startsWith);
// endsWith
boolean endsWith = str.endsWith("!");
System.out.println("str ends with '!': " + endsWith);
// String Modification
// substring
String substr = str.substring(7, 12);
System.out.println("Substring from index 7 to 11: " + substr);
// concat
String str4 = str.concat(" How are you?");
System.out.println("Concatenated string: " + str4);
// replace
String replacedStr = str.replace("World", "Java");
System.out.println("Replaced 'World' with 'Java': " + replacedStr);
// toLowerCase
String lowerStr = str.toLowerCase();
System.out.println("Lowercase string: " + lowerStr);
// toUpperCase
String upperStr = str.toUpperCase();
System.out.println("Uppercase string: " + upperStr);
// trim
String str5 = " Hello, World! ";
String trimmedStr = str5.trim();
OUTPUT
Character at index 0: H
Characters from index 7 to 11: World
str equals str2: true
str equalsIgnoreCase str3: true
str compareTo str3: -32
Index of first 'o': 4
Index of last 'o': 8
str contains 'World': true
str starts with 'Hello': true
str ends with '!': true
Substring from index 7 to 11: World
Concatenated string: Hello, World! How are you?
Replaced 'World' with 'Java': Hello, Java!
Lowercase string: hello, world!
Uppercase string: HELLO, WORLD!
Trimmed string: 'Hello, World!'
RESULT
This program illustrates the use of various methods for extracting characters from strings, comparing
strings, searching within strings, and modifying strings. Each method's result is printed to the console to
demonstrate its functionality.
6. Implement a java program to illustrate the use of different types of StringBuffer methods
AIM: To implement the use of different types of StringBuffer methods using Java Programming.
PROGRAM
public class StringBufferExample
{
public static void main(String[] args)
{
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");
// 1. append() method
System.out.println("1. append() method:");
sb.append(" World");
System.out.println("After append: " + sb); // Hello World
// 2. insert() method
System.out.println("\n2. insert() method:");
sb.insert(5, " Java");
System.out.println("After insert: " + sb); // Hello Java World
// 3. replace() method
System.out.println("\n3. replace() method:");
sb.replace(6, 10, "C++");
System.out.println("After replace: " + sb); // Hello C++ World
// 4. delete() method
System.out.println("\n4. delete() method:");
sb.delete(5, 9);
System.out.println("After delete: " + sb); // Hello World
// 5. reverse() method
System.out.println("\n5. reverse() method:");
sb.reverse();
System.out.println("After reverse: " + sb); // dlroW olleH
// 6. capacity() method
System.out.println("\n6. capacity() method:");
System.out.println("Capacity: " + sb.capacity());
// 7. ensureCapacity() method
System.out.println("\n7. ensureCapacity() method:");
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50): " + sb.capacity()); // 50
// 8. setLength() method
System.out.println("\n8. setLength() method:");
sb.setLength(5);
System.out.println("After setLength(5): " + sb); // dlroW
// 9. charAt() method
System.out.println("\n9. charAt() method:");
char ch = sb.charAt(2);
System.out.println("Character at index 2: " + ch); // r
OUTPUT
1. append() method:
After append: Hello World
2. insert() method:
After insert: Hello Java World
3. replace() method:
After replace: Hello C++ World
4. delete() method:
After delete: Hello World
5. reverse() method:
After reverse: dlroW olleH
6. capacity() method:
Capacity: 27
7. ensureCapacity() method:
Capacity after ensureCapacity(50): 50
8. setLength() method:
After setLength(5): dlroW
9. charAt() method:
Character at index 2: r
RESULT
This program demonstrates various useful methods of the `StringBuffer` class in Java, showcasing how
each method manipulates the string buffer in different ways.
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: To implement an 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 using Java Programming.
PROGRAM
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonEventDemo extends JFrame {
private JButton alphaButton;
private JButton betaButton;
private JLabel displayLabel;
public ButtonEventDemo() {
// Create the buttons
alphaButton = new JButton("Alpha");
betaButton = new JButton("Beta");
OUTPUT
RESULT
This program created a simple GUI with two buttons that display corresponding messages when clicked
using Swing Components.
8. A program to display greeting message on the browser “Hello UserName”, “How Are You?”,
accept username from the client using servlet.
AIM: To implement a program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.
PROGRAM
Program8.html file
<!DOCTYPE html>
<html>
<head>
<title>Greetings Form</title>
</head>
<body>
<form action="Greetings" method="post">
Enter the UserName: <br>
<input type="text" name="username"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Greetings.java File
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
OUTPUT
RESULT
Implemented a Servlet program to display the name, along with Hell username, How are you? ,by
accepting Username through an HTML form. Assuming that the servlet handles the details using a
doPost method for receiving form data securely.
9. A servlet program to display the name, USN, and total marks by accepting student detail.
AIM: To implement a servlet program to display the name, USN, and total marks by accepting student
detail.
PROGRAM
Students.html file
<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="Students" method="post">
Name: <br>
<input type="text" name="name"><br><br>
USN:<br>
<input type="text" name="usn"><br><br>
Marks 1:<br>
<input type="number" name="marks1"><br><br>
Marks 2: <br>
<input type="number" name="marks2" ><br><br>
Marks 3:<br>
<input type="number" name="marks3" ><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Students.java File
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Retrieve student details from request parameters
String name = request.getParameter("name");
String usn = request.getParameter("usn");
int marks1 = Integer.parseInt(request.getParameter("marks1"));
int marks2 = Integer.parseInt(request.getParameter("marks2"));
int marks3 = Integer.parseInt(request.getParameter("marks3"));
// Calculate total marks
int totalMarks = marks1 + marks2 + marks3;
double per = (totalMarks/600.0)*100.0;
java.io.PrintWriter out=reponse.getWriter();
// Display the student details and total marks
out.println("<html><body>");
out.println ("<h2>Student Details:</h2>");
out.println ("<p>Name: " + name + "</p>");
out.println ("<p>USN: " + usn + "</p>");
out.println ("<p>Total Marks: " + totalMarks + "</p>");
out.println ("<p>Total Marks: " + totalMarks + "</p>");
out.println ("</body></html>");
}
}
OUTPUT
Run the Students.html file and input the following below details.
Student Details:
Name: John Doe
USN: 123456789
Total Marks: 255
RESULT
Implemented a Servlet program to display the name, USN, and total marks by accepting student
details through an HTML form. Assuming that the servlet handles the details using a doPost method
for receiving form data securely
10. A Java program to create and read the cookie for the given cookie name as “EMPID” and its
value as “AN2356”.
AIM: To implement a Java program to create and read the cookie for the given cookie name as “EMPID”
and its value as “AN2356”.
PROGRAM
import java.util.*;
import jakarta.servlet.http.Cookie;
public class Pgm10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of Cookie Emp ID");
String cv=sc.nextLine();
sc.close();
Cookie c=new Cookie("EMPID",cv);
System.out.println("Cookie Name"+c.getName());
System.out.println("Cookie Value"+c.getValue());
}
}
OUTPUT
RESULT
To create and read a cookie named "EMPID" with the value "AN2356" in Java, we'll create a servlet that
demonstrates both creating the cookie and reading its 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…).
AIM: To implement a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries.
PROGRAM
STEP 1: Set Up MySQL DataBase
Install MYSQL.
Create a database named student_database using a MYSQL client or command line interface.
CREATE DATABASE student_database;
Create a table named Student with the Specified columns (id,first_name, last_name. age,
department) as described.
CREATE TABLE Student(
id INT AUTO_INCREMENT PRIMARY_KEY,
first_name VARCHAR(50);
last_name VARCHAR(50);
age INT,
dept VARCHAR(50);
);
STEP 2: Set up Eclipse Project
Open Eclipse IDE.
Create a new Java Project : Go to “File”>”New”>Java Project. Enter a project name and click
“Finish”.
STEP 3: Add Jar File
Add MYSQL JDBC driver jar file to the project.
Once the JAR file is downloaded, Open Eclipse.
Right-click on your Java project in the Package Explorer.
Select “Build Path” > “Configure Build Path”.
In the “Libraries” tab, click on the “Add External JARs” button.
Navigate to the location where you downloaded the MYSQL JDBC driver JAR files, Select it and
click “Open”.
Click “Apply and Close” to save the changes.
STEP 4: JAVA Program.
Import java.sql.*;
Public class StudentDatabaseEx
{
Private static final String JDBC_URL=”jdbc:mysql://localhost:3306/student_database”;
Private static final String USERNAME=”root”;
Private static final String PASSWORD=”root”;
Public static void main(String args[])
{
try{
//Step 1: Establishing a Connection to the Database.
try((Connection con=DriverManager.getConnection(JDBC_URL,
USERNAME, PASSWORD)){
System.out.println(“Connected to the Database”);
//Step 2:Inserting data into Student Table
insertStudent(con,”Ram”,”Kumar”,24,”ISE”);
//Step 3: Updating data in Student Table
updateStudent(con,1,”Kumar”,”Ram”,26,”CSE”);
//Step 4: Deleting data from Student Table.
deleteStudent(con,”Ram”);
//Step 5: Searching data in Student Table.
searchStudent(con,”Ram”);
//Step 6: Displaying all records in Student Table
displayAllStudents(con);
}
}
Catch(SQLException e)
{
System.out.println(“SQLException:” +e.getmessage());
System.out.println(“SQLState:” +e.getSQLState());
System.out.println(“Vendor Error:” +e.getErrorCode ());
}
}
//method to insert data into Student Table
Private static void insertStudent(Connection con, String firstName, String lastName, int age,
String dept) throws SQLException {
try(Statement stmt=con.createStatement();
ResultSet resultset = Statement.executeQuery(selectQuery)){
while(resultset.next()){
System.out.println(“ID:”+resultset.getInt(“id”));
System.out.println(“First Name:”+resultset.getString(“first_name”));
System.out.println(“Last Name:”+resultset.getString(“last_name”));
System.out.println(“Age:”+resultset.getInt(“age”));
System.out.println(“Department:”+resultset.getString(“dept”));
System.out.println(“-------------------------------------------------");
}
}
}
OUTPUT
Connected to the Database.
A new student record was inserted successfully!
Student record with ID 1 was updated successfully!
Student record with ID 1 was deleted successfully!
No student found with first Name: Pankaj
Connected to the Database
A new Student record was inserted Successfully!
Student Found:
ID: 2;
First Name: Pankaj
Last Name: Kumar
Age: 25
Department: ISE
----------------------------------------------------------------------------
ID: 3;
First Name: Rahul
Last Name: Sharma
Age: 30
Department: ISE
12. A program to design the Login page and validating the USER_ID and PASSWORD using JSP
and DataBase.
AIM: To design the Login page and validating the USER_ID and PASSWORD using JSP and DataBase.
PROGRAM
STEP 1: Set Up Dynamic Web Project.
1. Open Eclipse IDE.
2. Go to “File”>”New”>”Dynamic web project”.
3. Enter a project name and click “Next”.
4. Choose the target runtime (Apache tomcat server) and click “Next”.
5. Choose the default configuration for the web.xml deployment descriptor and click “Finish”.
6. Right-click on the java project in the package Explorer.
7. Select “build-path”>”Configure Build Path.
8. In the Libraries tab click on the “Add External JARS” button.
STEP 2: Create JSP Files
1. Right click on the web content directory in the project explorer.
2. Go to “New”>File.
3. Enter a file name with a.jsp extension and click Finish.
4. Write your JSP code in the created file.
STEP 3: Set up MYSQL Database:
1. Create a MYSQL database/
2. Create a table to store user credentials for user_id and password,
CREATE DATABASE user_database;
USE user_database;
CREATE TABLE users(
User_id VARCHAR(50) PRIMARY KEY,
Password VARCHAR(50)
);
STEP 4: Create a Login Page (login.jsp):
1. Create a JSP file named login.jsp
2. Design a login form with fields for user Id and password.
3. Submit the form to JSP page for validation.
<%@page language=”java” contentType=”text/html”%>
<html>
<head>
<title>Program 12</title>
</head>
<body>
<form action=”validate.jsp”method=”post”>
User ID : <input type=”text” name=”uname”> <br>
Password:>input type=”password” name=”pwd”><br>
<input type=”submit” value=”Login”>
</form>
</body>
</html>
STEP 5: Validate User credentials (validate.jsp)
<%@page language=”java” contentType=”text.html”%>
<%@page import=”java.sql.*”%>
<html>
<head>
<title>Login Validation</title>
</head>
<body>
<%
//Retrieve user_id and password from the login form
String user_id=request.getParameter(“user_is”);
String pwd=request.getParameter(“pwd”);
//JDBC URL username and password of MYSQL server.
String jdbcURL=”jdbc:mysql://localhost:3306/users_database”;
String dbUser=”root”;
String dbPassword=”root”;
Connection con=null;
preparedStatement stmt=null;
ResultSet rs=null;
try{
//Establish connection to the database
Class.forName(“com.mysql.cj.jdbc.Driver”)
Con=DriverManager.getConnection(jdbcURL,dbUser,dbPassword);
//Prepare SQL query to select user by user id and password
String sql =”SELECT * FROM users WHERE user_id=” AND password=?”;
stmt=con.prepareStatement(sql);
stmt.getString(1,user_id);
stmt.getString(2,password);
resultset=stmt.executeQuer();
if(resultset.next()){
response.sendRedirect(“success,jsp?user_id”+user_id);
} else {
response.sendRedirect(“error.jsp”);
}
}catch(SQLException | ClassNotFoundException e){
e.printStacktrace();
out.println(“Error Connecting to the database”);
} finally {
if(resultSet !=null) {
try {
resultSet.close();
} catch(SQLException e) {
e.printStacktrace();
}
}
if (stmt ! = null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStacktrace();
}
}
if (con ! = null) {
try {
con.close();
} catch (SQLException e) {
e.printStacktrace();
}
}
}
%>
STEP 6 Create Success and Error Pages
1. Create JSP pages for success (success.jsp)
OUTPUT