0% found this document useful (0 votes)
77 views

Advanced Java Lab Manual Upd

adavanced java lab manual according to new syllabus

Uploaded by

VEENA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Advanced Java Lab Manual Upd

adavanced java lab manual according to new syllabus

Uploaded by

VEENA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Akshaya Institute of Technology

(Affiliated to VTU,Belgum & Approved by AICTE,NewDelhi)


Lingapura,Obalapura Post, Koratagere Road,Tumakuru-572106

Department of Computer Science & Information


Science Engineering
LABORATORYMANUAL
ADVACED JAVA LAB
(BIS402)
B.E,IV Semester,
Information Science & Engineering
[Asper Choice BasedCredit System(CBCS)scheme]

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

Teaching-Learning Process (General Instructions)


These are sample Strategies; that teachers can use to accelerate the attainment of the various course outcomes.
1. Lecturer method (L) does not mean only the traditional lecture method, but different types of
teaching methods may be adopted to achieve the outcomes.
2. Promote collaborative learning (Group Learning) in the class.
3. Pose at least three HOT (Higher Order Thinking) questions in the class to stimulate critical
thinking.
4. Incorporate Problem-Based Learning (PBL) to foster students' analytical skills and develop their
ability to evaluate, generalize, and analyze information rather than merely recalling it.
5. Introduce Topics in manifold representations.
6. Demonstrate ways to solve the same problem and encourage the students to come up with their
own creative solutions.
7. Discuss application of every concept to solve the real world problems.

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.

Text Book 1: Ch. 20

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

Assessment Details (both CIE and SEE)


The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the SEE
minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be deemed to
have satisfied the academic requirements and earned the credits allotted to each subject/ course if the student
secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation)
and SEE (Semester End Examination) taken together.

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.

Web links and Video Lectures (e-Resources):


1. https://nptel.ac.in/courses/106/105/106105191/
2. https://nptel.ac.in/courses/106/105/106105225/
3. https://youtu.be/qGMxs-PbFPk

Activity Based Learning (Suggested Activities in Class)/ Practical Based learning


Demonstration of simple projects on database connectivity
Group assignment for J2EE projects

@# 16032024
Advanced java Lab - (BIS402)

INDEX
PAGE
S.NO EXPERIMENTS
NO

Implement a java program to demonstrate creating an ArrayList, adding elements,


1. removing elements, sorting elements of ArrayList. Also illustrate the use of toArray() 2
method
Develop a program to read random numbers between a given range that are 6
2.
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.
8
Implement a java program to illustrate the use of different types of string class
4. 10
constructors.
Implement a java program to illustrate the use of different types of character
5. 12
extraction, string comparison, string search and string modification methods.
Implement a java program to illustrate the use of different types of StringBuffer 18
6.
methods.
Demonstrate a swing event handling application that creates 2 buttons Alpha and 21
7.
Beta and displays the text “Alpha pressed” when alpha button is clicked and “Beta
pressed” when beta button is clicked.
A program to display greeting message on the browser “Hello UserName”, “How Are 24
8.
You?”, accept username from the client using servlet.
A servlet program to display the name, USN, and total marks by accepting student
detail 27
9.
A Java program to create and read the cookie for the given cookie name as “EMPID”
and its value as “AN2356”.
10 30
Write a JAVA Program to insert data into Student DATA BASE and retrieve info
based on particular queries(For example update, delete, search etc…).
11. 32
A program to design the Login page and validating the USER_ID and PASSWORD 35
12
using JSP and DataBase.
II SAMPLE VIVA QUESTIONS AND ANSWERS 36-38

Department of ISE, AIT Tumkur Page 1


Advanced java Lab - (BIS402)

Program 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

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.*;

