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

Advanced Java Lab Manual

The document outlines the syllabus for an Advanced Java course (BIS402) at Jain Institute of Technology, detailing the vision and mission of the institution and department, program specific outcomes, educational objectives, and program outcomes. It includes sample Java programs demonstrating various concepts such as ArrayLists, comparators, user-defined classes, string manipulation, and StringBuffer methods. The document is prepared by Dr. Azizkhan F Pathan, Associate Professor in the Department of Information Science and Engineering.

Uploaded by

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

Advanced Java Lab Manual

The document outlines the syllabus for an Advanced Java course (BIS402) at Jain Institute of Technology, detailing the vision and mission of the institution and department, program specific outcomes, educational objectives, and program outcomes. It includes sample Java programs demonstrating various concepts such as ArrayLists, comparators, user-defined classes, string manipulation, and StringBuffer methods. The document is prepared by Dr. Azizkhan F Pathan, Associate Professor in the Department of Information Science and Engineering.

Uploaded by

Nayana Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

JAIN INSTITUTE OF TECHNOLOGY

Davanagere, Karnataka-570003

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

“ADVANCED JAVA”

(BIS402)

As per VTU Syllabus

PREPARED BY:

Dr. AZIZKHAN F PATHAN


Associate Professor

Department of Information Science & Engineering

Jain Institute of Technology, Davanagere


Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

Vision and Mission of the Institution


Vision of the Institute:

Technical manpower development to build professionally excellent, globally competitive,

socially responsible engineers and entrepreneurs with human values.

Mission of the Institute:

To provide quality education through innovation in teaching to create


M1
technologically competent engineers.
To achieve excellence in research and development to advance science and
M2
technology to the ever changing needs of society.
To create outstanding professionals by facilitating state of the art platform capable
M3
of working in multi-cultural environment.
To produce quality engineers with high ethical standards and
M4
professionalism.
Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

Vision & Mission of the Program

Vision of the Department:

To develop professionally excellent, socially responsible Information Science Engineers and


Entrepreneurs through Teaching, Research & Development and Cognitive skills with human
eminence.

Mission of the Department:

To promote the development of skilled professionals through strong


M1
foundations and experiential learning.

To foster research and entrepreneurship by innovative solutions and research-


M2
driven education.
To support social responsibility, ethical conduct, nurturing a culture of
M3
integrity, and empathy by fostering a compassionate global community.
Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

Program Specific Outcomes

A graduate of the Information Science and Engineering Program will demonstrate:

PSOs Program Specific Outcomes

Effective Information Management: Ability to design and manage databases,


PSO1 information repositories, and content management systems for ensuring data integrity,
accessibility, and usability.
Software Development and Entrepreneurship for Successful Career: Analyze,
PSO2 design and develop data-driven software systems and applications that harness the
power of emerging computing technologies for successful career.

Program Educational Objectives


Professional Excellence
PEO1 Graduates of the program will be able to demonstrate professional excellence to
address real-world challenges in the field of technology.
Innovation and Entrepreneurship
PEO2 Graduates of the program will be able to exhibit a strong inclination towards
innovation and entrepreneurship.
Social Responsibility and Ethics
PEO3 The graduates will be socially responsible and will demonstrate ethical leadership in
their professional and personal lives.
Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

Program Outcomes
Information Science & Engineering Graduates will be able to:

POs Program Outcomes

PO1 Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and computer science and engineering to the solution of
complex engineering problems.

PO2 Problem analysis: Identify, formulate, review research literature, and analyze
complex computer engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.

PO3 Design/development of solutions: Design solutions for complex computer


engineering problems and design system components or processes that meet the
specified needs with appropriate consideration for the public health and safety, and
the cultural, societal, and environmental considerations.

PO4 Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern computer engineering and IT tools including prediction and modeling to
complex computer engineering activities with an understanding of the limitations.

PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional
computer engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the computer engineering practice.

PO9 Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.

PO10 Communication: Communicate effectively on complex computer engineering


activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.

PO11 Project management and finance: Demonstrate knowledge and understanding of


