Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

3 Mech - Java Programming Unit 5

Uploaded by

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

3 Mech - Java Programming Unit 5

Uploaded by

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

Please read this disclaimer before

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

Department : Mechanical Engineering

Batch / Year :2021-2025 / II Year

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

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 13

9 Lecture Notes 15

10 Assignments 52

11 Part A Questions & Answers 54

12 Part B Questions 61

13 Supportive online Certification courses 63

14 Real time Applications 64

15 Contents beyond the Syllabus 65

16 Assessment Schedule 70

17 Prescribed Text Books & Reference Books 71

18 Mini Project Suggestions 72

5
2. COURSE OBJECTIVES

• To understand Object Oriented Programming concepts and


fundamentals of Java
• To know the principles of packages, inheritance and
interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics
classes
• To use the functionalities of Strings and Collections

6
3. PRE REQUISITES

Pre-requisite Chart

20CS302 – OBJECT ORIENTED


PROGRAMMING

20GE101 – PROBLEM SOLVING AND C


PROGRAMMING

7
4. SYLLABUS

20CS304 JAVA PROGRAMMING LTPC3003


OBJECTIVES:
• To understand Object Oriented Programming concepts and fundamentals of Java
• To know the principles of packages, inheritance and interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics classes
• To use the functionalities of Strings and Collections
UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9
An Overview of Java - Data Types, Variables, and Arrays – Operators – Control
Statements – Class Fundamentals – Declaring objects – Methods – Constructors – this
keyword - Overloading methods - Overloading constructors - Access Control – Static –
Final.
UNIT II - INHERITANCE, PACKAGE AND INTERFACES 9
Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract Classes,
Using final with Inheritance – Package and Interfaces: Packages, Packages and member
access, Importing Packages, Interfaces, Static Methods in an Interface
UNIT III - MULTITHREADING, I/O AND GENERIC PROGRAMMING 9
Exception Handling: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw,
throws, finally, Java’s Built-in Exceptions. Multithreaded Programming: Thread Creation
UNIT IV I/O AND GENERIC PROGRAMMING 9
I/O: I/O Basics, Reading Console Input, Writing Console Output, Reading and Writing
Files – Generics: Introduction, Generic class, Bounded Types, Generic Methods, Generic
Interfaces, Generic Restrictions.
UNIT V STRING HANDLING AND COLLECTIONS 9
String Handling – Collections: The Collection Interfaces, The Collection Classes – List,
Array List, Set, Iterator – Map.
TOTAL: 45 PERIODS

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

COURSE OUTCOMES HKL


Understand the Object Oriented Programming concepts and
CO1 K2
fundamentals of Java

Develop Java programs with the packages, inheritance and


CO2 K3
interfaces

CO3 Build applications using Exceptions and Threads. K3

CO4 Build Java applications with I/O streams and generics classes K3

CO5 Use Strings and Collections in applications K3


6. CO-PO/PSO Mapping

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

S. Scheduled Actual Date Mode of Taxonomy


Topic CO
No. Date of Completion Delivery Level
Video/
String Handling CO3
1 PPT K1
PPT/
Collections CO3 K1
2 Demo
PPT/
The Collection Interfaces CO3 K1
3 Demo
PPT/
4 The Collection Classes CO3 K1
Demo
PPT/
List CO3
5 Demo K2

PPT/
Array List CO3
6 Demo K2

Set CO3 PPT/


7 Demo K3

PPT/
Iterator CO3
8 Demo K2

PPT/
Map CO3
9 Demo K3
LECTURE PLAN – UNIT V

• ASSESSMENT COMPONENTS MODE OF DELEIVERY


• AC 1. Unit Test MD 1. Oral presentation
• AC 2. Assignment MD 2. Tutorial
• AC 3. Course Seminar MD 3. Seminar
• AC 4. Course Quiz MD 4 Hands On
• AC 5. Case Study MD 5. Videos
• AC 6. Record Work MD 6. Field Visit
• AC 7. Lab / Mini Project
• AC 8. Lab Model Exam
• AC 9. Project Review
8. ACTIVITY BASED LEARNING – UNIT V

COMPLETE THE PUZZLES GIVEN BELOW

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