public class ArrayListDemo {

public static void main(String[] args) {

// Create an ArrayList of Strings.

ArrayList<String> al = new ArrayList<String>();

System.out.println("Initial size of al: " + al.size());

// Add elements to the ArrayList.


al.add("C");
al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

al.add(1, "A2");

Department of ISE, AIT Tumkur Page 2


Advanced java Lab - (BIS402)
System.out.println("Size of al after additions: " + al.size());

// Display the ArrayList.

System.out.println("Contents of al: " + al);

// Remove elements from the ArrayList.

al.remove("F");

al.remove(2);

System.out.println("Size of al after deletions: " + al.size());

System.out.println("Contents of al: " + al);

// Sort the ArrayList.


Collections.sort(al);
System.out.println("Contents of al after sorting: " + al);

// Convert the ArrayList into an array.

String[] array = new String[al.size()];

array = al.toArray(array);

// Display the array.

System.out.println("Contents of array: " + Arrays.toString(array));

// Create an ArrayList of Integers.

ArrayList<Integer> intList = new ArrayList<Integer>();

// Add elements to the ArrayList.

intList.add(1);
intList.add(2);

Department of ISE, AIT Tumkur Page 3


Advanced java Lab - (BIS402)
intList.add(3);

intList.add(4);

System.out.println("Contents of intList: " + intList);

// Convert the ArrayList into an array.

Integer[] intArray = new Integer[intList.size()];

intArray = intList.toArray(intArray);

// Sum the array.

int sum = 0;
for (int i : intArray) sum += i;

System.out.println("Sum is: " + sum);

Department of ISE, AIT Tumkur Page 4


Advanced java Lab - (BIS402)

Input/Output:

Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 6
Contents of al: [C, A2, A, E, B, D]
Contents of al after sorting: [A, A2, B, C, D, E]
Contents of array: [A, A2, B, C, D, E]
Contents of intList: [1, 2, 3, 4]
Sum is: 10

Department of ISE, AIT Tumkur Page 5


Advanced java Lab - (BIS402)

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;

public class RandomNumberSorter {


public static void main(String[] args) {
int lowerBound = 10;
int upperBound = 100;
int numberOfRandomNumbers = 20;

// Generate random numbers within the specified range


List<Integer> randomNumbers = generateRandomNumbers(lowerBound, upperBound,
numberOfRandomNumbers);
System.out.println("Generated Numbers: " + randomNumbers);

// Filter numbers that are multiples of both 2 and 5


List<Integer> filteredNumbers = filterMultiplesOf2And5(randomNumbers);
System.out.println("Filtered Numbers: " + filteredNumbers);

// Sort the filtered numbers based on the tens place


Collections.sort(filteredNumbers, new TensPlaceComparator());
System.out.println("Sorted Numbers: " + filteredNumbers);
}

// Generate random numbers within a specified range


public static List<Integer> generateRandomNumbers(int lowerBound, int upperBound, int count) {

Department of ISE, AIT Tumkur Page 6


Advanced java Lab - (BIS402)
Random random = new Random();
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < count; i++) {
int randomNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
numbers.add(randomNumber);
}
return numbers;
}

// Filter numbers that are multiples of both 2 and 5


public static List<Integer> filterMultiplesOf2And5(List<Integer> numbers) {
List<Integer> filteredNumbers = new ArrayList<>();
for (int number : numbers) {
if (number % 2 == 0 && number % 5 == 0) {
filteredNumbers.add(number);
}
}
return filteredNumbers;
}

// Comparator to sort numbers based on the tens place


public static class TensPlaceComparator implements Comparator<Integer> {

public int compare(Integer o1, Integer o2) {


int tensPlace1 = (o1 / 10) % 10;
int tensPlace2 = (o2 / 10) % 10;
return Integer.compare(tensPlace1, tensPlace2);
}
}
}

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]

Department of ISE, AIT Tumkur Page 7


Advanced java Lab - (BIS402)

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;

// Constructor to initialize the Address object


Address(String n, String s, String c, String st, String cd) {
name = n;
street = s;
city = c;
state = st;
code = cd;
}

// Overriding toString() method to provide string representation of Address