the computer engineering and management principles and apply these to one’s own
work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
ADVANCED JAVA BIS402

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


removing elements, sorting elements of ArrayList. Also illustrate the use of toArray()
method.

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListDemo {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();

fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");

System.out.println("ArrayList after adding elements: " + fruits);

fruits.remove("Banana");
System.out.println("ArrayList after removing 'Banana': " + fruits);

Collections.sort(fruits);
System.out.println("ArrayList after sorting: " + fruits);

String[] fruitsArray = new String[fruits.size()];


fruits.toArray(fruitsArray);

System.out.println("Array obtained from ArrayList:");


for (String fruit : fruitsArray) {
System.out.println(fruit);
}
}
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 1


ADVANCED JAVA BIS402

Output:
ArrayList after adding elements: [Apple, Banana, Orange, Mango]
ArrayList after removing 'Banana': [Apple, Orange, Mango]
ArrayList after sorting: [Apple, Mango, Orange]
Array obtained from ArrayList:
Apple
Mango
Orange

2. Develop a program to read random numbers between a given range that are
multiples of 2 and 5, sort the numbers according to tens place using comparator.
import java.util.*;

class TensPlaceComparator implements Comparator<Integer> {


public int compare(Integer num1, Integer num2) {
int tensPlace1 = (num1 % 100) / 10;
int tensPlace2 = (num2 % 100) / 10;
return tensPlace1 - tensPlace2;
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower bound of the range: ");


int lowerBound = scanner.nextInt();

System.out.print("Enter the upper bound of the range: ");


int upperBound = scanner.nextInt();

System.out.print("Enter the number of random numbers to generate: ");


int count = scanner.nextInt();

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 2


ADVANCED JAVA BIS402

List<Integer> numbers = new ArrayList<>();

Random random = new Random();


for (int i = 0; i < count; i++) {
int randomNum = lowerBound + random.nextInt(upperBound –lowerBound + 1);
if (randomNum % 2 == 0 && randomNum % 5 == 0) {
numbers.add(randomNum);
}
}

Collections.sort(numbers, new TensPlaceComparator());

System.out.println("Sorted numbers according to tens place:");


for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
Enter the lower bound of the range: 20
Enter the upper bound of the range: 200
Enter the number of random numbers to generate: 10
Sorted numbers according to tens place:
20
60
70

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


import java.util.LinkedList;
class Address {
private String name;
private String street;
private String city;
private String state;

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 3


ADVANCED JAVA BIS402

private String code;

Address(String n, String s, String c,String st, String cd) {


name = n;
street = s;
city = c;
state = st;
code = cd;
}

public String toString() {


return name + "\n" + street + "\n" +city + " " + state + " " + code;
}
}

class MailList {
public static void main(String[] args) {
LinkedList<Address> ml = new LinkedList<Address>();

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

for(Address element : ml)


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

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 4


ADVANCED JAVA BIS402

Ralph Baker
1142 Maple Lane
Mahomet IL 61853

Tom Carlton
867 Elm St
Champaign IL 61820

4. Implement a java program to illustrate the use of different types of string class
constructors.
import java.util.*;

public class StringConstructorsExample {


public static void main(String[] args) {
String str1 = "Hello";
System.out.println("String created using literal: " + str1);

char[] charArray = {'J', 'a', 'v', 'a'};


String str2 = new String(charArray);
System.out.println("String created using char array: " + str2);

String str3 = new String(charArray, 1, 3);


System.out.println("Substring created using char array: " + str3);

String str4 = new String(str2);


System.out.println("String created using a String object: " + str4);

byte[] byteArray = {65, 66, 67, 68, 69,70};


String str5 = new String(byteArray);
System.out.println("String created from byte array: " + str5);
String str6 = new String(byteArray, 2, 3);
System.out.println("Substring created using byte array: " + str6);

StringBuffer strBufObj = new StringBuffer("Java");

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 5


ADVANCED JAVA BIS402

String str7 = new String(strBufObj);


System.out.println("String created from StringBuffer: " + str7);

StringBuilder strBuildObj = new StringBuilder("Java");


String str8 = new String(strBuildObj);
System.out.println("String created from StringBuilder: " + str8);
}
}
Output:
String created using literal: Hello
String created using char array: Java
Substring created using char array: ava
String created using a String object: Java
String created from byte array: ABCDEF
Substring created using byte array: CDE
String created from StringBuffer: Java
String created from StringBuilder: Java

5.Implement a java program to illustrate the use of different types of character


extraction, stringcomparison, string search and string modification methods.

import java.io.*;
import java.util.*;

public class StringOperations {


public static void main(String[] args) {
String str = "Hello, World!";
System.out.println("Original String: " + str);

char ch = str.charAt(7);
System.out.println("Character at index 7: " + ch);

char[] charArray = new char[5];


str.getChars(7, 12, charArray, 0);

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 6


ADVANCED JAVA BIS402

System.out.print("Characters from index 7 to 12: ");


for (char c : charArray) {
System.out.print(c);
}
System.out.println();

byte[] byteArray = str.getBytes();


System.out.print("Bytes array: ");
for (byte b : byteArray) {
System.out.print(b + " ");
}
System.out.println();

char[] charArrayFromStr = str.toCharArray();


System.out.print("Character array from string: ");
for (char c : charArrayFromStr) {
System.out.print(c);
}
System.out.println();

String str1 = "Hello";


String str2 = "hello";

System.out.println("str1 equals str2: " + str1.equals(str2));


System.out.println("str1 equalsIgnoreCase str2: " + str1.equalsIgnoreCase(str2));

System.out.println("str1 regionMatches with str2: " + str1.regionMatches(true, 0, str2, 0, 5));

System.out.println("str startsWith 'Hello': " + str.startsWith("Hello"));


System.out.println("str endsWith 'World!': " + str.endsWith("World!"));

String str3 = new String("Hello");


System.out.println("str1 equals str3: " + str1.equals(str3));
System.out.println("str1 == str3: " + (str1 == str3));

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 7


ADVANCED JAVA BIS402

System.out.println("str1 compareTo str2: " + str1.compareTo(str2));

System.out.println("Index of 'o' in str: " + str.indexOf('o'));


System.out.println("Last index of 'o' in str: " + str.lastIndexOf('o'));

System.out.println("Substring from index 7: " + str.substring(7));

System.out.println("Concatenation of str1 and str2: " + str1.concat(str2));

System.out.println("Replace 'World' with 'Java' in str: " + str.replace("World", "Java"));

String strWithSpaces = " Hello, World! ";


System.out.println("Trimmed string: '" + strWithSpaces.trim() + "'");

System.out.println("Stripped string: '" + strWithSpaces.strip() + "'");


}
}
Output:
Original String: Hello, World!
Character at index 7: W
Characters from index 7 to 12: World
Bytes array: 72 101 108 108 111 44 32 87 111 114 108 100 33
Character array from string: Hello, World!
str1 equals str2: false
str1 equalsIgnoreCase str2: true
str1 regionMatches with str2: true
str startsWith 'Hello': true
str endsWith 'World!': true
str1 equals str3: true
str1 == str3: false
str1 compareTo str2: -32
Index of 'o' in str: 4
Last index of 'o' in str: 8
Substring from index 7: World!

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 8


ADVANCED JAVA BIS402

Concatenation of str1 and str2: Hellohello


Replace 'World' with 'Java' in str: Hello, Java!
Trimmed string: 'Hello, World!'
Stripped string: 'Hello, World!'

6. Implement a java program to illustrate the use of different types of StringBuffer


methods.
import java.io.*;
import java.util.*;

public class StringBufferMethods{


public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello");

System.out.println("Length of StringBuffer: " + stringBuffer.length());


System.out.println("Capacity of StringBuffer: " + stringBuffer.capacity());

stringBuffer.append(" Java");
stringBuffer.append('!');
System.out.println("Appended String: " + stringBuffer);

System.out.println("Character at index 6: " + stringBuffer.charAt(6));


stringBuffer.setCharAt(6, 'W');
System.out.println("StringBuffer after setCharAt: " + stringBuffer);

char[] charArray = new char[5];


stringBuffer.getChars(1, 4, charArray, 0);
System.out.print("Characters from index 1 to 4: ");
for (char c : charArray) {
System.out.print(c);
}
System.out.println();

stringBuffer.insert(6, "Awesome ");

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 9


ADVANCED JAVA BIS402

System.out.println("Inserted String: " + stringBuffer);

stringBuffer.delete(6, 12); // Deletes "Awesome "


System.out.println("String after deletion: " + stringBuffer);

stringBuffer.deleteCharAt(0); // Deletes ‘H’


System.out.println("String after deletion: " + stringBuffer);

stringBuffer.replace(1, 3, "i");
System.out.println("String after replacement: " + stringBuffer);

System.out.println("Substring starting at index 7: " + stringBuffer.substring(7));


System.out.println("Substring starting at index 7 and ending at 11: " +
stringBuffer.substring(7,11));

stringBuffer.reverse();
System.out.println("Reversed String: " + stringBuffer);

stringBuffer. ensureCapacity(20);
System.out.println("New Capacity of StringBuffer: " + stringBuffer.capacity());

stringBuffer.setLength(20);
System.out.println("StringBuffer length after setting length to 20: " + stringBuffer.length());
}
}

Output:
Length of StringBuffer: 5
Capacity of StringBuffer: 21
Appended String: Hello Java!
Character at index 6: J
StringBuffer after setCharAt: Hello Wava!
Characters from index 1 to 4: ell
Inserted String: Hello Awesome Wava!

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 10


ADVANCED JAVA BIS402

String after deletion: Hello e Wava!


String after deletion: ello e Wava!
String after replacement: eio e Wava!
Substring starting at index 7: ava!
Substring starting at index 7 and ending at 11: ava!
Reversed String: !avaW e oie
New Capacity of StringBuffer: 21
StringBuffer length after setting length to 20: 20

7. Demonstrate a swing event handling application that creates 2 buttons Alpha and
Beta and displays the text “Alpha pressed” when alpha button is clicked and “Beta
pressed” when beta button is clicked.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class EventDemo {
JLabel jlab;

EventDemo() {

JFrame jfrm = new JFrame("An Event Example");

jfrm.setLayout(new FlowLayout());

jfrm.setSize(220, 90);

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton jbtnAlpha = new JButton("Alpha");


JButton jbtnBeta = new JButton("Beta");

jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 11


ADVANCED JAVA BIS402

jlab.setText("Alpha was pressed.");


}
});

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

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

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

jfrm.add(jlab);

jfrm.setVisible(true);
}

public static void main(String args[]) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}

