3 Mech - Java Programming Unit 5
3 Mech - Java Programming Unit 5
proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
JAVA PROGRAMMING
Created by :
Dr J.Sathiamoorthy Associate Professor / CSE
Date : 08.08.2022
4
1. CONTENTS
Page
S. No. Contents
No
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course outcomes 9
7 Lecture Plan 11
9 Lecture Notes 15
10 Assignments 52
12 Part B Questions 61
16 Assessment Schedule 70
5
2. COURSE OBJECTIVES
6
3. PRE REQUISITES
Pre-requisite Chart
7
4. SYLLABUS
OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications
8
5. Course Outcomes
CO4 Build Java applications with I/O streams and generics classes K3
POs/PSOs
PS O
COs PO PO PO PO PO PO PO PO PO 9 PO1 PO1 PO1 PSO 1PSO 2 3
1 2 3 4 5 6 7 8 0 1 2
CO1 3 3 3 - - - - - - - - - 3 2 2
CO2 3 2 2 - - - - - - - - - 3 2 2
CO3 3 2 2 - - - - - - - - - 3 2 2
CO4 3 2 2 - - - - - - - - - 3 2 2
CO5 3 2 2 - - - - - - - - - 3 2 2
7. Lecture Plan
UNIT – V
PPT/
Array List CO3
6 Demo K2
PPT/
Iterator CO3
8 Demo K2
PPT/
Map CO3
9 Demo K3
LECTURE PLAN – UNIT V
Across
3. Which of these class can be used to implement the input stream that uses a
character array as the source?
4. keyword is used to explicitly throw an exception
5. block is used to enclose the code that might throw an exception. It must be used
within the method.
7. divide any number by zero, there occurs
8. The wrong formatting of any value may occur
11. When does Exceptions in Java arises in code sequence?
13. Which of these classes can return more than one character to be returned to
input stream?
Down
1. inserting any value in the wrong index of array, it would result in
2. Which of these stream contains the classes which can work on character stream?
6. Which of these class is used to read characters in a file?
9. block is always executed whether an exception is handled or not
10. Which of these method of FileReader class is used to read characters from a file?
12. keyword is used to apply restrictions on class, method, and variable.
8. ACTIVITY BASED LEARNING – UNIT V
SCRAMBLED WORDS
ENCETPIOX _________________________
YTR __________________________
CTAHC __________________________
WORTH __________________________
NITUP __________________________
TSCAK __________________________
RARYNIEDX __________________________
UNMREBOFRAMT __________________________
LIEF __________________________
TSERAM __________________________
9. Lecture Notes
Strings
Strings In Java
String methods
returns char value for the particular
1. char charAt(int index)
index
Example: 1
if (string1 == string2)
equal");
else
Unequal");
String b="technology";
n= new StringBuffer("Technology");
Output:
Declaration:
class ArrayList<E> where E represents the type of the objects that the list
can hold.
Syntax
ArrayList <type> obj = new ArrayList <type>();
ArrayList Methods
class Demo
s.add("Lion");
s.add("Elephant");
s.add(1,"Tiger");
String c=in.next();
for(int i=0;i<s.size();i++)
if(s.get(i).startsWith(c.toUpperCase()))
System.out.println(s.get(i));
System.out.println(s.contains("Lion");
System.out.println(s);
}
• COLLECTIONS:
• Collection is an interface in the java.util package
that is used to define a group, or collection of
objects.
• Java Collections can achieve all the operations that
you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
• Collections framework provide a set of standard
utility classes to manage collections.
• THE COLLECTION INTERFACES:
• The Collections Framework defines several core
interfaces.
• Hierarchy of Collection Framework:
• The Collection Interface:
• The Collection interface is the foundation upon
which the Collections Framework is built because it
must be implemented by any class that defines a
collection.
• Collection is a generic interface that has this
declaration:
• interface Collection<E>
• Here, E specifies the type of objects that the
collection will hold.
• Collection extends the Iterable interface. This
means that all collections can be cycled through by
use of the foreach style for loop.
• The Methods Declared by Collection Interface:
The List Interface:
•List interface extends from Collection interface
•It stores elements in a sequential manner
•Elements in the list can be accessed or inserted based on their position
•Starts with zero based index
•Can contain duplicate elements
•An Iterator can be used to access the elements of the List
The Methods Declared by List Interface:
The Set Interface:
•Set interface extends from Collection interface
•Set is an unordered collection
•It doesn’t allow duplicates
•If you add duplicates, it will replace the existing one
Example:
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
publicstaticvoid main(String args[]) {
// Create an array list.
ArrayList<String>al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
class ArrayListToArray {
publicstaticvoid main(String args[]) {
// Create an array list.
ArrayList<Integer>al = new ArrayList<Integer>();
// Add elements to the array list.
al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of al: " + al);
// Get the array.
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
intsum = 0;
// Sum the array.
for (inti : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}
Output:
Contents of al: [1, 2, 3, 4]
Sum is: 10
class LinkedListDemo {
publicstaticvoid main(String args[]) {
// Create a linked list.
LinkedList<String>ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
//Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
//Get and set a value.
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Output:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
class ArrayDequeDemo {
publicstaticvoid main(String args[]) {
// Create an array deque.
ArrayDeque<String>adq = new ArrayDeque<String>();
// Use an ArrayDeque like a stack.
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.print("Popping the stack: ");
while (adq.peek() != null)
System.out.print(adq.pop() + " ");
System.out.println();
}
}
Output:
Popping the stack: F E D B A
Using an Iterator:
Iterator is an object that enables you to traverse through a collection.
Each of the collection classes provides an iterator( ) method that returns
an iterator object to the start of the collection.
In general, to use an iterator to cycle through the contents of a
collection, follow these steps:
Obtain an iterator to the start of the collection by calling the collection’s
iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as
long as hasNext( ) returns true.
Within the loop, obtain each element by calling next( ).
ListIterator:
Used for obtaining a iterator for collections that implement List
ListIterator gives us the ability to access the collection in either forward or
backward direction
Has both next() and previous() method to access the next and previous element in
the List.
The Methods Provided by ListIterator:
Example:
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
publicstaticvoid main(String args[]) {
// Create an array list.
ArrayList<String>al = new ArrayList<String>();
// Add elements to the array list.
al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D");
al.add("F");
// Use iterator to display contents of al.
System.out.print("Original contents of al: ");
Iterator<String>itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated.
ListIterator<String>litr = al.listIterator();
while (litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards: ");
while (litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
for-each construct can also be used for iterating through the Collection
Use Iterator instead of the for-each construct when you need to:
Remove the current element
The for-each construct hides the iterator, so you cannot call remove
Iterate over multiple collections in parallel.
for(Object o : oa) {
Fruit d2 = (Fruit)o;
System.out.println(d2.name); }
class ForEachDemo {
publicstaticvoid main(String args[]) {
// Create an array list for integers.
ArrayList<Integer>vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Contents of vals: ");
for (intv : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
intsum = 0;
for (intv : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
Output:
Contents of vals: 1 2 3 4 5
Sum of values: 15
Spliterators:
A spliterator cycles through a sequence of elements.
It offers substantially more functionality than does either Iterator or ListIterator.
It provide support for parallel iteration of portions of the sequence.
The Methods Declared by Spliterator:
Example:
// A simple Spliterator demonstration.
import java.util.*;
class SpliteratorDemo {
publicstaticvoid main(String args[]) {
// Create an array list for doubles.
ArrayList<Double>vals = new ArrayList<>();
// Add values to the array list.
vals.add(1.0);
vals.add(2.0);
vals.add(3.0);
vals.add(4.0);
vals.add(5.0);
//Use tryAdvance() to display contents of vals.
System.out.print("Contents of vals:\n");
Spliterator<Double>spltitr = vals.spliterator();
while (spltitr.tryAdvance((n) -> System.out.println(n)))
;
System.out.println();
//Create new list that contains square roots.
spltitr = vals.spliterator();
ArrayList<Double>sqrs = new ArrayList<>();
while (spltitr.tryAdvance((n) ->sqrs.add(Math.sqrt(n))))
;
//Use forEachRemaining() to display contents of sqrs.
System.out.print("Contents of sqrs:\n");
spltitr = sqrs.spliterator();
spltitr.forEachRemaining((n) -> System.out.println(n));
System.out.println();
}
}
Output:
Contents of vals:
1.0
2.0
3.0
4.0
5.0
Contents of sqrs:
1.0
1.4142135623730951
1.7320508075688772
2.0
2.23606797749979
MAPS:
A map is an object that stores associations between keys and values, or key/value
pairs.
Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
Map don’t implement the Iterable interface. This means that you cannot cycle
through a map using a for-each style for loop. Furthermore, you can’t obtain
an iterator to a map.
THE MAP INTERFACES:
Example:
Expression Lambda ()->123.45
Block Lambda
(n) -> {
int result = 1;
for (int i=1;i<=n;i++) result=i*result;
return result;
};
revsb=sb.reverse();
if(str.equals(revsb)) System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
Iterator interface provides the facility of iterating the elements in a forward direction
only.
1.Obtain an iterator to the start of the collection by calling the collection’s
iterator( ) method.
2.Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
The ArrayList class extends AbstractList and implements the List interface.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections
framework.
14.What is the HashSet class in Java and how does it store elements?
(K1,CO4)
•iterator()
•listiterator()
•List
•Set
•Queue
There are two classes that support regular expression processing: Pattern and
Matcher. These classes work together. Use Pattern to define a regular
expression. Match the pattern against another sequence using Matcher.
12. PART - B
1. Write a program to read a line of text and reverse each word.
2. Explain the various methods available in String with suitable example.
3. Explain the difference between String, StringBuffer and StringBuilder
4. Write a Java program to remove all non-alphanumeric characters from a string
using regular expression.
9. List out all the methods in ArrayList and write a Java program to sum and
average of all the elements of an ArrayList
10. Explain the methods in LinkedList class
11. Write a Java program to get the first and last occurrence of the specified
elements in a linked list and print the list in forward and backward order.
12. Write a Java program to compare two linked lists
13. Write a java program to print the list in descending order.
14. Write a Java program to get the first and last occurrence of the specified
elements in a linked list and print the list in forward and backward order.
15. Explain the different interfaces and views of Map with all its methods and write
a Java program to get all keys from the given Map
16. Explain the different interfaces and views of Map with all its methods and write
a program to iterate through the Map
1. Explain the concept of streams and its byte stream classes in detail. (K2, CO3)
2. Explain the use of File stream classes and file modes. Write an example program
for file manipulation. (K2, CO3)
3. Explain I/O streams with suitable examples. (K2, CO3)
• Collection:
• Queues in Ticketing systems.
• TreeMap in Coin changer Application.
• Hash Search.
• TreeSet for Binary Search.
.
70
15. Content Beyond Syllabus
Implement Queue in Java using Array
The queue is a linear data structure that follows the FIFO rule (first in
first out). We can implement Queue for not only Integers but also
Strings, Float, or Characters. There are 5 primary operations in
Queue:
• enqueue() adds element x to the front of the queue
• dequeue() removes the last element of the queue
• front() returns the front element
• rear() returns the rear element
• empty() returns whether the queue is empty or not
// Importing input output classes
import java.io.*;
// Importing all utility classes
import java.util.*;
// Class 1
// Helper Class(user defined - generic queue class)
class queue<T> {
// front and rear variables are initially initiated to
// -1 pointing to no element that control queue
int front = -1, rear = -1;
// Creating an object of ArrayList class of T type
ArrayList<T> A = new ArrayList<>();
// Method 1
// Returns value of element at front
T front()
{
// If it is not pointing to any element in queue
if (front == -1)
return null;
Name of the
S.NO Start Date End Date Portion
Assessment
114
17. Text Books & References
TEXT BOOKS
1.Herbert Schildt, “Java The complete reference”, 11th Edition, McGraw Hill Education,
2019.
REFERENCES
1.Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, 9th Edition,
Prentice Hall, 2019.
2.Paul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition, Pearson, 2015.
3.Steven Holzner, “Java 2 Black book”, Dreamtech press, 2011.
4.Timothy Budd, “Understanding Object-oriented programming with Java”, Updated
Edition, Pearson Education, 2008.
5.https://www.tutorialspoint.com/java/index.htm
6.https://www.javatpoint.com/java-tutorial
7.https://www.w3schools.com/java/
8.https://www.geeksforgeeks.org/java-tutorial/
9.https://docs.oracle.com/javase/tutorial/
18. Mini Project
Interest Calculator with Collections
Calculate interest based on the type of the account and the status
of the account holder. The rates of interest changes according to
the amount (greater than or less than 1 crore), age of account
holder (General or Senior citizen) and number of days if the type
of account is FD or RD.
Some sample rates are given in the below tables: Rate of FD
citizen) and interest for amounts below 1 Crore:
Normal 4%
NRI 6%
Requirements:
1. Separate classes should be created for the different types of
accounts.
2. All classes should be derives from an abstract class named
‘Account’ which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of
the account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in
any fields, raise a user defined exception.
Sample class structure is given below:
Account(Abstract)
double interestRate
double amount
FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double calculateInterest()
SBAccount
double interestRate
double amount
abstract double calculateInterest()
RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double calculateInterest()
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.