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

Advanced Java - RNSIT

The document is a lab manual for the Advanced Java course (BIS402) at RNS Institute of Technology, detailing course outcomes, program descriptions, and various Java programming exercises. It emphasizes the development of technical skills and competencies in students through practical applications of Java concepts. The manual includes sample programs, expected outputs, and a disclaimer regarding the proprietary nature of the content.

Uploaded by

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

Advanced Java - RNSIT

The document is a lab manual for the Advanced Java course (BIS402) at RNS Institute of Technology, detailing course outcomes, program descriptions, and various Java programming exercises. It emphasizes the development of technical skills and competencies in students through practical applications of Java concepts. The manual includes sample programs, expected outputs, and a disclaimer regarding the proprietary nature of the content.

Uploaded by

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

RN SHETTY TRUST®

RNS INSTITUTE OF TECHNOLOGY


Affiliated to VTU, Recognized by GOK, Approved by AICTE, NewDelhi
(NAAC ‘A+ Grade’ Accredited, NBA Accredited (UG - CSE, ECE, ISE, EIE and
EEE)Channasandra, Dr. Vishnuvardhan Road, Bengaluru - 560 098
Ph:(080)28611880,28611881 URL: www.rnsit.ac.in

DEPARTMENT OF ISE

ADVANCED JAVA LAB MANUAL


(BIS402)
(As per Visvesvaraya Technological University Course type- IPCC)

Compiled by

DEPARTMENT OF ISE
R N S Institute of Technology
Bengaluru-98

Name:

USN:
RN SHETTY TRUST®

RNS INSTITUTE OF TECHNOLOGY


Affiliated to VTU, Recognized by GOK, Approved by AICTE, NewDelhi
(NAAC ‘A+ Grade’ Accredited, NBA Accredited (UG - CSE, ECE, ISE, EIE and
EEE)Channasandra, Dr. Vishnuvardhan Road, Bengaluru - 560 098
Ph:(080)28611880,28611881 URL: www.rnsit.ac.in

DEPARTMENT OF ISE

VISION OF THE DEPARTMENT


Building Information Technology Professionals by Imparting Quality Education and Inculcating
Key Competencies

MISSION OF THE DEPARTMENT


 Provide strong fundamentals through learner centric approach.
 Instill technical, interpersonal, interdisciplinary skills and logical
thinking for holistic development.

 Train to excel in higher education, research, and innovation with global


perspective.
 Develop leadership and entrepreneurship qualities with societal responsibilities.
Disclaimer

The information contained in this document is the proprietary and exclusive property of
RNS Institute except as otherwise indicated. No part of this document, in whole or in
part, may be reproduced, stored, transmitted, or used for course material development
purposes without the prior written permission of RNS Institute of Technology.

The information contained in this document is subject to change without notice. The
information in this document is provided for informational purposes only.

Trademark

Edition:2023-24

DocumentOwner
The primary contact for questions regarding this document is:

1.Kavitha B
Author(s):
2.Aishwarya G
3.Chaitra S
4. Aruna U
Department: ISE
Contact email ids: [email protected]
[email protected]
[email protected]

[email protected]
COURSE OUTCOMES
Course Outcomes: At the end of this course, students are able to:
CO1-Apply appropriate collection class/interface to solve the given problem.

CO2-Demonstrate the concepts of String operations in Java.


CO3-Apply the concepts of Swings to build Java applications.
CO4-Develop web based applications using Java servlets and JSP.
CO5- Use JDBC to build database applications.

Cos and Pos Mapping of lab Component

COURSE
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4
OUTCOMES

CO1

CO2

CO3

CO4

CO5
Mapping of Graduate Attributes’ (GAs) and ‘Program Outcomes’ (POs)
Graduate Attributes (GAs)
Program Outcomes(POs)
(As per Washington Accord
(As per NBA New Delhi)
Accreditation)
Apply the knowledge of mathematics, science, engineering fundamentals
Engineering Knowledge and an engineering specialization to the solution of complex engineering
problems

Identify, formulate, review research literature and analyze complex


Problem Analysis engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences and engineering sciences.

Design solutions for complex engineering problems and design system


components or processes that meet the specified needs with appropriate
Design/Development of solutions
considerations for the public health and safety and the cultural, societal and
environmental consideration.

Use research – based knowledge and research methods including design of


Conduct Investigation of complex
experiments, analysis and interpretation of data and synthesis of the
problems
information to provide valid conclusions.

Create, select and apply appropriate techniques, resources and modern


Modern Tool Usage engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

Apply reasoning informed by the contextual knowledge to assess society,


The engineer and society health, safety, legal and cultural issues and the consequential
responsibilities relevant to the professional engineering practice.

Understand the impact of the professional engineering solutions in societal


Environment and sustainability and environmental context and demonstrate the knowledge of and need for
sustainable development.
Apply ethical principles and commit professional ethics and
Ethics
responsibilities and norms of the engineering practice.
Function effectively as an individual and as a member or leader in diverse
Individual and teamwork
teams and in multidisciplinary settings.

Communicate effectively on complex engineering activities with the


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

Demonstrate knowledge and understanding of the engineering and


management principles and apply these to ones won work, as a member
Project management & finance
and leader in a team, to manage projects and in multidisciplinary
environments.
Recognize the need for and have the preparation and ability to engage in
Life Long Learning
independent and life-long learning in the broadest context of technological
change.
REVISED BLOOMS TAXONOMY(RBT)
ROGRAM LIST

Page
Sl. No. Programs Description
No.
Implement a java program to demonstrate creating an ArrayList, adding elements, removing 1
1. elements, sorting elements of ArrayList. Also illustrate the use of toArray() method.

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

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


3.
Implement a java program to illustrate the use of different types of string class constructors. 7
4.
Implement a java program to illustrate the use of different types of character extraction, 9
5. string
5 comparison, string search and string modification methods.

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

Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta and 13
7. 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 15
8. You?”, accept username from the client using servlet.

A servlet program to display the name, USN, and total marks by accepting student detail 17
9.
A Java program to create and read the cookie for the given cookie name as “EMPID” and its 19
10. value as “AN2356”.

Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on 21
11 particular queries(For example update, delete, search etc…).

A program to design the Login page and validating the USER_ID and PASSWORD using 25
12. JSP and Database.

Sample Viva Questions 29


13.
Additional Programs. 32
14.
1
Program1:

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


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

SOURCE CODE:

package Advanced_java;
import java.util.ArrayList;
import java.util.Collections;

publicclass Program1 {
publicstaticvoid main(String[] args) {
// Creating ArrayList
ArrayList<Integer>arrayList = new ArrayList<>();

// Adding elements
arrayList.add(5);
arrayList.add(3);
arrayList.add(8);
arrayList.add(1);

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

// Removing element at index 2


arrayList.remove(2);

System.out.println("ArrayList after removing element at index 2: " + arrayList);

// Sorting elements
Collections.sort(arrayList);

System.out.println("ArrayList after sorting: " + arrayList);

// Using toArray() method


Integer[] array = arrayList.toArray(new Integer[0]);

System.out.print("Array obtained from ArrayList using toArray(): ");


for (inti : array) {
System.out.print(i + " ");
}
System.out.println();
}
}

1
Sample Output:
ArrayList after adding elements: [5, 3, 8, 1]
ArrayList after removing element at index 2: [5, 3, 1]
ArrayList after sorting: [1, 3, 5]
Array obtained from ArrayList using toArray(): 1 3 5

2
Program2:

AIM: 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.

SOURCE CODE:
package Advanced_java;

import java.util.*;

class TensPlaceComparator implements Comparator<Integer> {


@Override
publicint compare(Integernum1, Integernum2) {
// Get the tens place of each number
inttensPlace1 = (num1 % 100) / 10;
inttensPlace2 = (num2 % 100) / 10;

// Compare based on the tens place


returnInteger.compare(tensPlace1, tensPlace2);
}
}

publicclass Program2 {
publicstaticvoid main(String[] args) {
// Define the range for random numbers
intlowerBound = 100;
intupperBound = 1000;

// Generate random numbers between the range that are multiples of 2 and 5
ArrayList<Integer>numbers = new ArrayList<>();
Random random = new Random();
for (inti = 0; i< 10; i++) {
intrandomNumber;
do {
randomNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
} while (randomNumber % 2 != 0 || randomNumber % 5 != 0); // Ensure multiple of 2
and 5
numbers.add(randomNumber);
}

System.out.println("Random numbers: " + numbers);

// Sort the numbers according to tens place using comparator


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

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


}}
3
Sample Output:

Random numbers: [710, 670, 530, 1000, 620, 630, 230, 290, 730, 970]
Sorted numbers according to tens place: [1000, 710, 620, 530, 630, 230, 730, 670, 970, 290]

4
Program3:

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

SOURCE CODE:
package Advanced_java;

import java.util.ArrayList;

class Person {
private String name;
privateintage;

public Person(String name, intage) {


this.name = name;
this.age = age;
}

public String getName() {


returnname;
}

publicint getAge() {
returnage;
}

@Override
public String toString() {
return"Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
publicclass Program3 {
publicstaticvoid main(String[] args) {
ArrayList<Person>personList = new ArrayList<>();

personList.add(new Person("Alice", 30));


personList.add(new Person("Bob", 25));
personList.add(new Person("Charlie", 40));

System.out.println("Contents of the ArrayList:");


for (Person person : personList) {
System.out.println(person);
}

5
}
}

Sample Output:
Contents of the ArrayList:
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=40}

6
Program4:

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

SOURCE CODE:
package Advanced_java;

publicclass Program4 {
publicstaticvoid main(String[] args) {
// Constructor 1: Using a string literal
String str1 = "Hello, World!";
System.out.println("Constructor 1: Using a string literal: " + str1);

// Constructor 2: Using a character array


char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(charArray);
System.out.println("Constructor 2: Using a character array: " + str2);

// Constructor 3: Using a portion of a character array


String str3 = new String(charArray, 2, 3); // Starts at index 2, length 3
System.out.println("Constructor 3: Using a portion of a character array: " + str3);

// Constructor 4: Using bytes and specifying character encoding


byte[] byteArray = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String str4 = new String(byteArray);
System.out.println("Constructor 4: Using bytes and specifying character encoding: " + str4);

// Constructor 5: Using bytes, specifying character encoding, and specifying range


String str5 = new String(byteArray, 2, 3); // Starts at index 2, length 3
System.out.println("Constructor 5: Using bytes, specifying character encoding, and
specifying range: " + str5);

// Constructor 6: Using another String object


String str6 = new String(str1);
System.out.println("Constructor 6: Using another String object: " + str6);

}
}

7
Sample Output:

Constructor 1: Using a string literal: Hello, World!


Constructor 2: Using a character array: Hello
Constructor 3: Using a portion of a character array: llo

Constructor 4: Using bytes and specifying character encoding: Hello


Constructor 5: Using bytes, specifying character encoding, and specifying range: llo
Constructor 6: Using another String object: Hello, World!

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

SOURCE CODE:
package Advanced_java;

publicclass Program5 {
publicstaticvoid main(String[] args) {
// String declaration
String str = "Hello, World!";

// Character extraction
charfirstChar = str.charAt(0);
charlastChar = str.charAt(str.length() - 1);

// Substring extraction
String substring = str.substring(7); // Extracts "World!"

// String comparison
String anotherStr = "hello, world!";
booleanisEqual = str.equals(anotherStr); // false
booleanisEqualIgnoreCase = str.equalsIgnoreCase(anotherStr); // true

// String search
booleancontainsHello = str.contains("Hello"); // true
intindexOfComma = str.indexOf(','); // 5

// String modification
String replacedStr = str.replace("World", "Universe"); // "Hello, Universe!"
String upperCaseStr = str.toUpperCase(); // "HELLO, WORLD!"
String lowerCaseStr = str.toLowerCase(); // "hello, world!"

// Output
System.out.println("First Character: " + firstChar);
System.out.println("Last Character: " + lastChar);
System.out.println("Substring: " + substring);
System.out.println("Is equal?: " + isEqual);
System.out.println("Is equal (ignore case)?: " + isEqualIgnoreCase);
System.out.println("Contains 'Hello'?: " + containsHello);
System.out.println("Index of comma: " + indexOfComma);
System.out.println("Replaced String: " + replacedStr);
System.out.println("Upper Case: " + upperCaseStr);
System.out.println("Lower Case: " + lowerCaseStr);
}}

9
Sample Output:
First Character: H
Last Character: !
Substring: World!
Is equal?: false
Is equal (ignore case)?: true
Contains 'Hello'?: true
Index of comma: 5
Replaced String: Hello, Universe!
Upper Case: HELLO, WORLD!
Lower Case: hello, world!

10
Program6:
AIM: Implement a java program to illustrate the use of different types of StringBuffer
methods.
SOURCE CODE;

package Advanced_java;
publicclass Program6
{
publicstaticvoid main(String[] args) {
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");

// Append method
sb.append(" World");
System.out.println("After appending: " + sb);

// Insert method
sb.insert(5, " Java");
System.out.println("After inserting: " + sb);

// Delete method
sb.delete(5, 10);
System.out.println("After deleting: " + sb);

// Reverse method
sb.reverse();
System.out.println("After reversing: " + sb);

// Replace method
sb.replace(6, 11, "Program");
System.out.println("After replacing: " + sb);

// Capacity method
System.out.println("Capacity of StringBuffer: " + sb.capacity());

// Length method
System.out.println("Length of StringBuffer: " + sb.length());

// EnsureCapacity method
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50): " + sb.capacity());
}}

11
Sample Input and Output:
After appending: Hello World
After inserting: Hello Java World
After deleting: Hello World

After reversing: dlroW olleH


After replacing: dlroW Program
Capacity of StringBuffer: 21
Length of StringBuffer: 13
Capacity after ensureCapacity(50): 50

12
Program7:
AIM: 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.
SOURCE CODE:
import javax.swing.*;

import java.awt.event.*;
public class ButtonDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();

}
});
}
private static void createAndShowGUI() {
// Create and set up the window
JFrame frame = new JFrame("Button Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create buttons
JButton alphaButton = new JButton("Alpha");
JButton betaButton = new JButton("Beta");
// Add action listeners to buttons
alphaButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


JOptionPane.showMessageDialog(frame, "Alpha pressed");
}
});