Output:

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 12


ADVANCED JAVA BIS402

8. A program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., GreetingApp), choose the server (e.g., Apache Tomcat), and
click Finish.

Step 2: Create the HTML Form


1. In the Web Pages directory, Add the following HTML code to index.jsp:
<!DOCTYPE html>
<html>
<head>
<title>Greeting App</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="GreetingServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 13
ADVANCED JAVA BIS402

Step 3: Create the Servlet


1. Right-click on the Source Packages directory, and select New -> Servlet.
2. Name the servlet GreetingServlet and click Next, then Finish.
3. Update the GreetingServlet.java file as follows:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "GreetingServlet", urlPatterns = {"/GreetingServlet"})


public class GreetingServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String username = request.getParameter("username");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Greeting App</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + username + "</h1>");
out.println("<h2>How are you?</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 14


ADVANCED JAVA BIS402

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Greeting Servlet";
}
}

Step 4: Deploy and Test the Application


1. Right-click on the project name and select Run.
2. The browser should open with the URL of your application.
3. Enter your username in the form and submit it.
4. You should see the greeting message "Hello, UserName" and "How Are You?".

Output:

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 15


ADVANCED JAVA BIS402

9. A servlet program to display the name, USN, and total marks by accepting student
detail.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., StudentApp), choose the server (e.g., Apache Tomcat), and
click Finish.