@Override
public String toString() {
return name + "\n" + street + "\n" + city + " " + state + " " + 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<>();

// Adding Address objects to the LinkedList


ml.add(new Address("J.W. West", "11 Oak Ave", "Urbana", "IL", "61801"));
ml.add(new Address("Ralph Baker", "1142 Maple Lane", "Mahomet", "IL", "61853"));
ml.add(new Address("Tom Carlton", "867 Elm St", "Champaign", "IL", "61820"));

// Printing each Address object from the LinkedList


for (Address element : ml) {
System.out.println(element + "\n");
}
}
}
Input/Output:
J.W. West
11 Oak Ave
Urbana IL 61801

Ralph Baker
1142 Maple Lane
Mahomet IL 61853

Tom Carlton
867 Elm St
Champaign IL 61820

Department of ISE, AIT Tumkur Page 9


Advanced java Lab - (BIS402)

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) {

// 1. Using default constructor to create an empty string


String s1 = new String();
System.out.println("Empty String: \"" + s1 + "\"");

// 2. Using char array constructor


char[] chars = {'a', 'b', 'c'};
String s2 = new String(chars);
System.out.println("String from char array: \"" + s2 + "\"");

// 3. Using char array with start index and length


char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
String s3 = new String(charArray, 2, 3);
System.out.println("Substring from char array: \"" + s3 + "\"");

// 4. Using another String object


String s4 = new String(s2);
System.out.println("String from another String: \"" + s4 + "\"");

// 5. Using byte array constructor


byte[] ascii = {65, 66, 67, 68, 69, 70}; // ASCII values for 'A' to 'F'
String s5 = new String(ascii);
System.out.println("String from byte array: \"" + s5 + "\"");

Department of ISE, AIT Tumkur Page 10


Advanced java Lab - (BIS402)
// 6. Using byte array with start index and length
String s6 = new String(ascii, 2, 3);
System.out.println("Substring from byte array: \"" + s6 + "\"");

// 7. Using StringBuffer constructor


StringBuffer stringBuffer = new StringBuffer("Hello");
String s7 = new String(stringBuffer);
System.out.println("String from StringBuffer: \"" + s7 + "\"");

// 8. Using Unicode code points array


int[] codePoints = {97, 98, 99, 100, 101}; // Unicode code points for 'a' to 'e'
String s8 = new String(codePoints, 0, codePoints.length);
System.out.println("String from Unicode code points: \"" + s8 + "\"");

// 9. Using StringBuilder constructor (same as StringBuffer in this context)


StringBuilder stringBuilder = new StringBuilder("World");
String s9 = new String(stringBuilder);
System.out.println("String from StringBuilder: \"" + s9 + "\"");

// Additional: String literal and concatenation


String s10 = "Hello" + " " + "World";
System.out.println("Concatenated String: \"" + s10 + "\"");
}
}

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"

Department of ISE, AIT Tumkur Page 11


Advanced java Lab - (BIS402)

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");

// Section 1: Character Extraction Methods


System.out.println("1. Implementation of character extraction methods:");
charAtExample();
substringExample();
toCharArrayExample();
System.out.println();

// Section 2: String Comparison Methods


System.out.println("2. Implementation of String comparison methods:");
equalsExample();
regionMatchesExample();
startsWithEndsWithExample();
equalsVsEqualsOperator();
compareToExample();
System.out.println();

// Section 3: Searching a String


System.out.println("3. Implementation of searching a string:");
indexOfExample();
Department of ISE, AIT Tumkur Page 12
Advanced java Lab - (BIS402)
System.out.println();

// Section 4: Modifying a String


System.out.println("4. Implementation of modifying a string:");
concatExample();
replaceExample();
trimExample();
}

// Section 1: Character Extraction Methods


public static void charAtExample() {
// Example of charAt()
String str = "Hello, World!";
char charAtIndex4 = str.charAt(4);
String substringFrom10To12 = str.substring(10, 13); // Note: endIndex is exclusive
System.out.println("Character at index 4 in \"" + str + "\": " + charAtIndex4);
System.out.println("Characters extracted from index 10 to 12: " + substringFrom10To12);
}

