Advanced Java - RNSIT
Advanced Java - RNSIT
DEPARTMENT OF ISE
Compiled by
DEPARTMENT OF ISE
R N S Institute of Technology
Bengaluru-98
Name:
USN:
RN SHETTY TRUST®
DEPARTMENT OF ISE
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.
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
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 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.
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);
// Sorting elements
Collections.sort(arrayList);
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.*;
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);
}
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:
SOURCE CODE:
package Advanced_java;
import java.util.ArrayList;
class Person {
private String name;
privateintage;
publicint getAge() {
returnage;
}
@Override
public String toString() {
return"Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
publicclass Program3 {
publicstaticvoid main(String[] args) {
ArrayList<Person>personList = new ArrayList<>();
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);
}
}
7
Sample Output:
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
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() {
13
betaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Beta pressed");
}
});
frame.setContentPane(contentPane);
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");
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");
try {
totalMarks = Integer.parseInt(totalMarksStr);
} catch (NumberFormatException e) {
e.printStackTrace();
17
}
// 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;
// Create a cookie
HttpCookie cookie = new HttpCookie("EMPID", "AN2356");
19
for (HttpCookie storedCookie : cookieStore.getCookies()) {
if (storedCookie.getName().equals("EMPID")) {
empId = storedCookie.getValue();
break;
}
}
} 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";
deleteData(connection, "John");
21
// Close the connection
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
preparedStatement.setInt(2, age);
int rowsInserted = preparedStatement.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}
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.");
}
preparedStatement.setString(1, name);
int rowsDeleted = preparedStatement.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
}
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
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
</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")
response.setContentType("text/html;charset=UTF-8");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/example_db", "your_username",
"your_password");
ps.setString(1, userId);
ps.setString(2, password);
26
ResultSet rs = ps.executeQuery();
if (rs.next()) {
response.sendRedirect("success.jsp");
} else {
Success.jsp
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Success</title>
</head>
<body>
</body>
</html>
27
Sample Output:
28
Sample Viva Questions.
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
// Main class
public class SetExample {
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);
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
// Main class
class GFG {
{
// Creating object of Set of type String
Set<String> h = new HashSet<String>();
h.add("India");
34
// Displaying the HashSet
System.out.println(h);
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.
import java.util.*;
class GFG {
// using add()
lh.add("India");
lh.add("Australia");
lh.add("South Africa");
// element
lh.add("India");
System.out.println(lh);
36
// Removing items from LinkedHashSet
// using remove()
lh.remove("Australia");
+ "Australia:" + lh);
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.*;
treeMap.put(4, "Four");
treeMap.put(5, "Five");
38
// Checking if a key exists
System.out.println("Does TreeMap contain key 2? " + treeMap.containsKey(2));
Sample Output:
TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
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
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.*;
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
// of a Deque in Java
import java.util.*;
Deque<String> deque
= new LinkedList<String>();
// in various ways
deque.add("Element 1 (Tail)");
deque.addFirst("Element 2 (Head)");
deque.addLast("Element 3 (Tail)");
43
deque.push("Element 4 (Head)");
deque.offer("Element 5 (Tail)");
deque.offerFirst("Element 6 (Head)");
System.out.println(deque + "\n");
deque.removeFirst();
deque.removeLast();
+ deque);
}}
Sample output:
44
Program 9: Java program to demonstrate comparator() method for reverse ordering
// comparator() method
import java.util.*;
<b>Output:</b>
<pre>
</pre>
</div>
try {
SortedMap<Integer, String>
45
Collections.reverseOrder());
sotreemap.put(1, "one");
sotreemap.put(2, "two");
sotreemap.put(3, "three");
sotreemap.put(4, "four");
sotreemap.put(5, "five");
catch (NullPointerException e) {
46
}
Sample Output:
47
Program10: Java Program retrieving contents of Table Using JDBC connection.
import java.sql.*;
PreparedStatement p = null;
ResultSet rs = null;
con = connection.connectDB();
try {
48
// SQL command data stored in String datatype
p = con.prepareStatement(sql);
rs = p.executeQuery();
System.out.println("id\t\tname\t\temail");
// Condition check
while (rs.next()) {
int id = rs.getInt("id");
catch (SQLException e) {
System.out.println(e);} }}
Sample Output:
49