Step 2: Create the HTML Form


1. In the Web Pages directory, Add the following HTML code to index.jsp:

<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h1>Enter Student Details</h1>
<form action="DisplayDetailsServlet" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="usn">USN:</label>
<input type="text" id="usn" name="usn"><br><br>
<label for="marks">Total Marks:</label>
<input type="number" id="marks" name="marks"><br><br>
<input type="submit" value="Submit">
</form>
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 16
ADVANCED JAVA BIS402

</body>
</html>

Step 3: Create the Servlet


1. Right-click on the Source Packages directory, and select New -> Servlet.
2. Name the servlet DisplayDetailsServlet and click Next, then Finish.
3. Update the DisplayDetailsServlet.java file as follows:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/DisplayDetailsServlet"})

public class DisplayDetailsServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name = request.getParameter("name");
String usn = request.getParameter("usn");
int marks = Integer.parseInt(request.getParameter("marks"));

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Student Details Display Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Student Details " + request.getContextPath() + "</h1>");

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 17


ADVANCED JAVA BIS402

out.println("<p>Name: " + name + "</p>");


out.println("<p>USN: " + usn + "</p>");
out.println("<p>Total Marks: " + marks + "</p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Student Details";
}
}
Step 4: Deploy and Test the Application
1. Right-click on the project name and select Run.
2. The browser should open with the URL of your application.
3. Fill in the form and submit it to see the student details displayed by the servlet.

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 18