13
betaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Beta pressed");
}

});

// Set up the content pane


JPanel contentPane = new JPanel();
contentPane.add(alphaButton);
contentPane.add(betaButton);

frame.setContentPane(contentPane);

// Display the window


frame.pack();
frame.setVisible(true);
}

Sample Output:

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

import java.io.*;
import javax.servlet.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/GreetingServlet")
public class GreetingServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");

// Get username parameter from the request

String username = request.getParameter("username");

// Create PrintWriter object


PrintWriter out = response.getWriter();

// Generate HTML response

out.println("<html><head><title>Greeting Servlet</title></head><body>");
out.println("<h1>Hello " + username + "</h1>");
out.println("<p>How are you?</p>");
out.println("</body></html>");

15
// Close PrintWriter
out.close();
}
}

Sample Output:

16
PROGRAM9:
AIM:A servlet program to display the name, USN, and total marks by accepting student
detail.
SOURCE CODE:

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/StudentDetailsServlet")
public class StudentDetailsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");

// Get student details from the request

String name = request.getParameter("name");


String usn = request.getParameter("usn");
String totalMarksStr = request.getParameter("totalMarks");

// Convert total marks to integer


int totalMarks = 0;

try {
totalMarks = Integer.parseInt(totalMarksStr);
} catch (NumberFormatException e) {
e.printStackTrace();

17
}

// Create PrintWriter object


PrintWriter out = response.getWriter();

// Generate HTML response


out.println("<html><head><title>Student Details</title></head><body>");
out.println("<h1>Student Details</h1>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>USN: " + usn + "</p>");

out.println("<p>Total Marks: " + totalMarks + "</p>");


out.println("</body></html>");

// Close PrintWriter
out.close();
}

Sample Output:

18
Proram10:
AIM: A Java Program to create and read the cookie for the given cookie name as
"EMPID" and its value as "AN2356"

SOURCE CODE:
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;

import java.net.HttpCookie;

public class CookieExample {

public static void main(String[] args) {


// Create a new CookieManager

CookieManager cookieManager = new CookieManager();


CookieHandler.setDefault(cookieManager);

// Create a cookie
HttpCookie cookie = new HttpCookie("EMPID", "AN2356");

// Get the default cookie store


CookieStore cookieStore = cookieManager.getCookieStore();

// Add the cookie to the store


cookieStore.add(null, cookie);

// Read and display the value of the cookie


String empId = null;

19
for (HttpCookie storedCookie : cookieStore.getCookies()) {
if (storedCookie.getName().equals("EMPID")) {
empId = storedCookie.getValue();
break;

}
}

// Display the value of the EMPID cookie


if (empId != null) {
System.out.println("Value of EMPID cookie: " + empId);

} else {
System.out.println("EMPID cookie not found");
}
}
}
SAMPLE OUTPUT:

20
PROGRAM11:
AIM: write a java program to insert data into DATABASE and retrieve info based on
particular queries (For Example Update, Delete, Search,..ect)
SOURCE CODE:
import java.sql.*;
public class DatabaseExample {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/example_db";

private static final String USERNAME = "your_username";


private static final String PASSWORD = "your_password";

public static void main(String[] args) {


try {
// Connect to the database

Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,


PASSWORD);

// Insert data into the database

insertData(connection, "John", 25);

// Update data in the database


updateData(connection, "John", 30);

// Delete data from the database

deleteData(connection, "John");

// Search data in the database


searchByName(connection, "John");

21
// Close the connection
connection.close();
} catch (SQLException e) {

e.printStackTrace();
}
}

// Insert data into the database


private static void insertData(Connection connection, String name, int age) throws
SQLException {
String insertQuery = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, name);

preparedStatement.setInt(2, age);
int rowsInserted = preparedStatement.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}

// Update data in the database

private static void updateData(Connection connection, String name, int newAge) throws
SQLException {
String updateQuery = "UPDATE users SET age = ? WHERE name = ?";
PreparedStatement preparedStatement =
connection.prepareStatement(updateQuery);
preparedStatement.setInt(1, newAge);
preparedStatement.setString(2, name);
int rowsUpdated = preparedStatement.executeUpdate();

22
System.out.println(rowsUpdated + " row(s) updated.");
}

// Delete data from the database

private static void deleteData(Connection connection, String name) throws


SQLException {
String deleteQuery = "DELETE FROM users WHERE name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery);

preparedStatement.setString(1, name);
int rowsDeleted = preparedStatement.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
}

// Search data in the database by name

private static void searchByName(Connection connection, String name) throws


SQLException {
String selectQuery = "SELECT * FROM users WHERE name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(selectQuery);

preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("Name: " + resultSet.getString("name") + ", Age: " +
resultSet.getInt("age"));
}
}
}

23
Sample Output:

24
Program 12:

AIM: A Program to design the Login page and validating the USER_ID and PASSWORD using
JSP and DataBase.

SOURCE CODE:

Login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Login Page</title>

</head>

<body>

<h2>Login</h2>

<form action="loginServlet" method="post">

User ID: <input type="text" name="userId"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Login">

</form>

</body>

</html>

loginServelet.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

25
import java.sql.ResultSet;

import java.sql.SQLException;

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("/loginServlet")

public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

String userId = request.getParameter("userId");

String password = request.getParameter("password");

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/example_db", "your_username",
"your_password");

PreparedStatement ps = con.prepareStatement("select * from users where user_id=? and


password=?");

ps.setString(1, userId);

ps.setString(2, password);

26
ResultSet rs = ps.executeQuery();

if (rs.next()) {

// Valid user, redirect to success page

response.sendRedirect("success.jsp");

} else {

// Invalid user, display error message

out.println("Invalid user ID or password!");

} catch (ClassNotFoundException | SQLException e) {

out.println("Error: " + e.getMessage());

Success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Success</title>

</head>

<body>

<h2>Welcome, you are logged in!</h2>

</body>

</html>

27
Sample Output:

28
Sample Viva Questions.

 What is the Java Collection framework?


 What are the core interfaces in the Collection framework?
 Explain the difference between a Collection and a Collections in Java.
 What is an Iterator? How is it used in Java Collections?
 What is the difference between Iterator and ListIterator?
 Explain the purpose of the Iterable interface.
 What is the difference between Set and List in Java?
 Explain the characteristics of the Map interface.
 What is the difference between HashMap and HashTable?
 Explain the difference between HashSet and LinkedHashSet.
 What is the purpose of the Comparable interface?
 Explain the use of the Comparator interface.
 What is the difference between ArrayList and LinkedList?
 What is the purpose of the Queue interface?
 What is the difference between PriorityQueue and LinkedList?
 Explain the purpose of the Deque interface.
 What is the difference between ArrayDeque and LinkedList?
 What is the purpose of the Collection.sort() method?
 Explain the purpose of the Collections class in Java.
 What are the advantages of using the Java Collection.
 What is the Java Collection framework?
 What are the core interfaces in the Collection framework?
 Explain the difference between a Collection and a Collections in Java.
 What is an Iterator? How is it used in Java Collections?
 What is the difference between Iterator and ListIterator?
 Explain the purpose of the Iterable interface.
 What is the difference between Set and List in Java?
 Explain the characteristics of the Map interface.
 What is the difference between HashMap and HashTable?
 Explain the difference between HashSet and LinkedHashSet.
 What is the purpose of the Comparable interface?
 Explain the use of the Comparator interface.
 What is the difference between ArrayList and LinkedList?
 What is the purpose of the Queue interface?
 What is the difference between PriorityQueue and LinkedList?

29
 Explain the purpose of the Deque interface.
 What is the difference between ArrayDeque and LinkedList?
 What is the purpose of the Collection.sort() method?
 Explain the purpose of the Collections class in Java.
 What are the advantages of using the Java Collection
 What is the Java Collection framework?
 What are the core interfaces in the Collection framework?
 Explain the difference between a Collection and a Collections in Java.
 What is an Iterator? How is it used in Java Collections?
 What is the difference between Iterator and ListIterator?
 Explain the purpose of the Iterable interface.
 What is the difference between Set and List in Java?
 Explain the characteristics of the Map interface.
 What is the difference between HashMap and HashTable?
 Explain the difference between HashSet and LinkedHashSet.
 What is the purpose of the Comparable interface?
 Explain the use of the Comparator interface.
 What is the difference between ArrayList and LinkedList?
 What is the purpose of the Queue interface?
 What is the difference between PriorityQueue and LinkedList?
 Explain the purpose of the Deque interface.
 What is the difference between ArrayDeque and LinkedList?
 What is the purpose of the Collection.sort() method?
 Explain the purpose of the Collections class in Java.
 What are the advantages of using the Java Collection
 What is the Java Collection framework?
 What are the core interfaces in the Collection framework?
 Explain the difference between a Collection and a Collections in Java.
 What is an Iterator? How is it used in Java Collections?
 What is the difference between Iterator and ListIterator?
 Explain the purpose of the Iterable interface.
 What is the difference between Set and List in Java?
 Explain the characteristics of the Map interface.
 What is the difference between HashMap and HashTable?
 Explain the difference between HashSet and LinkedHashSet.
 What is the purpose of the Comparable interface?

30
 Explain the use of the Comparator interface.
 What is the difference between ArrayList and LinkedList?
 What is the purpose of the Queue interface?
 What is the difference between PriorityQueue and LinkedList?
 Explain the purpose of the Deque interface.
 What is the difference between ArrayDeque and LinkedList?
 What is the purpose of the Collection.sort() method?
 Explain the purpose of the Collections class in Java.
 What are the advantages of using the Java Collection
 What is the Java Collection framework?
 What are the core interfaces in the Collection framework?
 Explain the difference between a Collection and a Collections in Java.
 What is an Iterator? How is it used in Java Collections?
 What is the difference between Iterator and ListIterator?
 Explain the purpose of the Iterable interface.
 What is the difference between Set and List in Java?
 Explain the characteristics of the Map interface.
 What is the difference between HashMap and HashTable?
 Explain the difference between HashSet and LinkedHashSet.
 What is the purpose of the Comparable interface?
 Explain the use of the Comparator interface.
 What is the difference between ArrayList and LinkedList?
 What is the purpose of the Queue interface?
 What is the difference between PriorityQueue and LinkedList?
 Explain the purpose of the Deque interface.
 What is the difference between ArrayDeque and LinkedList?
 What is the purpose of the Collection.sort() method?
 Explain the purpose of the Collections class in Java.
 What are the advantages of using the Java Collection

31
ADDITIONAL PROGRAMS

1. Java Program Demonstrating Operations on the Set such as Union, Intersection


and Difference operations.

// Java Program Demonstrating Operations on the Set


// such as Union, Intersection and Difference operations

// Importing all utility classes


import java.util.*;

// Main class
public class SetExample {

// Main driver method


public static void main(String args[])
{
// Creating an object of Set class
// Declaring object of Integer type
Set<Integer> a = new HashSet<Integer>();

// Adding all elements to List


a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));

// Again declaring object of Set class


// with reference to HashSet
Set<Integer> b = new HashSet<Integer>();

b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));

// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);

// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);

// To find the symmetric difference

32
Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}}

Sample Output:
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection of the two Set[0, 1, 3, 4]
Difference of the two Set[2, 8, 9]

33
Program2: Java program Demonstrating Creation of Set object Using the Hashset class

// Java program Demonstrating Creation of Set object


// Using the Hashset class

// Importing utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)

{
// Creating object of Set of type String
Set<String> h = new HashSet<String>();

// Adding elements into the HashSet


// using add() method

// Custom input elements


h.add("India");
h.add("Australia");
h.add("South Africa");

// Adding the duplicate element

h.add("India");

34
// Displaying the HashSet
System.out.println(h);

// Removing items from HashSet


// using remove() method
h.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + h);

// Iterating over hash set items


System.out.println("Iterating over set:");

// Iterating through iterators


Iterator<String> i = h.iterator();
// remaining in the object

while (i.hasNext())
System.out.println(i.next());
}}
Sample Output:
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India

35
Program3: Java program to demonstrate the creation of Set object using the
LinkedHashset class.

// Java program to demonstrate the

// creation of Set object using

// the LinkedHashset class

import java.util.*;

class GFG {

public static void main(String[] args)

Set<String> lh = new LinkedHashSet<String>();

// Adding elements into the LinkedHashSet

// using add()

lh.add("India");

lh.add("Australia");

lh.add("South Africa");

// Adding the duplicate

// element

lh.add("India");

// Displaying the LinkedHashSet

System.out.println(lh);

36
// Removing items from LinkedHashSet

// using remove()

lh.remove("Australia");

System.out.println("Set after removing "

+ "Australia:" + lh);

// Iterating over linked hash set items

System.out.println("Iterating over set:");

Iterator<String> i = lh.iterator();

while (i.hasNext())

System.out.println(i.next());

Sample Output:
[India, Australia, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

37
Program4: Java Program to implement methods of SortedMap Interface using
TreeMap Class.

import java.util.*;

public class TreeMapDemo {


public static void main(String[] args) {
// Creating a TreeMap

TreeMap<Integer, String> treeMap = new TreeMap<>();

// Adding elements to the TreeMap


treeMap.put(3, "Three");
treeMap.put(1, "One");
treeMap.put(2, "Two");

treeMap.put(4, "Four");
treeMap.put(5, "Five");

// Displaying the TreeMap


System.out.println("TreeMap: " + treeMap);

// Getting the size of the TreeMap


System.out.println("Size of the TreeMap: " + treeMap.size());

// Checking if TreeMap is empty


System.out.println("Is TreeMap empty? " + treeMap.isEmpty());

// Getting value associated with a key


System.out.println("Value associated with key 3: " + treeMap.get(3));

38
// Checking if a key exists
System.out.println("Does TreeMap contain key 2? " + treeMap.containsKey(2));

// Checking if a value exists


System.out.println("Does TreeMap contain value 'Six'? " +
treeMap.containsValue("Six"));

// Removing a key-value pair


treeMap.remove(4);
System.out.println("After removing key 4: " + treeMap);

// Removing all elements from the TreeMap


treeMap.clear();

System.out.println("After clearing TreeMap: " + treeMap);


}
}

Sample Output:
TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}

Size of the TreeMap: 5


Is TreeMap empty? false
Value associated with key 3: Three
Does TreeMap contain key 2? true
Does TreeMap contain value 'Six'? false
After removing key 4: {1=One, 2=Two, 3=Three, 5=Five}

After clearing TreeMap: {}

39
Program5: Simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

Sample Output:

40
Program6: Java JLabel Example with ActionListener

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}}

Sample Output:

41
Program7: Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}

myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

42
Program 8: Java program to demonstrate the working of a Deque in Java

// Java program to demonstrate the working

// of a Deque in Java

import java.util.*;

public class DequeExample {

public static void main(String[] args)

Deque<String> deque

= new LinkedList<String>();

// We can add elements to the queue

// in various ways

// Add at the last

deque.add("Element 1 (Tail)");

// Add at the first

deque.addFirst("Element 2 (Head)");

// Add at the last

deque.addLast("Element 3 (Tail)");

// Add at the first

43
deque.push("Element 4 (Head)");

// Add at the last

deque.offer("Element 5 (Tail)");

// Add at the first

deque.offerFirst("Element 6 (Head)");

System.out.println(deque + "\n");

// We can remove the first element

// or the last element.

deque.removeFirst();

deque.removeLast();

System.out.println("Deque after removing "

+ "first and last: "

+ deque);

}}

Sample output:

[Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1


(Tail), Element 3 (Tail), Element 5 (Tail)]

Deque after removing first and last: [Element 4 (Head), Element 2


(Head), Element 1 (Tail), Element 3 (Tail)]

44
Program 9: Java program to demonstrate comparator() method for reverse ordering

// Java program to demonstrate

// comparator() method

// for reverse ordering

import java.util.*;

public class GFG1 {

public static void main(String[] argv)

throws Exception<div class="code-output">

<b>Output:</b>

<pre>

Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

The set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]

</pre>

</div>

try {

// Creating object of TreeMap

SortedMap<Integer, String>

sotreemap = new TreeMap<Integer, String>(

45
Collections.reverseOrder());

// Populating tree map

sotreemap.put(1, "one");

sotreemap.put(2, "two");

sotreemap.put(3, "three");

sotreemap.put(4, "four");

sotreemap.put(5, "five");

// Printing the TreeMap

System.out.println("SortedTreeMap: " + sotreemap);

// Getting used Comparator in the map

// using comparator() method

Comparator comp = sotreemap.comparator();

// Printing the comparator value

System.out.println("Comparator value: " + comp);

catch (NullPointerException e) {

System.out.println("Exception thrown : " + e);

46
}

Sample Output:

SortedTreeMap: {5=five, 4=four, 3=three, 2=two, 1=one}


Comparator value: java.util.Collections$ReverseComparator@232204a1

47
Program10: Java Program retrieving contents of Table Using JDBC connection.

// Java Program retrieving contents of

// Table Using JDBC connection

// Java code producing output which is based

// on values stored inside the "cuslogin" table in DB

// Importing SQL libraries to create database

import java.sql.*;

public class GFG {

// Step1: Main driver method

public static void main(String[] args)

// Step 2: Making connection using

// Connection type and inbuilt function on

Connection con = null;

PreparedStatement p = null;

ResultSet rs = null;

con = connection.connectDB();

// Try block to catch exception/s

try {

48
// SQL command data stored in String datatype

String sql = "select * from cuslogin";

p = con.prepareStatement(sql);

rs = p.executeQuery();

// Printing ID, name, email of customers

// of the SQL command above

System.out.println("id\t\tname\t\temail");

// Condition check

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String email = rs.getString("email");

System.out.println(id + "\t\t" + name+ "\t\t" + email);}}

// Catch block to handle exception

catch (SQLException e) {

// Print exception pop-up on screen

System.out.println(e);} }}

Sample Output:

49

You might also like