In java, string is basically an object that represents sequence of char


values. Java String provides a lot of concepts that can be performed on a string
such as compare, concat, equals, split, length, replace, compareTo, intern, substring
etc.
In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.
String s=“Welcome";
There are two ways to create String object:
1.By string literal
2.By new keyword
1 ) String Literal
Java String literal is created by using double quotes. For Example: String
s=“Welcome";
2) By new keyword
String s=new String("Welcome");

String methods
returns char value for the particular
1. char charAt(int index)
index

2. int length() returns string length


static String format(String format,
3. returns formatted string
Object...args)
static String format(Locale l, String
4. returns formatted string with given locale
format, Object...args)
5. String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, returns substring for given begin index
6.
int endIndex ) and end index
returns true or false after matching the
7. boolean contains(CharSequence s)
sequence of char value
static String join(CharSequence
8. returns a joined string
delimiter, CharSequence... elements)
static String join(CharSequence
9. delimiter, Iterable<? extends returns a joined string
CharSequence> elements)
10. boolean equals(Object another) checks the equality of string with object

11. boolean isEmpty() checks if string is empty

12. String concat(String str) concatinates specified string


replaces all occurrences of specified
13. String replace(char old, char new)
char value
String replace(CharSequence old, replaces all occurrences of specified
14.
CharSequence new) CharSequence
static String equalsIgnoreCase(String compares another string. It doesn't
15.
another) check case.
16. String[] split(String regex) returns splitted string matching regex
returns splitted string matching regex
17. String[] split(String regex, int limit)
and limit
18. String intern() returns interned string

19. int indexOf(int ch) returns specified char value index


returns specified char value index
20. int indexOf(int ch, int fromIndex)
starting with given index
21. int indexOf(String substring) returns specified substring index
int indexOf(String substring, int returns specified substring index
22.
fromIndex) starting with given index
23. String toLowerCase() returns string in lowercase.
returns string in lowercase using
24. String toLowerCase(Locale l)
specified locale.
25. String toUpperCase() returns string in uppercase.
returns string in uppercase using
26. String toUpperCase(Locale l)
specified locale.
removes beginning and ending spaces
27. String trim()
of this string.
String pool space is located inside heap. because of lot use of strings when new
string create as string literal , java firstly check string pool for string value, if string
value exist in string pool then return reference for that string value, if value not
exist then new string will create inside string pool and return reference for
new string value.
Create String Object :
String exampleString = new String("java");
if you are creating a new String object by using new operator, then string pool
check will not perform and string object will create in heap memory.

Example: 1

Figure.2.16 String Pool


Example: 2

public class stringmethod

public static void main(String[] args)

String string1 = new String("hello");

String string2 = new String("hello");

if (string1 == string2)