ADVANCED JAVA BIS402

Output:

10. A Java program to create and read the cookie for the given cookie name as
“EMPID” and its value as “AN2356”.
Step 1: Set Up Your Project
1. Open NetBeans and create a new project.
2. Select Java Web -> Web Application and click Next.
3. Name your project (e.g., CookieApp), choose the server (e.g., Apache Tomcat), and
click Finish.

Step 2: Create the HTML Form


1. In the Web Pages directory, Add the following HTML code to index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie App</title>
</head>
<body>

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 19


ADVANCED JAVA BIS402

<h1>Hello, Welcome to Cookie Application!</h1>


</body>
</html>

Step 3: Create a Servlet to set the cookie


1. Right-click on the Source Packages directory, and select New -> Servlet.
2. Name the servlet SetCookieServlet and click Next, then Finish.
3. Update the SetCookieServlet.java file as follows:
import java.io.IOException;
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;

@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("SetCookieServlet called");
Cookie empidCookie = new Cookie("EMPID", "AN2356");
empidCookie.setMaxAge(24 * 60 * 60);
response.addCookie(empidCookie);
response.setContentType("text/html");
response.getWriter().println("Cookie 'EMPID' with value 'AN2356' has been set.");
}
}

Step 4: Create a Servlet to read the cookie


1. Right-click on the Source Packages directory, and select New -> Servlet.
2. Name the servlet ReadCookieServlet and click Next, then Finish.
3. Update the ReadCookieServlet.java file as follows:

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 20


ADVANCED JAVA BIS402

import java.io.IOException;
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;

@WebServlet("/ReadCookieServlet")
public class ReadCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ReadCookieServlet called");
Cookie[] cookies = request.getCookies();
String empidValue = "Cookie not found";

if (cookies != null) {
for (Cookie cookie : cookies) {
if ("EMPID".equals(cookie.getName())) {
empidValue = cookie.getValue();
break;
}
}
}

response.setContentType("text/html");
response.getWriter().println("EMPID Cookie Value: " + empidValue);
}
}

Step 5: Deploy and Test the Application


1. Right-click on the project name and select Run.
2. This will deploy your application to the server and open the default web browser.
3. Fill in the form and submit it to see the student details displayed by the servlet.

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 21


ADVANCED JAVA BIS402

4. To set the cookie, navigate to


http://localhost:8080/Cookieapp/SetCookieServlet.
5. To read the cookie, navigate to
http://localhost:8080/Cookieapp/ReadCookieServlet.

Output:

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…).
1. Create the MySQL Database
(i). Start XAMPP
 Open the XAMPP Control Panel.
 Start the Apache and MySQL modules by clicking on the "Start" buttons next to
