Advanced Java - SMVIT
Advanced Java - SMVIT
DEPARTMENT OF ISE
Compiled by
DEPARTMENT OF ISE
Sir M Visvesvaraya Institute of Technology Bengaluru
Name:
USN:
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:
import [Link];
import [Link];
public class Program1
{
public static void main(String[] args)
{
// Creating ArrayList
ArrayList<Integer> arrayList= new ArrayList<>();
// Adding elements
[Link](5); [Link](3); [Link](8); [Link](1);
[Link]("ArrayList after adding elements: " + arrayList);
// Sorting elements
[Link](arrayList);
[Link]("ArrayList after sorting: " + arrayList);
7
Program2:
AIM: Develop a program to read random numbers between a given range that are ultiples of 2 and
5, sort the numbers according to tens place using comparator.
package program2;
import [Link];
import [Link];
import [Link];
import [Link];
int randomNumber;
do {
randomNumber = [Link](upperBound - lowerBound + 1) + lowerBound;
} while (randomNumber % 2 != 0 || randomNumber % 5 != 0);
[Link](randomNumber);
}
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] 8
Program3:
import [Link];
class Person
{ private String name;
private int age;
public Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
public String getName() {
return name;
}
Sample Output:
Contents of the ArrayList:
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=40}
9
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!";
[Link]("Constructor 1: Using a string literal: " + str1);
}
}
10
Sample Output:
Constructor 5: Using bytes, specifying character encoding, and specifying range: llo
Constructor 6: Using another String object: Hello, World!
11
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 = [Link](0);
charlastChar = [Link]([Link]() - 1);
// Substring extraction
String substring = [Link](7); // Extracts "World!"
// String comparison
String anotherStr = "hello, world!";
booleanisEqual = [Link](anotherStr); // false
booleanisEqualIgnoreCase = [Link](anotherStr); // true
// String search
booleancontainsHello = [Link]("Hello"); // true
intindexOfComma = [Link](','); // 5
// String modification
String replacedStr = [Link]("World", "Universe"); // "Hello, Universe!"
String upperCaseStr = [Link](); // "HELLO, WORLD!"
String lowerCaseStr = [Link](); // "hello, world!"
// Output
[Link]("First Character: " + firstChar);
[Link]("Last Character: " + lastChar);
[Link]("Substring: " + substring);
[Link]("Is equal?: " + isEqual);
[Link]("Is equal (ignore case)?: " + isEqualIgnoreCase);
[Link]("Contains 'Hello'?: " + containsHello);
[Link]("Index of comma: " + indexOfComma);
[Link]("Replaced String: " + replacedStr);
[Link]("Upper Case: " + upperCaseStr);
[Link]("Lower Case: " + lowerCaseStr);
}}
12
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!
13
Program6:
AIM: Implement a java program to illustrate the use of different types of Str ingBuffer
methods.
SOURCE CODE;
package Advanced_java;
publicclass Program6
{
publicstaticvoid main(String[] args) {
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");
// Append method
[Link](" World");
[Link]("After appending: " + sb);
// Insert method
[Link](5, " Java");
[Link]("After inserting: " + sb);
// Delete method
[Link](5, 10);
[Link]("After deleting: " + sb);
// Reverse method
[Link]();
[Link]("After reversing: " + sb);
// Replace method
[Link](6, 11, "Program");
[Link]("After replacing: " + sb);
// Capacity method
[Link]("Capacity of StringBuffer: " + [Link]());
// Length method
[Link]("Length of StringBuffer: " + [Link]());
// EnsureCapacity method
[Link](50);
[Link]("Capacity after ensureCapacity(50): " + [Link]());
}}
14
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
15
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 [Link].*;
import [Link].*;
}
});
}
private static void createAndShowGUI() {
[Link](JFrame.EXIT_ON_CLOSE);
// Create buttons
16
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
});
[Link](contentPane);
Sample Output:
17
Program8:
AIM: A program to display greeting message on the browser “Hello UserName”, “How
Are You?”, accept username from the client using servlet.
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/GreetingServlet")
public class GreetingServlet extends HttpServlet {
[Link]("<html><head><title>Greeting Servlet</title></head><body>");
[Link]("<h1>Hello " + username + "</h1>");
[Link]("<p>How are you?</p>");
[Link]("</body></html>");
18
// Close PrintWriter
[Link]();
}
}
Sample Output:
19
PROGRAM9:
AIM:A servlet program to display the name, USN, and total marks by accepting student
detail.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/StudentDetailsServlet")
public class StudentDetailsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
[Link]("text/html");
try {
totalMarks = [Link](totalMarksStr);
} catch (NumberFormatException e) {
[Link]();
20
}
[Link]("</body></html>");
// Close PrintWriter
[Link]();
}
Sample Output:
21
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 [Link];
import [Link];
import [Link];
import [Link];
// Create a cookie
22
for (HttpCookie storedCookie : [Link]()) {
if ([Link]().equals("EMPID")) {
empId = [Link]();
break;
}
}
} else {
[Link]("EMPID cookie not found");
}
}
}
SAMPLE OUTPUT:
23
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 [Link].*;
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");
24
// Close the connection
[Link]();
} catch (SQLException e) {
[Link]();
}
private static void insertData(Connection connection, String name, int age) throws
SQLException {
String insertQuery = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = [Link](insertQuery);
[Link](1, name);
[Link](2, age);
int rowsInserted = [Link]();
[Link](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 =
[Link](updateQuery);
[Link](1, newAge);
[Link](2, name);
25
[Link](rowsUpdated + " row(s) updated.");
}
26
Sample Output:
27
Program 12:
AIM: A Program to design the Login page and validating the USER_ID and PASSWORD using
JSP and DataBase.
SOURCE CODE:
[Link]
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
</form>
</body>
</html>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
28
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/loginServlet")
[Link]("text/html;charset=UTF-8");
try {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/example_db", "your_username",
"your_password");
[Link](1, userId);
[Link](2, password);
29
ResultSet rs = [Link]();
if ([Link]()) {
[Link]("[Link]");
} else {
[Link]
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Success</title>
</head>
<body>
</body>
</html>
30
Sample Output:
31
Sample Viva Questions.
32
• Explain the purpose of the Deque interface.
• What is the difference between ArrayDeque and LinkedList?
• What is the purpose of the [Link]() 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 [Link]() 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?
33
• 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 [Link]() 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 [Link]() method?
• Explain the purpose of the Collections class in Java.
• What are the advantages of using the Java Collection
34
ADDITIONAL PROGRAMS
// Main class
public class SetExample {
[Link]([Link](
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
// To find union
Set<Integer> union = new HashSet<Integer>(a);
[Link](b);
[Link]("Union of the two Set");
[Link](union);
// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
[Link](b);
[Link]("Intersection of the two Set");
[Link](intersection);
35
Set<Integer> difference = new HashSet<Integer>(a);
[Link](b);
[Link]("Difference of the two Set");
[Link](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]
36
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>();
37
// Displaying the HashSet
[Link](h);
while ([Link]())
[Link]([Link]());
}}
Sample Output:
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India
38
Program3: Java program to demonstrate the creation of Set object using the
LinkedHashset class.
import [Link].*;
class GFG {
// using add()
[Link]("India");
[Link]("Australia");
[Link]("South Africa");
// element
[Link]("India");
[Link](lh);
39
// Removing items from LinkedHashSet
// using remove()
[Link]("Australia");
+ "Australia:" + lh);
Iterator<String> i = [Link]();
while ([Link]())
[Link]([Link]());
Sample Output:
[India, Australia, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
40
Program4: Java Program to implement methods of SortedMap Interface using
TreeMap Class.
import [Link].*;
[Link](4, "Four");
[Link](5, "Five");
41
// Checking if a key exists
[Link]("Does TreeMap contain key 2? " + [Link](2));
Sample Output:
TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Size of the TreeMap: 5
Is TreeMap empty? false
42
Program5: Simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
Sample Output:
43
Program6: Java JLabel Example with ActionListener
import [Link].*;
import [Link].*;
import [Link].*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
[Link](50,50, 150,20);
l=new JLabel();
[Link](50,100, 250,20);
b=new JButton("Find IP");
[Link](50,150,95,30);
[Link](this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=[Link]();
String ip=[Link](host).getHostAddress();
[Link]("IP of "+host+" is: "+ip);
}catch(Exception ex){[Link](ex);}
}
public static void main(String[] args) {
new LabelExample();
}}
Sample Output:
44
Program7: Example of Graphics in applet:
import [Link];
import [Link].*;
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
45
Program 8: Java program to demonstrate the working of a Deque in Java
// of a Deque in Java
import [Link].*;
Deque<String> deque
= new LinkedList<String>();
// in various ways
[Link]("Element 1 (Tail)");
[Link]("Element 2 (Head)");
[Link]("Element 3 (Tail)");
46
[Link]("Element 4 (Head)");
[Link]("Element 5 (Tail)");
[Link]("Element 6 (Head)");
[Link](deque + "\n");
[Link]();
[Link]();
+ deque);
}}
Sample output:
47
Program 9: Java program to demonstrate comparator() method for reverse ordering
// comparator() method
import [Link].*;
<b>Output:</b>
<pre>
</pre>
</div>
try {
SortedMap<Integer, String>
48
[Link]());
[Link](1, "one");
[Link](2, "two");
[Link](3, "three");
[Link](4, "four");
[Link](5, "five");
catch (NullPointerException e) {
49
}
Sample Output:
50
Program10: Java Program retrieving contents of Table Using JDBC connection.
import [Link].*;
PreparedStatement p = null;
ResultSet rs = null;
con = [Link]();
try {
51
// SQL command data stored in String datatype
p = [Link](sql);
rs = [Link]();
[Link]("id\t\tname\t\temail");
// Condition check
while ([Link]()) {
int id = [Link]("id");
catch (SQLException e) {
[Link](e);} }}
Sample Output:
52