public static void substringExample() {


// Example of substring()
String str = "This is a test. This is, too.";
String search = "is";
String replace = "was";
String result = "";
int index;
System.out.println("Example of substring():");
do {
System.out.println(str);
index = str.indexOf(search);
if (index != -1) {
result = str.substring(0, index);
result = result + replace;
result = result + str.substring(index + search.length());
str = result;
}
} while (index != -1);
System.out.println();
}

public static void toCharArrayExample() {


// Example of toCharArray()
String str = "Hello";
char[] charArray = str.toCharArray();
System.out.print("Character array for \"" + str + "\": ");
for (char ch : charArray) {
System.out.print(ch + " ");
}

Department of ISE, AIT Tumkur Page 13


Advanced java Lab - (BIS402)
System.out.println();
}

// Section 2: String Comparison Methods


public static void equalsExample() {
// Example of equals() and equalsIgnoreCase()
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println("a) Example of equals() and equalsIgnoreCase()");
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
System.out.println();
}

public static void regionMatchesExample() {


// Example of regionMatches()
String str1 = "Hello, World!";
String str2 = "World";
boolean regionMatches = str1.regionMatches(true, 7, str2, 0, 5); // Ignore case, from index 7, compare
with str2 from index 0 for 5 characters
System.out.println("b) Example of regionMatches()");
System.out.println("Region matches from index 7: " + regionMatches);
System.out.println();
}

public static void startsWithEndsWithExample() {


// Example of startsWith() and endsWith()
String str = "Hello, World!";
System.out.println("c) Example of startsWith() and endsWith()");
System.out.println("Starts with \"Hello\": " + str.startsWith("Hello"));
System.out.println("Ends with \"World!\": " + str.endsWith("World!"));
System.out.println();
}

public static void equalsVsEqualsOperator() {


// Example of equals() vs ==
String s1 = "Hello";
String s2 = new String(s1);
System.out.println("d) Example of equals() vs ==");
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
System.out.println();
}

Department of ISE, AIT Tumkur Page 14


Advanced java Lab - (BIS402)
public static void compareToExample() {
// Example of compareTo()
String[] arr = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid",
"of", "their", "country" };
bubbleSort(arr);
System.out.println("e) Example of compareTo()");
System.out.println("Sorted array:");
for (String str : arr) {
System.out.print(str + " ");
}
System.out.println();
System.out.println();
}

// Bubble sort for compareTo() demonstration


public static void bubbleSort(String[] arr) {
int n = arr.length;
String temp;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1].compareTo(arr[j]) > 0) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}

// Section 3: Searching a String


public static void indexOfExample() {
// Example of indexOf() and lastIndexOf()
String s = "Now is the time for all good men to come to the aid of their country.";
System.out.println("Example of indexOf() and lastIndexOf():");
System.out.println("First index of \"Java\": " + s.indexOf("Java"));
System.out.println("Last index of \"Java\": " + s.lastIndexOf("Java"));
System.out.println();
}

// Section 4: Modifying a String


public static void concatExample() {
// Example of concat()
String s1 = "Hello";
String s2 = s1.concat(" World");
System.out.println("a) Example of concat()");
System.out.println("Concatenated string: " + s2);
System.out.println();
}

Department of ISE, AIT Tumkur Page 15


Advanced java Lab - (BIS402)

public static void replaceExample() {


// Example of replace()
String s = "Hello".replace('l', 'w');
System.out.println("b) Example of replace()");
System.out.println("Replaced string: " + s);
System.out.println();
}

public static void trimExample() {


// Example of trim()
String s = " Hello World ".trim();
System.out.println("c) Example of trim()");
System.out.println("Trimmed string: \"" + s + "\"");
System.out.println();
}
}

Output:
Implementing Java program to illustrate different types of string operations.

1. Implementation of character extraction methods:


Character at index 4 in "Hello, World!": o
Characters extracted from index 10 to 12: Wor

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.

Character array for "Hello": H e l l o

2. Implementation of String comparison methods:


a) Example of equals() and equalsIgnoreCase()
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

b) Example of regionMatches()
Region matches from index 7: true

Department of ISE, AIT Tumkur Page 16


Advanced java Lab - (BIS402)

c) Example of startsWith() and endsWith()


Starts with "Hello": true
Ends with "World!": 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

3. Implementation of searching a string:


Example of indexOf() and lastIndexOf():
First index of "Java": -1
Last index of "Java": -1

4. Implementation of modifying a string:


a) Example of concat()
Concatenated string: Hello World

b) Example of replace()
Replaced string: Hewwo

c) Example of trim()
Trimmed string: "Hello World"

Department of ISE, AIT Tumkur Page 17


Advanced java Lab - (BIS402)

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();

// D. charAt() and setCharAt()


System.out.println("D. charAt() and setCharAt()");
System.out.println("Character at index 1: " + sb.charAt(1));
sb.setCharAt(1, 'i');
System.out.println("Buffer after setting charAt(1) to 'i': " + 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();

// I. delete() and deleteCharAt()


sb.delete(8, 17);
System.out.println("I. delete() and deleteCharAt()");
System.out.println("Buffer after delete(8, 17): " + sb);
sb.deleteCharAt(0);
System.out.println("Buffer after deleteCharAt(0): " + 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);
}
}

Department of ISE, AIT Tumkur Page 19


Advanced java Lab - (BIS402)

Input/Output:

A. length() and capacity()


Initial buffer: Hello
Length: 5
Capacity: 21

B. ensureCapacity()
Updated capacity after ensureCapacity(30): 30

C. setLength()
Buffer after setLength(2): He

D. charAt() and setCharAt()


Character at index 1: e
Buffer after setting charAt(1) to 'i': Hi

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

I. delete() and deleteCharAt()


Buffer after delete(8, 17): !dlroW iH
Buffer after deleteCharAt(0): dlroW iH

J. replace()
Buffer after replace(5, 9, "was"): dlroW wasH

K. substring()
Substring from index 5: WasH

Department of ISE, AIT Tumkur Page 20


Advanced java Lab - (BIS402)

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 class EventDemo {


JLabel jlab;

public EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.


jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.


JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");

// Add action listener for Alpha.


jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});
Department of ISE, AIT Tumkur Page 21
Advanced java Lab - (BIS402)

// Add action listener for Beta.


jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});

// Add the buttons to the content pane.


jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);

// Create a text-based label.


jlab = new JLabel("Press a button.");

// Add the label to the content pane.


jfrm.add(jlab);

// Display the frame.


jfrm.setVisible(true);
}

public static void main(String[] args) {


// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}

Output:

Department of ISE, AIT Tumkur Page 22


Advanced java Lab - (BIS402)

Department of ISE, AIT Tumkur Page 23


Advanced java Lab - (BIS402)

Program 8 A program to display greeting message on the browser “Hello UserName”,


“How Are You?”, accept username from the client using servlet.
AIM: The aim of this Java Servlet program is to create a web application that greets
users by their provided username. Users enter their username in an HTML form, which is
then sent to a servlet. The servlet processes the input and returns a personalized greeting
message displayed in the browser.
Definition:
A Java Servlet is a server-side component that handles HTTP requests and generates
responses in a web application. It extends server capabilities by processing user input,
managing business logic, and delivering dynamic content. In this context, the servlet
processes form data and returns an HTML response with a personalized greeting.

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()

Department of ISE, AIT Tumkur Page 24


Advanced java Lab - (BIS402)
*/
public Greeting() {
super();

// TODO Auto-generated constructor stub


}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {

// TODO Auto-generated method stub


String username=request.getParameter("username");
response.setContentType("text/html");
java.io.PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> Greeting Response </title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Hello,"+username+"<h1>,How are you? ");

Department of ISE, AIT Tumkur Page 25


Advanced java Lab - (BIS402)
out.println("</body>");
out.println("</html>");
}

Output:

Department of ISE, AIT Tumkur Page 26


Advanced java Lab - (BIS402)

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.

Department of ISE, AIT Tumkur Page 27


Advanced java Lab - (BIS402)
*/
public StudentDetails() {

// TODO Auto-generated constructor stub


}
/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

// TODO Auto-generated method stub


doGet(request, response);
String name= request.getParameter("name");
String usn = request.getParameter("usn");
int total=Integer.parseInt(request.getParameter("marks"));
double percentage=(total/600.0)*100;
response.setContentType("text/html");

Department of ISE, AIT Tumkur Page 28


Advanced java Lab - (BIS402)
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> Student marks </title>");
out.println("</head>");
out.println("<body>");
out.println("<h2> Student details </h2>");
out.println("<p> Name :"+name + " </p>");
out.println("<p> USN :"+usn + " </p>");
out.println("<p> tOTAL Marks :"+total + " </p>");
out.println("<p> Percentage :"+percentage + " </p>");
out.println("</body>");
out.println("</html>");
}
}
Output:

Department of ISE, AIT Tumkur Page 29


Advanced java Lab - (BIS402)

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();

// Create a cookie with name "EMPID" and value "AN2356"


Cookie cookie = new Cookie("EMPID", "AN2356");
// Add the cookie to the response
Department of ISE, AIT Tumkur Page 30
Advanced java Lab - (BIS402)
response.addCookie(cookie);

// Read cookies from the request


Cookie[] cookies = request.getCookies();

// Display the cookies' names and values


out.println("<html>");
out.println("<head>");
out.println("<title>Cookie Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Cookies</h2>");

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

Department of ISE, AIT Tumkur Page 31


Advanced java Lab - (BIS402)

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.*;

public class StudentDatabaseExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // Updated driver class name
static final String DB_URL = "jdbc:mysql://localhost/STUDENT"; // Database URL

// Database credentials
static final String USER = "username"; // Replace with your MySQL username
static final String PASS = "password"; // Replace with your MySQL password

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

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();

// Insert data into the database


String sql = "INSERT INTO STUDENT_INFO (ID, NAME, AGE) VALUES (101, 'John', 20)";
stmt.executeUpdate(sql);
System.out.println("Data inserted successfully!");

// Retrieve data from the database


sql = "SELECT ID, NAME, AGE FROM STUDENT_INFO";
ResultSet rs = stmt.executeQuery(sql);
Department of ISE, AIT Tumkur Page 32
Advanced java Lab - (BIS402)
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("ID");
String name = rs.getString("NAME");
int age = rs.getInt("AGE");
// Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();

// Update data in the database


String updateSql = "UPDATE STUDENT_INFO SET AGE = 21 WHERE ID = 101";
stmt.executeUpdate(updateSql);
System.out.println("Data updated successfully!");

// Delete data from the database


String deleteSql = "DELETE FROM STUDENT_INFO WHERE ID = 101";
stmt.executeUpdate(deleteSql);
System.out.println("Data deleted successfully!");

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Finally block used to close resources
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
// Nothing we can do
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

Department of ISE, AIT Tumkur Page 33


Advanced java Lab - (BIS402)

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!

Department of ISE, AIT Tumkur Page 34


Advanced java Lab - (BIS402)

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:

Department of ISE, AIT Tumkur Page 35


Advanced java Lab - (BIS402)

II) Sample Viva Questions and Answers

Program 1: ArrayList Operations

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.

Program 2: Random Number Filtering and Sorting

11. How do you generate random numbers within a range?


o Use Random.nextInt(upper - lower + 1) + lower;
12. How do you filter numbers that are multiples of 2 and 5?
o Check if number % 2 == 0 && number % 5 == 0;
13. How do you sort numbers based on the tens place?
o Use a custom comparator that compares the tens place values.
14. What is a custom comparator?
o A class implementing the Comparator interface with a custom compare method.
15. How do you use a custom comparator with Collections.sort()?
o Pass the custom comparator to Collections.sort(list, comparator);

Program 3: User-Defined Classes in Collections

16. How do you create a user-defined class?


o Define a class with attributes and methods.
17. How do you store objects of a user-defined class in a collection?
o Use collections like LinkedList<Address>.
18. How do you add objects to a LinkedList?
o Use add(object); e.g., ml.add(new Address(...));
19. How do you print objects from a LinkedList?

Department of ISE, AIT Tumkur Page 36


Advanced java Lab - (BIS402)
o Iterate over the list and print each object.
20. What is the purpose of the toString() method in a user-defined class?
o It provides a string representation of the object.

Program 4: String Constructors

21. How do you create an empty string?


o Use new String();
22. How do you create a string from a character array?
o Use new String(charArray);
23. How do you create a string from a byte array?
o Use new String(byteArray);
24. How do you create a string from a StringBuffer?
o Use new String(stringBuffer);
25. How do you create a string from Unicode code points?
o Use new String(codePoints, offset, count);

Program 5: String Operations

26. How do you extract a character from a string?


o Use charAt(index);
27. How do you find a substring within a string?
o Use substring(startIndex, endIndex);
28. How do you compare two strings for equality?
o Use equals(otherString);
29. How do you find the index of a substring within a string?
o Use indexOf(substring);
30. How do you replace characters in a string?
o Use replace(oldChar, newChar);

Program 6: StringBuffer Methods

31. How do you check the length of a StringBuffer?


o Use length();
32. How do you ensure a minimum capacity in a StringBuffer?
o Use ensureCapacity(minCapacity);
33. How do you set the length of a StringBuffer?
o Use setLength(newLength);
34. How do you get a character at a specific index in a StringBuffer?
o Use charAt(index);
35. How do you append text to a StringBuffer?
o Use append(text);
36. How do you insert text into a StringBuffer?
o Use insert(index, text);
37. How do you reverse the content of a StringBuffer?
o Use reverse();
38. How do you delete a portion of a StringBuffer?
o Use delete(startIndex, endIndex);
39. How do you replace a portion of a StringBuffer?

Department of ISE, AIT Tumkur Page 37


Advanced java Lab - (BIS402)
o Use replace(startIndex, endIndex, replacement);
40. How do you extract a substring from a StringBuffer?
o Use substring(startIndex, endIndex);

Program 7: Swing Event Handling

1. What is the purpose of the EventDemo class in Program 7?

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.

2. How does the ActionListener work in this Swing application?

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.

3. Why is SwingUtilities.invokeLater used in the main method?

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.

Program 8: Greeting Servlet

1. What is the role of the Greeting servlet in Program 8?

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.

2. How does the servlet handle form data?

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.

Program 9: Student Details Servlet

1. What operations does the StudentDetails servlet perform?

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.

2. How does the servlet calculate the 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.

3. What is the purpose of doGet and doPost methods in this servlet?

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.

Program 10: Cookie Example

1. How does the CookieExample servlet manage cookies?

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.

2. What is the significance of the response.addCookie() method?

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.

3. What does request.getCookies() return?

Department of ISE, AIT Tumkur Page 39


Advanced java Lab - (BIS402)
Answer:
request.getCookies() returns an array of Cookie objects sent by the client's browser with the current
request. If no cookies are present, it returns null.

Program 11: Student Database Operations

1. What are the primary operations performed in the StudentDatabaseExample class?

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.

2. How does the program handle database connection and exceptions?

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.

Program 12: JSP Login Page

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.

2. What role does JSP play in web application development?

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.

3. How is user authentication performed in this JSP example?Answer:


In this JSP example, user authentication would typically involve querying the database to check if the
provided credentials match any stored records. The login.jsp page would contain Java code to connect to
the database, execute a query, and verify the user's credentials.

Department of ISE, AIT Tumkur Page 40

You might also like