them.

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 22


ADVANCED JAVA BIS402

(ii). Open phpMyAdmin


 Once Apache and MySQL are running, open your web browser and go to
http://localhost/phpmyadmin.
(iii). Create a New Database
 In phpMyAdmin, you will see a navigation menu on the left and several tabs at the
top of the page.
 Click on the "Databases" tab.
 In the "Create database" field, enter the name of your new database, e.g., student_db.
 Choose the collation (default is fine for most cases, e.g., utf8_general_ci).
 Click the "Create" button.

(iv). Create a Table in the Database


 Once the database is created, it will appear in the left navigation menu.
 Click on your new database (student_db) to open it.
 Click on the "SQL" tab to open the SQL query editor.
 Enter the following SQL code to create the students table:
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
);
 Click the "Go" button to execute the query. This will create the students table with the
specified columns.

2. Set Up NetBeans Project


(i) Create a New Java Application Project
 Open NetBeans.
 Go to File > New Project.
 Select Java > Java Application and click Next.
 Name your project (e.g., StudentDBApp) and click Finish.

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 23


ADVANCED JAVA BIS402

(ii) Add MySQL JDBC Driver to the Project


 Download the MySQL JDBC driver (e.g., mysql-connector-java-8.0.xx.jar) from the
MySQL website.
 Right-click on your project in NetBeans.
 Go to Libraries > Add Library > Create Library.
 Select MySQL JDBC Driver and add the JAR file you downloaded.

3. Write the Java Code


 Right-click on the Source Packages directory, and select New -> Java class.
 Create a main class StudentDBApp.

