0% found this document useful (0 votes)
9 views54 pages

Ajava Lab Manual

The document outlines a list of Java programming experiments focused on advanced concepts, including ArrayLists, sorting, user-defined classes, string manipulation, and servlet applications. Each program includes code examples and explanations of key Java concepts such as collections, interfaces, and string methods. Additionally, it features a section on viva questions related to the Java Collections Framework and string operations.

Uploaded by

sariyaanjum8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views54 pages

Ajava Lab Manual

The document outlines a list of Java programming experiments focused on advanced concepts, including ArrayLists, sorting, user-defined classes, string manipulation, and servlet applications. Each program includes code examples and explanations of key Java concepts such as collections, interfaces, and string methods. Additionally, it features a section on viva questions related to the Java Collections Framework and string operations.

Uploaded by

sariyaanjum8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Advanced Java BIS402

LIST OF PROGRAMS

[Link] Experiments

1. Implement a java program to demonstrate creating an Array List, adding elements,


removing elements, sorting elements of Array List. 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 storing user defined classes in collection.

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.
ADVANCED JAVA 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 to Array()
method.

PROGRAM

import [Link];

import [Link];

public class

ArrayListExample {

public static void main(String[] args) {

// Creating an ArrayList of String type

ArrayList<String> fruits = new

ArrayList<>();

// Adding elements to the

ArrayList [Link]("Apple");

[Link]("Banana");

[Link]("Cherry");

[Link]("Date");

// Displaying elements of the ArrayList

[Link]("Initial ArrayList: " + fruits);

// Removing an element from the ArrayList

[Link]("Date"); // removing by object

[Link](1); // removing by index


ADVANCED JAVA BIS402

(Banana)

// Displaying ArrayList after removal

[Link]("ArrayList after removing elements: "

+ fruits);

// Adding more elements

[Link]("Elderberry");
ADVANCED JAVA BIS402

[Link]("Fig");

// Sorting the ArrayList

[Link](fruits);

// Displaying the sorted ArrayList

[Link]("Sorted ArrayList: " +

fruits);

// Converting ArrayList to Array

String[] fruitArray = [Link](new String[0]);

// Displaying elements of Array

[Link]("Array

elements:"); for (String fruit :

fruitArray) {

[Link](fruit);

}
ADVANCED JAVA BIS402

OUTPUT
ADVANCED JAVA BIS402

VIVA

1. What is Collection in Java?


The term collection refers to a group of objects represented as one unit. Classes in the Java
collection class hierarchy are divided into two “root” interfaces: Collection ([Link])
and Map ([Link]).

2. What is a Framework in Java?


Frameworks are sets of classes and interfaces that provide a ready-made architecture. The
framework can be used in a variety of ways, such as by calling its methods, extending it, and
supplying “callbacks”, listeners, and other implementations.

3. What are the various interfaces used in Java Collections Framework?


Collections represent groups of objects known as elements. Egs of Iinterfaces are
• Collection interface
• List interface
• Set interface
• Queue interface
• Dequeue interface
• Map interface

4. What is ArrayList in Java?


ArrayList is a part of the Java collection framework and it is a class of [Link] package. It
provides us with dynamic arrays in Java.

5. What is the Difference between ArrayList and LinkedList in the java collection
framework?
Arraylist: This class uses a dynamic array to store the elements in it. With the introduction of
generics, this class supports the storage of all types of objects.
LinkedList: This class uses a doubly linked list to store the elements in it. Similar to the
ArrayList, this class also supports the storage of all types of objects.
Advanced Java 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.

PROGRAM

import
[Link];
import
[Link];
import
[Link];
import [Link];
import [Link];
public class
SortedMultiples {
public static void main(String[] args) {
int lowerBound = 1; // Minimum value of the
range int upperBound = 500; // Maximum
value of the range
int numNumbers = 100; // Number of random numbers to generate

// Generate and collect the numbers


List<Integer> numbers = generateRandomMultiples(lowerBound, upperBound,
numNumbers);

// Sort the numbers by the tens place


[Link](numbers, new
Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {

// Extract the tens digit and compare


return [Link](o1 / 10 % 10, o2 / 10 % 10);
}
}

// Print the sorted numbers


[Link]("Sorted numbers by tens
digit:"); for (Integer num : numbers) {
[Link](num);
Advanced Java BIS402

}
}

private static List<Integer> generateRandomMultiples(int lower, int upper, int


count) { List<Integer> multiples = new ArrayList<>();
Random random = new
Random(); while
([Link]() < count) {
int randomNum = [Link](upper - lower + 1) + lower;
// Ensure the number is a multiple
of 10 if (randomNum % 10 == 0)
{
Advanced Java BIS402

[Link](randomNum);
}
}
return multiples;
}
}

OUTPUT

VIVA

1. What are the methods present in List interface.


List interface extends collection interface. It includes new method.
Which are given below. void add(int index , E obj )
boolean addAll(int
index , E get(int
index )
int indexOf(Object obj )
int lastIndexOf(Object obj )
Advanced Java BIS402

ListIterator<E> listIterator( )
ListIterator<E> listIterator(int
index ) E remove(int index )
Advanced Java BIS402

E set(int index , E obj )


List<E> subList(int start , int end )

2. Explain Set Interface and set method.


The Set interface defines a set. It extends Collection and declares the behaviour of a collection
that does not allow duplicate elements.
Therefore, the add() method returns false if an attempt. Set is a generic interface that has this
declaration: interface Set<E>

3. Explain Comparator interface.


Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared. The Comparator interface defines two
methods: compare( ) and equals( ).

4. What are Legacy classes?


Early versions of [Link] did not include the
Collections Framework. Instead, it defined several classes and an interface that provided an ad
hoc method of storing objects.

5. Explain Vector class of Stack


Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only
defines the default constructor, which creates an empty stack.
Advanced Java BIS402

PROGRAM 3

Implement a java program to illustrate storing user defined classes in collection.

PROGRAM

import
[Link];
import [Link];
// Define the Book class with some
attributes class Book
{
private String title;
private String
author;
private int publicationYear;
// Constructor to initialize the Book object
public Book(String title, String author, int
publicationYear) { [Link] = title;
[Link] = author;
[Link] =
publicationYear;
}
// Getter methods for the
attributes public String
getTitle() {
return title;
}
public String getAuthor()
{ return author;
}
public int getPublicationYear()
{ return publicationYear;
}
// Overriding the toString method to display book details
@Override
public String toString()
{
return "Book {" +
"title='" + title +
'\'' +
", author='" + author + '\'' +
Advanced Java BIS402

", publicationYear=" +
publicationYear + '}';
}
}
public class Main
{
public static void main(String[] args)
{
// Create an ArrayList to store Book objects
List<Book> bookList = new ArrayList<>();
Advanced Java BIS402

// Adding books to the list


[Link](new Book("1984", "George Orwell", 1949));
[Link](new Book("Brave New World", "Aldous Huxley",
1932)); [Link](new Book("The Great Gatsby", "F. Scott
Fitzgerald", 1925));
// Displaying all books in the list using enhanced
for-loop for (Book book : bookList)
{
[Link](book);
} }}

OUTPUT

VIVA

1. Explain Dictionary class.


Dictionary is an abstract class that represents a key/value storage repository and operates much
like Map. Given a key and value, you can store the value in a Dictionary object.

2. Explain Properties Subclass


Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String.

3. Explain Linked HashMap


LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the
order in which they were inserted. This allows insertion-order iteration over the map.

4. Explain ArrayDeque
Advanced Java BIS402

Java SE 6 added the ArrayDeque class, which extends AbstractCollection and implements the
Deque interface. It adds no methods of its own. ArrayDeque creates a dynamic array and has no
capacity restrictions.

5. Explain TreeSet
TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection
that uses a tree for storage. Objects are stored in sorted, ascending order.
Advanced Java BIS402

PROGRAM 4

Implement a java program to illustrate the use of different types of string class
constructors.

PROGRAM

public class stringConstructors


{
public static void main(String[] args)
{
char[] charArray
={'H','e','l’,’l’,’o’,'W','o','r','l','d'}; byte[] ascii
={65,66,67,68,70,71,73};
String str = "Welcome";
String strl =new String("Java");
String str2 =new
String(charArray);
String str3 =new
String(charArray,3,3); String str4
=new String(ascii);
String str5 =new
String(ascii,2,3); String str6
=new String();
String str7 =new String(str);
[Link]("str : "+
str); [Link]("strl :
"+ strl);
[Link]("str2 : "+
str2); [Link]("str3
: "+ str3);
[Link]("str4 : "+
str4); [Link]("str5
: "+ str5);
[Link]("str6 : "+
str6); [Link]("str7
: "+ str7); str += " It is
beautiful";
[Link]("str : "+
str);
}
}
Advanced Java BIS402

OUTPUT
Advanced Java BIS402

VIVA

1. Explain toString() function


Every class implements toString( ) because it is defined by Object. However, the default
Implementation of toString() is sufficient.

2. Explain character extraction function charAt()


charAt( ) - To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method.

3. Explain character extraction function getChars( )


To extract more than one character at a time, you can use the getChars() method. Syntax void
getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

4. Explain character extraction function getBytes( )


This method is called getBytes( ), and it uses the default character-to-byte conversions provided
by the platform. Syntax: byte[ ] getBytes( )

5. Explain character extraction function toCharArray( )


If you want to convert all the characters in a String object into a character array, the easiest
way is to call toCharArray( ). It returns an array of characters for the entire string. It has this
general form: char[ ] toCharArray( )
Advanced Java BIS402

PROGRAM 5

Implement a java program to illustrate the use of different types of character extraction
,string comparison, string search and string modification methods.

PROGRAM

import [Link];
public class
StringMethods {
public static void main(String[]
args) { String str = "java world";
String str1 = "Java
world"; String str2 =
"java";
String str3 = "This is
August"; String result = "";
[Link]([Link]
(0));
[Link]([Link]
(1)); char[] destArray = new
char[20]; [Link](5, 10,
destArray, 0);
[Link](destArray
); byte b[]=[Link]();
for(int i=0;i<[Link];i++)
{ [Link](b[i]+" ");
}
[Link]();
char
ch[]=[Link]();
[Link](ch);
[Link]("Output after equals() "+[Link](str1));
[Link]("Output after equalsIgnoreCase()
"+[Link](str1)); [Link]("Output after == "+
(str==str1));
[Link]("Output after Compare str and str 1 ");
[Link]([Link](str1));//Positive value
[Link]("Output after Compare str 1 and str 2 ");
[Link]([Link](str2)); //negative value
[Link]("Index Of 'u' is "+[Link]('u')) ;
[Link]("Last Index Of 'u' is "+[Link]('u')) ;
[Link]("Index Of 'is' "+[Link]("is")) ;
[Link]("Last Index Of 'is' "+[Link]("is")) ;
[Link]("Index Of 'u' is "+[Link]('u',10)) ;
Advanced Java BIS402

[Link]("Last Index Of 'u' is


"+[Link]('u',10)) ; result=[Link](0,4);
[Link]("Output after substring extraction: " +result);
result=[Link](" is ");
result=[Link](str2);
[Link]("Output after Concat: "
+result); result=[Link]('i', 'a');
[Link]("Output after Replacing 'i' with 'a' :"+result);
[Link]("Output after trim() :"+" Hello ".trim());
Advanced Java BIS402

[Link]("Output after strip() :"+" \n Hello\t".strip());


}}

OUTPUT

VIVA

1. Explain equals( )
To compare two strings for equality, use equals( ). It has this general form: boolean
equals(Object str)

2. Explain equalsIgnoreCase( )
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it
compares two strings, it considers A-Z to be the same as a-z.

3. Explain regionMatches( )
The regionMatches() method compares a specific region inside a string with another specific
region in another string. There is an overloaded form that allows you to ignore case in such
comparisons.

4. Explain startsWith( ) and endsWith( )


Advanced Java BIS402

The startsWith( ) method determines whether a given String begins with a specified string.
endsWith( ) determines whether the String in question ends with a specified string.

5. Explain equals( ) Versus ==


The equals( ) method compares the characters inside a String [Link] == operator compares
two object references to see whether they refer to the same instance.
Advanced Java BIS402

PROGRAM 6

Implement a java program to illustrate the use of different types of String Buffer methods

PROGRAM

import
[Link];
public class Str
{
public static void main( String args[] )
{
StringBuffer s = new StringBuffer("Java is Object Oriented");
[Link]("\n Given String = "+s); // Will Print the
string [Link]("\n Length = "+[Link]() ); //total
characters [Link]("\n Length = "+[Link]() ); //
total allocated capacity [Link](14); // Sets the length and
destroy the remaining characters [Link]("\n After
setting length String = "+s ); [Link](0,'K'); // It will change
character at specified position [Link]("\n SetCharAt
String = "+s );
[Link](0,'C'
); int a = 007;
[Link](a); // It concatenates the other data type value
[Link]("\n Appended String = "+s );
[Link](6," truly"); // used to insert one string or char or object
[Link]("\n Inserted String = "+s );
[Link]();
[Link]("\n Reverse String =
"+s ); [Link]();
[Link](6,14); // used to delete sequence of character
[Link]("\n\n After deleting string="+s);
}}

OUTPUT
Advanced Java BIS402
Advanced Java BIS402

VIVA
1. Explain indexOf( ) and lastIndexOf( )
indexOf( ) Searches for the first occurrence of a character or substring. lastIndexOf( ) Searches
for the last occurrence of a character or substring.

2. Explain Substring( )
You can extract a substring using substring( ). It has two forms. The first is String substring(int
startIndex)

3. Explain concat( )
The replace( ) method has two forms. The first replaces all occurrences of one character in the
invoking string with another character.

4. Explain trim( )
The trim() method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed.

5. Explain Strip()
The method strip( ),which removes all whitespace characters (as defined by Java) from the
beginning and end of the invoking string and returns the result. Such whitespace characters
include, among others, spaces, tabs, carriage returns, and line feeds
Advanced Java 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.

PROGRAM

import [Link].*;
import
[Link].*;
import
[Link].*;
class EventDemo
{ JLabel jlab;
EventDemo() { // Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");// Specify FlowLayout for
the layout manager. [Link](new FlowLayout()); // Give the frame an
initial size.
[Link](220, 90);// Terminate the program when the user closes
the application.
[Link](JFrame.EXIT_ON_CLOSE); //
Make two buttons.
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta"); // Add action listener for
Alpha and Beta [Link](new ActionListener() {
public void actionPerformed(ActionEvent ae)
{ [Link]("Alpha was pressed.");
}
});
[Link](new
ActionListener() { public void
actionPerformed(ActionEvent ae)
Advanced Java BIS402

{ [Link]("Beta was pressed.");


}
});
// Add the buttons to the
content pane.
[Link](jbtnAlpha);
[Link](jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content
pane. [Link](jlab); //
Display the frame.
Advanced Java BIS402

[Link](true);
}
public static void main(String args[]) {
// Create the frame on the event
dispatching thread.
[Link](new
Runnable() { public void run() { new
EventDemo(); }
});
}}

OUTPUT

VIVA
1. Explain lightweight and heavyweight components
If native resources are used, they are called as heavyweight, else they are called lightweight.

2. What is Swing Pluggable Look and Feel


Possible to separate the look and feel of a component from the logic of the component.

3. What does MVC terminology correspond to?


-model corresponds to the state information
- view determines how the component is displayed
- controller determines how the component reacts to the user.
Advanced Java BIS402

4. What is a component?
A component is an independent visual control, such as a push button or slider.

5. What is a container?
A container is a special type of component that is designed to hold other components.
Advanced Java BIS402

PROGRAM 8

A program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.

PROGRAM

[Link]
import [Link].*;
import [Link];
import
[Link];
import
[Link];
public class Simple extends HttpServlet
{
public void doGet(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException
{
[Link]("text/
html") ; PrintWriter
out=[Link](); String
msg=[Link]("t1");
[Link]("hello "+msg+" how are you? ");
}
}

[Link]
<!DOCTYPE html>
<html>
<body>
<form action="Simple" >
<input type="text" name="t1" value="">
<input type="submit" value="submit">
</form>
</body>
</html>

OUTPUT
Advanced Java BIS402

VIVA

1. What is a Servlet?
Servlets are small programs that execute on the server side of a web connection.

2. What are advantages of Servlet?


Performance is better as they execute within web [Link] functionality of the Java class
libraries is available to a servlet.

3. What is the use of init() phase in servlet lifecycle?


The server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. Here initialization parameters to the servlet can be passed for
configuration.

4. What is the use of service() phase in servlet lifecycle?


The server then invokes the service( ) method of the [Link] method is called to process the
HTTP requests.

5. What is the use of destroy() phase in servlet lifecycle?


The server calls the destroy() method to relinquish any resources such as file handles.
Advanced Java BIS402

PROGRAM 9

A servlet program to display the name, USN, and total marks by accepting student detail

PROGRAM

[Link]

import [Link].*;
import [Link].*;
import
[Link].*;
public class Student extends HttpServlet
{
@Override
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
int
sno,s1,s2,s3,total;
String snm;
[Link]("text/
html"); PrintWriter
out=[Link]();
sno=[Link]([Link]("txtsno"));
snm=[Link]("txtnm");
s1=[Link]([Link]("txtsub1"));
s2=[Link]([Link]("txtsub2"));
s3=[Link]([Link]("txtsub3"));
total=s1+s2+s3;
[Link]("USN:
"+sno+"<br>");
[Link]("Name:
"+snm+"<br>");
[Link]("Mark 1:
"+s1+"<br>");
[Link]("Mark 2: "+s2+"<br>");
[Link]("Mark 3:
"+s3+"<br>");
[Link]("Total: "+total);
[Link]();
}
}
Advanced Java BIS402

[Link]

<!DOCTYPE html>
<html>
<body>
<form
action="Student">
<h3>Enter USN</h1>
<input type="text" name="txtsno" value="">
<h3>Enter Name</h1>
<input type="text" name="txtnm" value="">
<h3>Enter Mark 1</h1>
Advanced Java BIS402

<input type="text" name="txtsub1" value="">


<h3>Enter Mark 2</h1>
<input type="text" name="txtsub2" value="">

<h3>Enter Mark 3</h1>


<input type="text" name="txtsub3" value="">
<div align=center>
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

OUTPUT

VIVA
1. What does [Link] package consist of?
This package contains the classes and interfaces required to build servlets.

2. What is the use of the ServletRequest Interface?


The ServletRequest interface enables a servlet to obtain information about a client request.

3. What is the use of the ServletResponse Interface?


The ServletRequest interface enables a servlet to formulate a response for a client.

4. What is the use of GenericServlet class ?


The GenericServlet class provides implementations of the basic life cycle methods for a
Advanced Java BIS402

servlet. GenericServlet implements the Servlet and ServletConfig interfaces.

5. What is the use of HttpServletRequest interface?


The HttpServletRequest interface enables a servlet to obtain information about a client request
Advanced Java BIS402

PROGRAM 10

A Java program to create and read the cookie for the given cookie name as “EMPID” and
its value as “AN2356”.

PROGRAM

[Link]

<html>
<body>
<center>
<form name="Form1"
method="post"
action="AddCookieServlet"
>
<B>Enter a value for EMPID cookie:</B>
<input type=text name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>

[Link]

import
[Link];
import
[Link];
import
[Link];
import
[Link];
import
[Link];
import [Link].*;
//import [Link].*;
//import [Link].*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Get parameter from HTTP request. String data =
Advanced Java BIS402

[Link]("data"); // Create cookie.


Cookie cookie = new Cookie("EM", data); // Add cookie to HTTP
response. [Link](cookie); // Write output to browser.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>My Cookie has been set
to"); [Link](data);
[Link]();
}
}
Advanced Java BIS402

[Link]
import
[Link];
import
[Link];
import
[Link];
import
[Link];
import
[Link];
import [Link].*;
public class GetCookiesServlet extends
HttpServlet { public void
doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException { // Get cookies from header of HTTP
request. Cookie[] cookies = [Link](); // Display these cookies.
[Link]("text/html");
PrintWriter pw =
[Link]();
[Link]("<B>");
for(int i = 0; i < [Link]; i+
+) { String name =
cookies[i].getName(); String value
= cookies[i].getValue();
[Link]("name = " + name +"; value = " + value +"\n");
} [Link](); } }

OUTPUT

VIVA

1. Whatis a Cookie Class?


The Cookie class encapsulates a cookie.

2. Whatis a Cookie?
A cookie is stored on a client and contains state information. Cookies are valuable for tracking
Advanced Java BIS402
user activities.

3. What is a Cookie Constructor?


It’s a constructor used to create new cookies. AddCookie() method is used to add cookies.

4. What is JSP?
Java Server Pages (JSP) is a server-side program that is similar in design and functionality to a
Java servlet.

5. What is a Comment tag?


A comment tag opens with <%-- and closes with --%>, and is followed by a comment that
usually describes the functionality of statements that follow the comment tag.
Advanced Java 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…).

package JDBC;
import [Link].*;
import [Link].*;
public class JDBC
{
private Connection
Database; private Statement
DataRequest; private
ResultSet Results2; public
JDBC()
{ String url =
"jdbc:mysql://localhost:3306/studentdb"; String
userID = "root";
String password =
""; try {
[Link]( "[Link]");
Database = [Link](url,userID,password);
}
catch (ClassNotFoundException error)
{ [Link]("Unable to load the MySql Driver"
+ error); [Link](1); }
catch (SQLException error){
[Link]("Cannot connect to the database." +
error); [Link](2);}
try
{
while(true)
{
[Link]("1. Queries like:: create table/view,alter,drop,update and
delete"); [Link]("2. Quries like:: Insert");
[Link]("3. Queries like:: Selection/Calculation/Group
By/OrderBy/Join/Conditional Testing Query");
[Link]("4. Exit");
InputStreamReader isr = new
InputStreamReader([Link]) ; BufferedReader br = new
BufferedReader(isr) ; [Link]("Select your
choice");
int
Advanced Java BIS402

ch=[Link]([Link](
)); switch(ch)
{
case 1:
try
{
[Link]("Enter your
query"); String q1 = [Link]();
DataRequest = [Link]();
Advanced Java BIS402

[Link](q1);
[Link]("Query Executed
successfully"); [Link]();
}
catch(SQLException sqle)
{[Link](sqle);} break;
case 2:
try {
PreparedStatement
pst ;
[Link]("Enter your
query"); String q2 = [Link]();
pst=[Link](q2
); [Link]();
[Link]("Record inserted Successfully. ");
[Link]();
}
catch(SQLException e)
{[Link](e);} break;
case 3:
try
{
[Link]("\nEnter the query to be
executed\n"); String str=[Link]();
DataRequest=[Link]();
Results2=[Link](str);
DisplayResults(Results2);
[Link]();
}
catch(Exception e)
{[Link](e);} break;
case 4: [Link](0);
}
}
}
catch(IOException ioe1){[Link](ioe1);}
}
private void DisplayResults (ResultSet Results2) throws SQLException
{
ResultSetMetaData
rmd=[Link](); int
col=[Link]();
int count=1;
boolean
Advanced Java BIS402

b=[Link](); if(!
b)
{
[Link]("No Data Found");
}
else
{
do
{ [Link]("RECORD " +(count++)+" => ");
Advanced Java BIS402

for(int i=0;i<col;i++)
[Link]([Link](i+1)+"\t");
[Link]();
}
while([Link]());
}
}
public static void main(String[] args) { // TODO code
application logic here final JDBC sdb = new JDBC();
}
}

SQL

CREATE DATABASE
student_db; USE
student_db;
CREATE TABLE students (
id INT AUTO_INCREMENT
PRIMARY KEY, name
VARCHAR(100),
age INT,
grade CHAR(1)
);

//Insert a student record into the students table


INSERT INTO students (name, age, grade) VALUES ('John
Doe', 20, 'A'); INSERT INTO students (name, age, grade)
VALUES ('Jane Smith', 22, 'B'); INSERT INTO students (name,
age, grade) VALUES ('Emily Johnson', 21, 'C');

OUTPUT
Advanced Java BIS402

VIVA

1. What is JDBC?
The JDBC API defines Interfaces and classes for writing database applications in Java by
making database connections.

2. What does JDBC driver type 2 do?


Uses Java classes to generate platform-specific code for specific DBMS.

3. How is JDBC driver loaded?


Using [Link]() method, the JDBC driver is loaded.

4. How is Connection object created?


The [Link]() method is passed with URL of the database, the user ID
and password. The URL is a String object that contains the driver name and the name of the
database that is being accessed by the J2EE component.

5. How is statement object created?


The [Link]() method is used to create a Statement object
Advanced Java BIS402

PROGRAM 12

A program to design the Login page and validating the USER_ID and PASSWORD using
JSP and DataBase.

PROGRAM

[Link]

import
[Link];
import [Link];
import
[Link];
import
[Link];
import
[Link];
import [Link];
import [Link];
import
[Link];
import
[Link];
import [Link];
import
[Link];
import
[Link];
@WebServlet("/loginServlet")
public class LoginServlet extends
HttpServlet { private static final long
serialVersionUID = 1L;
// Database connection parameters (should ideally be stored in a
properties file) private static final String JDBC_URL =
"jdbc:mysql://localhost:3306/LOGIN"; private static final String
JDBC_USER = "root";
private static final String JDBC_PASSWORD = "123456";
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String user_id =
[Link]("user_id"); String
password = [Link]("password");
Advanced Java BIS402

Connection conn = null;


PreparedStatement pstmt =
null; ResultSet rs = null;
try {
// Load the database driver (this is optional for newer versions of JDBC)
[Link]("[Link]");
// Connect to the database
conn = [Link](JDBC_URL, JDBC_USER, JDBC_PASSWORD);
// Prepare SQL query to fetch user data
String sql = "SELECT * FROM users WHERE user_id = ? AND
password = ?"; pstmt = [Link](sql);
[Link](1,
user_id);
[Link](2,
password);
Advanced Java BIS402

// Execute the query


rs = [Link]();
// Check if user exists with entered
credentials if ([Link]()) {
// Valid credentials, redirect to success page
[Link]("[Link]");
} else {
// Invalid credentials, show error message
PrintWriter out = [Link]();
[Link]("<html><body><p>Invalid credentials. Please try
again.</p></body></html>");
}

} catch (SQLException
e) {
[Link]();
throw new ServletException("Database access error", e); // Better error handling
} catch (ClassNotFoundException e) {
[Link]();
throw new ServletException("JDBC Driver not found", e); // Better error handling
} finally {
// Close the resources in finally block to ensure they are
always closed try {
if (rs != null) [Link]();
if (pstmt != null)
[Link](); if (conn !=
null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
Advanced Java BIS402

</head>
<body>
<h2>Login</h2>
<form action="loginServlet" method="post">
<label for="user_id">User ID:</label>
<input type="text" id="user_id" name="user_id" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
Advanced Java BIS402

</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful!</h2>
<!-- Your success message or content here -->
</body>
</html>

SQL

CREATE DATABASE
lOGIN; USE LOGIN;
CREATE TABLE users (
user_id VARCHAR(50) PRIMARY KEY,
password VARCHAR(50)
);
select *from users;
select * from [Link];
INSERT INTO users (user_id, password)
VALUES ('user1', 'password1'),
('user2',

'password2');

select *from users;

OUTPUT
Advanced Java BIS402

Login Successful
Advanced Java BIS402

VIVA
1. How is the ResultSet object created?
ResultSet object is created using ResultSet class.

2. How is the JDBC connection terminated?


To terminate the connection, we use the close() method.

3. What is the executeQuery() method?


This method is used for returning one ResultSet object with rows, columns and metadata
.
4. What is the use of executeUpdate() method?
Executes queries that contain INSERT,UPDATE ,DELETE and DDL SQL statements. This
returns an integer indicating number of rows updated/deleted by the query.

5. What is PreparedStatement used for?


A SQL query can be precompiled and executed using PreparedStatement object.
Advanced Java BIS402

Mapping of Course Outcomes with POs & PSOs

Program
Program Outcomes(POs) Specific
CO Outcomes
(PSOs)
1 2 3 4 5 6 7 8 9 10 11 12 1 2
CO1 2 1 1 1 1 1 1
CO2 2 1 1 1 1 1 1
CO3 2 1 2 2 1 2 1
CO4 2 1 2 2 1 2 1 1
CO5 1
2 1 1 2 1 2 1
Average
Advanced Java BIS402

You might also like