System.out.println("string1= "+string1+" string2= "+string2+" are

equal");

else

System.out.println("string1= "+string1+" string2= "+string2+" are

Unequal");

System.out.println("string1 and string2 is= "+string1.equals(string2));


String a="information";
System.out.println("Uppercase of String a is= "+a.toUpperCase());

String b="technology";

System.out.println("Concatenation of object a and b is= "+a.concat(b));

System.out.println("After concatenation Object a is= "+a.toString());

System.out.println("\"Joseph\'s\" is the greatest\\ college in chennai");

System.out.println("Length of Object a is= "+a.length());

System.out.println("The third character of Object a is= "+a.charAt(2));


StringBuffer n=new StringBuffer("Technology");

StringBuffer m=new StringBuffer("Information");

System.out.println("Reverse of Object n is= "+n.reverse());

n= new StringBuffer("Technology");

System.out.println("Concatenation of Object m and n is= "+m.append(n));

System.out.println("After concatenation of Object m is= "+m);

Output:

string1= hello string2= hello are Unequal

string1 and string2 is= true

Uppercase of String a is= INFORMATION

Concatenation of object a and b is= informationtechnology

After concatenation Object a is= information

"Joseph's" is the greatest\ college in chennai

Length of Object a is= 11

The third character of Object a is= f

Reverse of Object n is= ygolonhceT

Concatenation of Object m and n is= InformationTechnology

After concatenation of Object m is InformationTechnology


Array Lists
Array Lists in JAVA

ArrayList class extends AbstractList class and implements List interface.


ArrayList is a generic class used to create dynamic array.

Declaration:
class ArrayList<E> where E represents the type of the objects that the list
can hold.

Constructors of ArrayList class


1. ArrayList()
2. ArrayList(Collection <? extends E> c) - Builds an array list which is initialized
with the elements of Collection c
3. ArrayList(int capacity) - Builds an array list with initial size defined by capacitY

Syntax
ArrayList <type> obj = new ArrayList <type>();

ArrayList Methods

Inserts the specified element at the


1. void add(int index, Object element) specified position in this ArrayList
Appends the specified element to the end of
2. boolean add(Object o) this ArrayList
Removes all of the elements from this
3. void clear() ArrayList
Returns true if this ArrayList contains the
4. boolean contains(Object elem)
specified element
Returns the element at the specified
5. Object get(int index)
position in this ArrayList
Searches for the first occurence of the given
6. int indexOf(Object elem) argument, testing for equality using the
equals method

7. boolean isEmpty() Tests if this ArrayList has no components

Returns the index of the last occurrence of


8. int lastIndexOf(Object elem))
the specified object in this ArrayList
Removes the element at the specified
9. Object remove(int index)
position in this ArrayList
Returns the number of components in this
10. int size()
ArrayList
Example:
import java.util.*;

class Demo

public static void main(String arg[])

ArrayList<String> s=new ArrayList<String>();

Scanner in=new Scanner(System.in);

s.add("Lion");

s.add("Elephant");

s.add(1,"Tiger");

System.out.print(“Enter the starting letter for the word to be


searched”);

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

It allows you to add only a single null value


An iterator can be used to traverse through the list
List interface has one legacy class called Vector, but Set doesn’t have any legacy class
Implementation classes for Set are TreeSet, HashSet and LinkedHashSet
The SortedSet Interface:
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending orde
SortedSet defines several methods that make set processing more convenient.
The Methods Declared by SortedSet:
The NavigableSet Interface:
The NavigableSet interface extends SortedSet and declares the behavior of a
collection that supports the retrieval of elements based on the closest match
to a given value or values.
The Methods Declared by NavigableSet:
The Queue Interface:
The Queue interface extends Collection and declares the behavior of a queue,
which is often a first-in, first-out list.
The methods declared by Queue are:

The Deque Interface:


The Deque interface extends Queue and declares the behavior of a double-ended
queue.
Double-ended queues can function as standard, first-in, first-out queues or as last-
in, firstout stacks.
In addition to the methods that it inherits from Queue, Deque adds the following
methods.
THE COLLECTION CLASSES:
Following core collection classes:

The ArrayList Class:


The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.
Standard arrays are of fixed size. After arrays are created they cannot grow or
shrink.
It provides more powerful insertion and search mechanisms than arrays.
Gives faster Iteration and fast random access.
Ordered Collection (by index), but not Sorted.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list.
The second constructor builds an array list that is initialized with the elements of
the collection c.
The third constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the elements.
The capacity grows automatically as elements are added to an array list.

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]

Obtaining an Array from an ArrayList:


To convert a collection into an array, use toArray( ) method.
There are two versions of toArray( ).
object[ ] toArray( )
<T>T[ ] toArray(T array[ ])
The first returns an array of Object. The second returns an array of elements that
have the same type as T.
Example:

// Convert an ArrayList into an array.


import java.util.*;

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

The LinkedList Class:


The LinkedList class extends AbstractSequentialList and implements the
List, Deque, and Queue interfaces.
It provides a linked-list data structure.
LinkedList has the two constructors shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list.
The second constructor builds a linked list that is initialized with the
elements of the collection c.
Example:
// Demonstrate LinkedList.
import java.util.*;

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]

The HashSet Class:


HashSet extends AbstractSet and implements the Set interface. It
creates a collection that uses a hash table for storage.
The following constructors are defined:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
The first form constructs a default hash set.
The second form initializes the hash set by using the elements of c.
The third form initializes the capacity of the hash set to capacity. (The
default capacity is 16.)
The fourth form initializes both the capacity and the fill ratio (also called
load capacity) of the hash set from its arguments. The fill ratio must
be between 0.0
and 1.0, and it determines how full the hash set can be before it is
resized upward.
Example:
// Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
publicstaticvoid main(String args[]) {
// Create a hash set.
HashSet<String>hs = new HashSet<String>();
// Add elements to the hash set.
hs.add("Beta");
hs.add("Alpha");
hs.add("Eta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Omega");
System.out.println(hs);
}
}
Output:
[Gamma, Eta, Alpha, Epsilon, Omega, Beta]
The LinkedHashSet Class:
The LinkedHashSet class extends HashSet and adds no members of its
own.
LinkedHashSet maintains a linked list of the entries in the set, in the
order in which they were inserted.
Example:
// Demonstrate HashSet.
import java.util.*;
classLinkedHashSetDemo {
publicstaticvoid main(String args[]) {
// Create a hash set.
LinkedHashSet<String>hs = new LinkedHashSet<String>();
// Add elements to the hash set.
hs.add("Beta");
hs.add("Alpha");
hs.add("Eta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Omega");
System.out.println(hs);
}
}
Output:
[Beta, Alpha, Eta, Gamma, Epsilon, Omega]

The TreeSet Class:


TreeSet extends AbstractSet and implements the NavigableSet interface.
It creates a collection that uses a tree for storage.
Objects are stored in sorted, ascending order.
Access and retrieval times are quite fast
TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E>c)
TreeSet(Comparator<? super E>comp)
TreeSet(SortedSet<E>ss)
The first form constructs an empty tree set that will be sorted in
ascending order according to the natural order of its elements.
The second form builds a tree set that contains the elements of c.
The third form constructs an empty tree set that will be sorted according
to the comparator specified by comp.
The fourth form builds a tree set that contains the elements of ss.
Example:
// Demonstrate TreeSet.
import java.util.*;
class TreeSetDemo {
publicstaticvoid main(String args[]) {
// Create a tree set.
TreeSet<String>ts = new TreeSet<String>();
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
Output:
[A, B, C, D, E, F]

The PriorityQueue Class:


PriorityQueue extends AbstractQueue and implements the Queue
interface.
It creates a queue that is prioritized based on the queue’s comparator.
PriorityQueue defines the six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(Comparator<? super E>comp) (Added by JDK 8.)
PriorityQueue(int capacity, Comparator<? super E>comp)
PriorityQueue(Collection<? extends E>c)
PriorityQueue(PriorityQueue<? extends E>c)
PriorityQueue(SortedSet<? extends E>c)
The first constructor builds an empty queue. Its starting capacity is 11.
The second constructor builds a queue that has the specified initial
capacity.
The third constructor specifies a comparator, and the fourth builds a
queue with the specified capacity and comparator.
The last three constructors create queues that are initialized with the
elements of the collection passed in c.
In all cases, the capacity grows automatically as elements are added.
The ArrayDeque Class:
The ArrayDeque class extends AbstractCollection and implements the
Deque interface.
It adds no methods of its own. ArrayDeque creates a dynamic array and
has no capacity restrictions.
ArrayDeque defines the following constructors:
ArrayDeque( )
ArrayDeque(int size)
ArrayDeque(Collection<? extends E>c)
The first constructor builds an empty deque. Its starting capacity is 16.
The second constructor builds a deque that has the specified initial
capacity.
The third constructor creates a deque that is initialized with the elements
of the collection passed in c.
In all cases, the capacity grows as needed to handle the elements added
to the deque.
Example:
// Demonstrate ArrayDeque.
import java.util.*;

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

ACCESSING A COLLECTION VIA AN ITERATOR:


Iterator enables you to cycle through a collection, obtaining or removing
elements.
ListIterator extends Iterator to allow bidirectional traversal of a list, and
the modification of elements.
The Methods Declared by Iterator:

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+

Advantage of Iterator over for-each method

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

The For-Each Alternative to Iterators


// Use the for-each for loop to cycle through a collection.
import java.util.*;

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:

The Map Interface:


The Map interface maps unique keys to values.
A key is an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object.
After the value is stored, you can retrieve it by using its key.
The Methods Declared by Map:
The SortedMap Interface:
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending
order based on the keys.
The Methods Declared by SortedMap:
The NavigableMap Interface:
The NavigableMap interface extends SortedMap and declares the behavior of a
map that supports the retrieval of entries based on the closest match to a
given key or keys.
The Methods Declared by NavigableMap:
The NavigableMap Interface:
The NavigableMap interface extends SortedMap and declares the behavior of a map
that supports the retrieval of entries based on the closest match to a given key or keys.
The Methods Declared by NavigableMap:
THE MAP CLASSES:

The Map.Entry Interface:


The Map.Entry interface enables you to work with a map entry. Recall that the entrySet(
) method declared by the Map interface returns a Set containing the map entries. Each of
these set elements is a Map.Entry object.
The Non-Static Methods Declared by Map.Entry:

AbstractMap is a superclass for all concrete map implementations.


The HashMap Class:
The HashMap class extends AbstractMap and implements the Map interface. It uses a
hash table to store the map. This allows the execution time of get( ) and put( ) to remain
constant even for large sets.
The following constructors are defined:
HashMap( )
HashMap(Map<? extends K, ? extends V>m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
Example:
import java.util.*;
class HashMapDemo {
publicstaticvoid main(String args[]) {
// Create a hash map.
HashMap<String, Double>hm = new HashMap<String,
Double>();
// Put elements to the map
hm.put("John Doe", newDouble(3434.34));
hm.put("Tom Smith", newDouble(123.22));
hm.put("Jane Baker", newDouble(1378.00));
hm.put("Tod Hall", newDouble(99.22));
hm.put("Ralph Smith", newDouble(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>>set = hm.entrySet();
// Display the set.
for (Map.Entry<String, Double>me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
//Deposit 1000 into John Doe's account.
doublebalance = hm.get("John Doe");
hm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}
Output:
Tod Hall: 99.22
John Doe: 3434.34
Ralph Smith: -19.08
Tom Smith: 123.22
Jane Baker: 1378.0
John Doe's new balance: 4434.34
The TreeMap Class:
The TreeMap class extends AbstractMap and implements the NavigableMap interface. It
creates maps stored in a tree structure. A TreeMap provides an efficient means of storing
key/value pairs in sorted order and allows rapid retrieval.
The following TreeMap constructors are defined:
TreeMap( )
TreeMap(Comparator<? super K>comp)
TreeMap(Map<? extends K, ? extends V>m)
TreeMap(SortedMap<K, ? extends V>sm)
Example:
import java.util.*;
class TreeMapDemo {
publicstaticvoid main(String args[]) {
// Create a tree map.
TreeMap<String, Double>tm = new TreeMap<String,
Double>();
// Put elements to the map.
tm.put("John Doe", newDouble(3434.34));
tm.put("Tom Smith", newDouble(123.22));
tm.put("Jane Baker", newDouble(1378.00));
tm.put("Tod Hall", newDouble(99.22));
tm.put("Ralph Smith", newDouble(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>>set = tm.entrySet();
// Display the elements.
for (Map.Entry<String, Double>me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account.
doublebalance = tm.get("John Doe");
tm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}
Output:
Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Tod Hall: 99.22
Tom Smith: 123.22
John Doe's new balance: 4434.34
The LinkedHashMap Class:
•LinkedHashMap extends HashMap.
•It maintains a linked list of the entries in the map, in the order in which they were
inserted.
•This allows insertion-order iteration over the map. That is, when iterating through a
collection-view of a LinkedHashMap, the elements will be returned in the order in which
they were inserted.
•You can also create a LinkedHashMap that returns its elements in the order in which
they were last accessed.
LinkedHashMap defines the following constructors:
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)
The IdentityHashMap Class:
IdentityHashMap extends AbstractMap and implements the Map interface. It is similar
to HashMap except that it uses reference equality when comparing elements.
The EnumMap Class:
EnumMap extends AbstractMap and implements Map. It is specifically for use with keys
of an enum type.
10. Assignment
Employee Register
You need to maintain the details of all employees of an Organization.
The following details of the employee needs to be maintained
First Name
Last Name
Mobile Number
Email
Address
There is no higher limit to store the number of employee in our application.
Get the number ofemployees first before getting all the employee details.
Collect all employee details and store them in an appropriate collection
type, so that when thecollection is printed, it prints the employee details
sorted by their first name.
Use Generics.
Note:
In case of Java, Use Java Format Specifier:
System.out.format("%-15s %-15s %-15s %-30s %-
15s\n","Firstname","Lastname","Mobile","Email","Address");
Sample Output:
Enter the Number of Employees
2
Enter Employee 1 Details:
Enter the Firstname
Janani
Enter the Lastname
Velmurugan
Enter the Mobile
7890123
Enter the Email
janani.velmurugan@gmail.com
Enter the Address
Chennai
Employee List:
FirstName SecondName MobileNumber Email Address
Anitha Ramesh 9906699224 anitha.ram@gmail.com Bangalore
Janani Velmurugan 7890123000 janani.vel@gmail.com Chennai
11. PART A
1.Compare expression lambdas and block
lambdas? Give an example. (K1,CO4)

The body of the lambdas shown in the


preceding examples consist of a single
expression. These types of lambda bodies are
referred to as expression bodies, and
lambdas that have expression bodies are
sometimes called expression lambdas.

Java supports a second type of lambda


expression in which the code on the right side
of the lambda operator consists of a block of
code that can contain more than one
statement. This type of lambda body is called a
block body. Lambdas that have block bodies
are sometimes referred to as block lambdas.

Example:
Expression Lambda ()->123.45

Block Lambda

(n) -> {

int result = 1;
for (int i=1;i<=n;i++) result=i*result;

return result;

};

2.Define functional interface (K1,CO4)


A functional interface is an interface that
contains one and only one abstract method.
This method specifies the intended purpose of
the interface. A functional interface typically
represents a single action. For example, the
standard interface Runnable is a functional
interface because it defines only one method:
run( ).

3.What is mutable object and immutable


object? Give example (K1,CO4)
When you create a String object, you are creating a string that cannot be
changed. Each time you need an altered version of an existing string, a new
String object is created that contains the modifications. The original string is
left unchanged.

StringBuffer and StringBuilder-Both hold strings that can be modified after


they are created

4.What is the main difference between StringBuffer and StringBuilder?


(K1,CO4)

StringBuilder is similar to StringBuffer except for one important difference: it


is not synchronized, which means that it is not thread-safe. The advantage of
StringBuilder is faster performance.

5.What are the different ways of constructing a String object?


(K1,CO4)
String s = new String(); String(char chars[ ])

String(char chars[ ], int startIndex, int numChars) String(String strObj)

6.What is the difference between equals() and == in Java Strings.


(K1,CO4)
equals( ) method compares the characters inside a String object. The ==
operator compares two object references to see whether they refer to the same
instance.

7.Write a java program to check whether a given string is palindrome


or not. (K3,CO4)

public class StringDemo {


public static void main(String[] args) { String str="Hello";

StringBuffer sb=new StringBuffer(str); StringBuffer

revsb=sb.reverse();

if(str.equals(revsb)) System.out.println("Palindrome");
else

System.out.println("Not Palindrome");

8. Differentiate between an ArrayList and an LinkedList


(K1,CO4)

9. What do you understand by Iterator in the Java Collection Framework?


(K1,CO4)

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.

3.Within the loop, obtain each element by calling next( ).

10.What is the use of the List interface? (K1,CO4)

 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

11.What is ArrayList in Java? (K1,CO4)

 The ArrayList class extends AbstractList and implements the List interface.

 ArrayList supports dynamic arrays that can grow as needed.


 Standard arrays are of fixed size. After arrays are created they cannot grow
or shrink.

 It provides more powerful insertion and search mechanisms than arrays.

 Gives faster Iteration and fast random access.

 Ordered Collection (by index), but not Sorted.


12.How would you convert an ArrayList to Array and an Array to
ArrayList? (K1,CO4)

An Array can be converted into an ArrayList by making use of the asList()


method provided by the Array class. It is a static method that accepts List
objects as a parameter. The toArray() is used to convert ArrayList into an
Array.

13.What is a Vector in Java? (K1,CO4)


Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector. Vector implements a dynamic array.
Also, the vector is not limited to a specific size, it can shrink or grow
automatically whenever required. It is similar to ArrayList, but with two
differences:

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)

• HashSet stores the elements by using a mechanism called hashing.

• HashSet contains unique elements only.

• HashSet allows null value.

• HashSet class is non synchronized.


• HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.

• HashSet is the best approach for search operations.

• The initial default capacity of HashSet is 16.

15. What is LinkedHashSet in Java Collections Framework?


(K1,CO4)

• Java LinkedList class can contain duplicate elements.

• Java LinkedList class maintains insertion order.

• Java LinkedList class is non synchronized.

• In Java LinkedList class, manipulation is fast because no shifting needs to


occur.

• Java LinkedList class can be used as a list, stack or queue.

16.What are the advantages of the Collection Framework in Java?


(K1,CO4)
The java.util package contains one of Java’s most powerful subsystems: the
Collections Framework.

The Collections Framework is a sophisticated hierarchy of interfaces and classes


that provide state-of-the-art technology for managing groups of objects.

17.List down the different Collection views provided by the Map


interface in the Java Collection framework? (K1,CO4)

The Map interface provides 3 views of key-value pairs which are:

• key set view

• value set view

• entry set view

18.What is Map interface in Java? (K1,CO4)

• A Map doesn't allow duplicate keys,

• but you can have duplicate values.

• HashMap and LinkedHashMap allow null keys and values,

• but TreeMap doesn't allow any null key or value.


19. Why Map doesn’t extend the Collection Interface? (K1,CO4)
•The main reason Map doesn’t extend the Collection interface is that the add(E e)
method of the Collection interface doesn’t support the key-value pair like Map
interface’s put(K, V) method. It might not extend the Collection interface but still is
an integral part of the Java Collections framework.

20. What are different ways to iterate over a list? (K1,CO4)

•iterator()

•for each loop

•listiterator()

21. What are the basic interfaces of Java Collections Framework?


(K1,CO4)

•List

•Set

•Queue

22. List out the common Exceptions raised by various collections.


(K1,CO4)

•UnsupportedOperationException the operation is not supported by the collection.


•A ClassCastException is generated when one object is incompatible with another,
such as when an attempt is made to add an incompatible object to a collection.

•A NullPointerException is thrown if an attempt is made to store a null object and


null elements are not allowed in the collection.

•An IllegalArgumentException is thrown if an invalid argument is used.


•An IllegalStateException is thrown if an attempt is made to add an element to a
fixed-length collection that is full.

23. What is a regular expression? (K1,CO4)


The regular expression package, java.util.regex lets you perform sophisticated
pattern matching operations. A regular expression is a string of characters that
describes a character sequence. This general description, called a pattern, can then
be used to find matches in other character sequences. Regular expressions can
specify wildcard characters, sets of characters, and various quantifiers.
24. Write down the two classes which supports the regular expression.
(K1,CO4)

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.

5. List out all the methods in ArrayList with an example.


6. Write a program to insert, delete, search and sort elements in ArrayList.
7. Draw the hierarchy of collection framework and explain.
8. Explain all the methods in the Set interface and write a program to print the
unique elements in a list of elements using collection.

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

17. Write a program to find the longest repeating sequence in a string


PART - B

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)

4. Classify the generic in java with example. (K2, CO4)


5. Explain briefly about generic classes and methods in java programming. (K5,
CO4)
6. Evaluate how generic methods and generic expressions are translated. (K6, CO4)
7. Design two threads to display odd numbered element in an array of size 50 and
even numbered elements in another array in size 50. create instances of the above
thread and run them. (K6, CO4)
13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications

• 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;

// else return the front element


return A.get(front);
}
Implement Queue in Java using Arrays
// Method 2
// Returns value of element at rear
T rear()
{
// If it is not pointing to any element in queue
if (rear == -1)
return null;
return A.get(rear);
}
// Method 3
// Inserts element at the front of queue
void enqueue(T X)
{
// If queue is empty
if (this.empty()) {
front = 0;
rear = 0;
A.add(X);
}
// If queue is not empty
else {
front++;
if (A.size() > front) {
// Mov front pointer to next
A.set(front, X);
}
else
// Add element to the queue
A.add(X);
}
}
Implement Queue in Java using Array
// Method 4
// Deletes elements from the rear from queue
void dequeue()
{
// if queue doesn't have any elements
if (this.empty())
// Display message when queue is already empty
System.out.println("Queue is already empty");
// If queue has only one element
else if (front == rear) {
// Both are pointing to same element
front = rear = -1;
}
// If queue has more than one element
else {
// Incrememnt the rear
rear++;
}
}
// Method 5
// Checks whether the queue is empty
boolean empty()
{
// Both are initialized to same value
// as assigned at declaration means no queue made
if (front == -1 && rear == -1)
return true;
return false;
}
Implement Queue in Java using
// Method 6
// Print the queue
// @Override
public String toString()
{
if (this.empty())
return "";
String Ans = "";
for (int i = rear; i < front; i++) {
Ans += String.valueOf(A.get(i)) + "->";
}
Ans += String.valueOf(A.get(front));
return Ans;
}
}
// Class 2
// Main class
class Main {

// Main driver method


public static void main(String args[])
{
// Case 1 : Integer Queue

// Creating object of queue Class (user defined)


// Declaring object of integer type
queue<Integer> q1 = new queue<>();

// Pushing elements to the integer object created


// Custom input integer entries
q1.enqueue(5);
q1.enqueue(10);
q1.enqueue(20);
Implement Queue in Java using Array
// Print the queue after inserting integer elements
System.out.println(
"q1 after enqueue of 3 elements:\n" + q1);
q1.dequeue();
System.out.println("q1 after dequeue :\n" + q1);
// Case 2 : String Queue
// Creating object of queue Class (user defined)
// Declaring object of string type
queue<String> q2 = new queue<>();
// Pushing elements to the String object created
// Custom input string entries
q2.enqueue("hello");
q2.enqueue("world");
q2.enqueue(“Dear Students");
// Print the queue after inserting string elements
System.out.println(
"\nq2 after enqueue of 3 elements:\n" + q2);
// Printing front and rear of the above queue
System.out.println("q2 front = " + q2.front()
+ ", q2 rear = " + q2.rear());
// Case 3 : Float Queue
// Creating object of queue Class (user defined)
// Declaring object of float type
queue<Float> q3 = new queue<>();
// Display message only
System.out.println(
"\nCreated new Float type queue q3...");
// Display whether queue is empty or not
// using the empty() method
System.out.println(
"Checking if queue is empty or not :\n"
+ q3.empty());
}
}
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 IAT 1 20.09.2021 25.09.2021 UNIT 1 & 2

2 IAT 2 22.10.2021 28.10.2021 UNIT 3 & 4

3 REVISION 13.11.2021 16.11.2021 UNIT 5 , 1 & 2

4 MODEL 18.11.2021 29.11.2021 ALL 5 UNITS

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:

Current Rates of interest


Maturity Period General Senior Citizen
7 days to 14 days 4.50 5.00

15 days to 29 days 4.75 5.25

30 days to 45 days 5.50 6.00

45 days to 60 days 7 7.50

61 days to 184 days 7.50 8.00

185 days to 1 year 8.00 8.50

Rate of FD interest for amounts above 1 Crore:

Maturity Period Interest Rate


7 days to 14 days 6.50
15 days to 29 days 6.75
30 days to 45 days 6.75
45 days to 60 days 8

61 days to 184 days 8.50

185 days to 1 year 10.00


Rate of RD interests:
Current Rates of interest
Maturity
General Senior Citizen
Period
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21 months 8.75 9.25

SB Account interest rates:


Type of Account Interest Rate

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()

Hint: Use method overriding


Sample Output:
Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
1

Enter the Average amount in your account: 10000


Interest gained: Rs. 400 Select the option:
1.Interest Calculator –SB
2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
2

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 65


Interest gained is: 800 Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 34

Interest gained is: 750


Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit

Enter the FD amount: 10000

Enter the number of days: -7

Enter your age: 78

Invalid Number of days. Please enter correct values.


Thank you

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.

You might also like