StudentDBApp.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class StudentDBApp {

private static final String URL = "jdbc:mysql://localhost:3306/student_db";


private static final String USER = "root";
private static final String PASSWORD = "1234";

public static Connection getConnection() throws SQLException {


return DriverManager.getConnection(URL, USER, PASSWORD);
}

public static void insertStudent(String name, int age, String grade) {


String query = "INSERT INTO students (name, age, grade) VALUES (?, ?, ?)";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, name);
ps.setInt(2, age);

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 24


ADVANCED JAVA BIS402

ps.setString(3, grade);
ps.executeUpdate();
System.out.println("Student inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void updateStudent(int id, String name, int age, String grade) {
String query = "UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, name);
ps.setInt(2, age);
ps.setString(3, grade);
ps.setInt(4, id);
ps.executeUpdate();
System.out.println("Student updated successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void deleteStudent(int id) {


String query = "DELETE FROM students WHERE id = ?";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(query)) {
ps.setInt(1, id);
ps.executeUpdate();
System.out.println("Student deleted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 25


ADVANCED JAVA BIS402

public static void searchStudent(int id) {


String query = "SELECT * FROM students WHERE id = ?";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(query)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
System.out.println("Age: " + rs.getInt("age"));
System.out.println("Grade: " + rs.getString("grade"));
} else {
System.out.println("Student not found.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("1. Insert Student");
System.out.println("2. Update Student");
System.out.println("3. Delete Student");
System.out.println("4. Search Student");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter name: ");

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 26


ADVANCED JAVA BIS402

String name = scanner.next();


System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter grade: ");
String grade = scanner.next();
insertStudent(name, age, grade);
break;
case 2:
System.out.print("Enter student ID to update: ");
int updateId = scanner.nextInt();
System.out.print("Enter new name: ");
String newName = scanner.next();
System.out.print("Enter new age: ");
int newAge = scanner.nextInt();
System.out.print("Enter new grade: ");
String newGrade = scanner.next();
updateStudent(updateId, newName, newAge, newGrade);
break;
case 3:
System.out.print("Enter student ID to delete: ");
int deleteId = scanner.nextInt();
deleteStudent(deleteId);
break;
case 4:
System.out.print("Enter student ID to search: ");
int searchId = scanner.nextInt();
searchStudent(searchId);
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Please try again.");
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 27


ADVANCED JAVA BIS402

} while (choice != 5);

scanner.close();
}
}

Output:
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Abhay
Enter age: 24
Enter grade: A
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Bharath
Enter age: 20
Enter grade: B
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 1
Enter name: Chetan

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 28


ADVANCED JAVA BIS402

Enter age: 19
Enter grade: C
Student inserted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 2
Enter student ID to update: 2
Enter new name: Deepak
Enter new age: 20
Enter new grade: A
Student updated successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 3
Enter student ID to delete: 3
Student deleted successfully.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 4
Enter student ID to search: 1
ID: 1
Name: Abhay
Age: 24
Grade: A
1. Insert Student

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 29


ADVANCED JAVA BIS402

2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 4
Enter student ID to search: 4
Student not found.
1. Insert Student
2. Update Student
3. Delete Student
4. Search Student
5. Exit
Enter your choice: 5
Exiting...

12. A program to design the Login page and validating the USER_ID and PASSWORD
using JSP and DataBase.
1. Create the MySQL Database
(i). Start XAMPP
 Open the XAMPP Control Panel.
 Start the Apache and MySQL modules by clicking on the "Start" buttons next to
them.

(ii). Open phpMyAdmin


 Once Apache and MySQL are running, open your web browser and go to
http://localhost/phpmyadmin.

(iii). Create a New Database


 In phpMyAdmin, you will see a navigation menu on the left and several tabs at the
top of the page.
 Click on the "Databases" tab.
 In the "Create database" field, enter the name of your new database, e.g., user_db.
 Choose the collation (default is fine for most cases, e.g., utf8_general_ci).
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 30
ADVANCED JAVA BIS402

 Click the "Create" button.

(iv). Create a Table in the Database


 Once the database is created, it will appear in the left navigation menu.
 Click on your new database (user_db) to open it.
 Click on the "SQL" tab to open the SQL query editor.
 Enter the following SQL code to create the users table:

CREATE TABLE users (


id INT PRIMARY KEY AUTO_INCREMENT,
user_id VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL
);
 Click the "Go" button to execute the query. This will create the students table with the
specified columns.
 Insert a sample user for testing:
INSERT INTO users (user_id, password) VALUES ('user1', '1234');

2. Set Up NetBeans Project


(i) Create a New Java Application Project
 Open NetBeans and create a new project.
 Select Java Web -> Web Application and click Next.
 Name your project (e.g., LoginApp), choose the server (e.g., Apache Tomcat), and
click Finish.

(ii) Add MySQL JDBC Driver to the Project


 Download the MySQL JDBC driver (e.g., mysql-connector-java-8.0.xx.jar) from the
MySQL website.
 Right-click on your project in NetBeans.
 Go to Libraries > Add Library > Create Library.
 Select MySQL JDBC Driver and add the JAR file you downloaded.

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 31


ADVANCED JAVA BIS402

3. Create JSP Pages


 In the Web Pages directory, Add the following HTML code to index.jsp. This
page will contain the login form.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="loginProcess.jsp" 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">
</form>
</body>
</html>

 loginProcess.jsp: This page will process the login form submission.


<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Process</title>
</head>
<body>
<%
String userID = request.getParameter("user_id");
String password = request.getParameter("password");

Connection conn = null;

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 32


ADVANCED JAVA BIS402

PreparedStatement pst = null;


ResultSet rs = null;

String url = "jdbc:mysql://localhost:3306/user_db";


String driver = "com.mysql.cj.jdbc.Driver";
String dbUserName = "root";
String dbPassword = "1234";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, dbUserName, dbPassword);

String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, userID);
pst.setString(2, password);
rs = pst.executeQuery();

if(rs.next()) {
out.println("Login successful! Welcome, " + userID);
} else {
out.println("Invalid user ID or password. Please try again.");
}
} catch (Exception e) {
e.printStackTrace();
out.println("Error occurred while connecting to the database.");
} finally {
try {
if(rs != null) rs.close();
if(pst != null) pst.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 33


ADVANCED JAVA BIS402

%>
</body>
</html>

Output:

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 34


ADVANCED JAVA BIS402

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere 35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy