Advanced Java Unit 4 Digital Notes
Advanced Java Unit 4 Digital Notes
2
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 for 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.
3
22CS305
Advanced Java Programming
(Lab Integrated)
Department : CSE/IT/ADS/CSD/CSBS/ECE
Batch / Year : 2023 – 2027 / II
Created by : All Subject Handling Staff Members
Date : 29.06.2024
4
Table of Contents
Pag
Sl.No. Topic
e
No
.
1 Course Objectives 6
2 Syllabus 7
3 Pre-requisites 10
4 Course Outcomes 11
5 CO- PO Mapping 12
6 Lecture Plan 13
7 Activity-based learning 14
8 Lecture Notes 15
9 Assignments I - V 71 - 75
11 Part B Questions 78
13 Real-Time Applications 80
15 Assessment Schedule 84
17 Mini Projects I - V 5
86-93
1. Course Objectives
OBJECTIVES: ( To be updated )
Gain a comprehensive understanding of the Java Collections Framework and its various
Learn the details of Java I/O streams and utility classes for managing dates, numbers, and
currencies.
Develop a thorough understanding of the Stream API introduced in Java 8 and its various
operations.
Explore advanced object serialization and string tokenizing techniques, including pattern
Understand advanced Stream API features and gain proficiency in using regular expressions
6
2. Syllabus
22CS305 ADVANCED JAVA PROGRAMMING (LAB INTEGRATED) L T P C
3 0 2 4
UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6
Introduction to Collections Framework - Collection Interface- Methods in Collection
Interface - - Iterable and Iterator Interfaces - List Interface- ArrayList - LinkedList - Set
Interface - HashSet- LinkedHashSet - TreeSet - Map Interface - HashMap -
LinkedHashMap- TreeMap - Queue Interface -PriorityQueue - Deque Interface - Utility
Classes.
List of Exercises
1. Write a program that measures the time taken for insertion, deletion, and search
operations on ArrayList, LinkedList, HashSet, and TreeSet for varying sizes of input data.
2. Implement a custom data structure that combines features of a list and a set.
3. Write a Java program to create a HashMap where the keys are strings, and the values are
integers Add five key-value pairs to the map. Print all the keys and values in the map.
Remove an entry by key. Update the value associated with a specific key. Check
2. Write a program that formats dates and currencies according to different locales.
3. Implement a java program that allows users to open a text file, navigate through it
using random access, insert, delete, and modify text at specific positions within the file.
7
UNIT III STREAM API AND FUNCTIONAL PROGRAMMING 9+6
PARADIGMS
Overview of Stream API - Importance of Stream API in Java 8 and Beyond – Functional
Programming Concepts - Creating Streams - Stream Interface Methods - Stream
Operations- Intermediate Filtering (filter)-Mapping (map, flatMap)-Sorting (sorted)-
Distinct (distinct)- Limit and Skip (limit, skip) - Terminal Operations -Collecting Results
(collect) - Reducing and Summarizing (reduce, summaryStatistics)-Iterating (forEach) -
Matching and Finding (anyMatch, allMatch, noneMatch, findFirst, findAny) -Counting
(count).
List of Exercises
1. Write a program that performs stream operations like filtering, mapping, and reducing.
2. Create an infinite stream generator that generates prime numbers. Implement
methods to check for primality and generate the next prime number.
3. Write a program that reads a text file containing sentences. Tokenize each sentence
into words, filter out stopwords, and print the remaining words.
String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern
Matching, Tokenizing - Object Serialization - Serializable Interface - Writing and Reading
Serializable Objects -Transient Keyword- SerialVersionUID - Advanced I/O - Piped
Streams (PipedInputStream and PipedOutputStream) – SequenceInputStream –
PushbackInputStream and PushbackReader.
List of Exercises
1. Write a program that reads a text file and tokenizes it into sentences using the
StringTokenizer class.
2. Create a class hierarchy representing different types of objects (e.g., Person,
Employee). Serialize instances of these classes to a file using object serialization.
3. Implement a program that uses advanced I/O techniques like PipedInputStream,
PipedOutputStream, SequenceInputStream, and PushbackInputStream.
8
UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+6
Importance and Use Cases of Advanced Stream Features - Creating Custom Streams –
Stream Generators (Stream.generate, Stream.iterate) - Infinite Streams -Using
Spliterators – Advanced Stream Operations - FlatMapping - Chaining Stream Operations
- Stream Peeking (peek) - Advanced Filtering Techniques- Introduction to Regular
Expressions - Character Classes - Quantifiers - Pattern Matching - Groups and Capturing
List of Exercises
1. Implement custom stream generators using Stream.generate and Stream.iterate
methods.
2. Write a program that demonstrates advanced stream operations like flatMapping,
chaining stream operations, and peeking.
tasks such as splitting strings, replacing text, and extracting specific patterns.
TEXT BOOKS:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals," 12th Edition, 2019.
5. Alan Mycroft and Martin Odersky, "Programming in Scala," 4th Edition, 2020.
REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition, 2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional Programming”,
1st Edition, 2014.
9
3. Pre-
requisites
10
4. Course Outcomes
At the end of this course, the students will be able to:
CO5 Effectively use regular expressions for advanced text processing tasks. K3
11
5. CO-PO Mapping
Program Status
Program Outcomes
Course Outcomes
Outcomes PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 3 3 - - - - - - - - - 3 2 2
CO2 3 2 2 - - - - - - - - - 3 3 2
CO3 3 2 2 - - - - - - - - - 3 3 2
CO4 3 2 2 - - - - - - - - - 3 3 2
CO5 3 2 2 - - - - - - - - - 3 3 2
CO6 3 2 2 - - - - - - - - - 3 3 2
12
Sl. No
6. LECTURE PLAN Taxono
No. of. Proposed Actual Pertaining Mode of
. Topics my
Periods Date Date CO Level Delivery
As per
As per
Time
Time table
table MD 1,
1,2 2 & CO1, CO6 K3
& MD 4
Academic
Academic
Calendar
Calendar
As per
As per
Time
Time table
table MD 1,
3 1 & CO1,CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
Time table
table MD 1,
4 1 & CO1, CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
Time table
table MD 1,
5 1 & CO1, CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
Time table
table MD 1,
6,7 2 & CO1, CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
Time table
table MD 1,
8 1 & CO1, CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
Time table
table MD 1,
9 1 & CO1, CO6 K3
Academic & MD 4
Calendar Academic
Calendar
As per
As per
Time
10- 15 Time table
& table
6 CO1, CO6 K3 iamneo
Academic &
Calendar Academic
* MD1 – Oral Presentation Calendar
13
* MD 4 – Hands on using any Java IDE
7. Activity Based Learning
Common Activities
Draw a detailed Mind Map diagram to create a visual representation which illustrates the
different classes and methods within Java Collections Framework . Include key details such as
interfaces, classes and their respective implementations, along with methods commonly used
for each type which provides a comprehensive overview of how collections are organized and
14
9. Lecture Notes
STRINGTOKENIZER
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object internally
maintains a current position within the string to be tokenized. Some operations advance this current
position past the characters processed.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
It provides the first step in the parsing process often called lexer or scanner.
StringTokenizer in Java is a utility class that breaks a string into pieces or multiple strings called
“tokens”. For example, strings separated by space and tab characters are tokens. These tokens are
separated with the help of a delimiter.
A Delimiter is a group of characters that separate tokens. Each character in the delimiter is considered a
valid delimiter. For example, comma, semicolons, and colon are sets of delimiters.
By default, space, tab, newline, and carriage return are used to separate the strings. But we can also use
any other characters to separate tokens. Let’s understand Java StringTokenizer with an example.
9. Lecture Notes
Suppose we have a string “Hello Scientech Easy”. If we define a space as a delimiter, this string has the
following three tokens:
1. Hello
2. Scientech
3. Easy
If we define a comma as a delimiter after “Hello”, the same string has the following two tokens:
1. Hello
2. Scientech Easy
StringTokenizer was added in Java 1.0 version and now it is not part of the Java Collections Framework.
It is present in java.util package.
If you want to use StringTokenizer, you must import java.util package or at least StringTokenizer class
into your application.
If you want to use StringTokenizer, you must import java.util package or at least StringTokenizer class
into your application.
extends Object
implements Enumeration<Object>
9. Lecture Notes
Constructors of StringTokenizer Class:
The StringTokenizer class defines the following constructors that are as follows:
1. StringTokenizer(String str): This constructor is used to construct a string tokenizer for the specified
string str. The parameter str is a string that will be tokenized. The default delimiters are used.
2. StringTokenizer(String str, String delim): This constructor is used to construct a string tokenizer
for the specified string and delimiter. The parameter delim is a string that represents delimiters to
separate the tokens.
If the delimAsToken is true, delimiter characters are returned as tokens. If it is false, delimiter
characters are not returned and serve to separate tokens. Delimiters are not returned as tokens by the
first two forms of the constructor.
StringTokenizer class in Java is useful to separate tokens. These tokens are then stored in the
StringTokenizer object from where they can be retrieved.
Example
import java.util.StringTokenizer;public
class Main {
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken()); } }}
9. Lecture Notes
Tokens in the sentence:
blessing
on
In the above statement, the actual string str is broken into multiple strings or tokens at the position
marked by delimiters. A StringTokenizer object returns one token at a time. We can also change the
delimiter anytime.
For example, to break the string “Hello Scientech easy” whenever a comma is found, we can write as
follows:
Similarly, to break a string whenever a comma, or semi-colon, or both are found, we can specify
delimiters as follows:
Similarly, to break a string with default delimiters such as space, tab, or newline, we can create object as:
import java.util.StringTokenizer;
public class StringTokens {
public static void main(String[] args)
{
// Take a string.
String str = "He is a gentle man";
// Create an object of string tokenizer and break into tokens. Here, delimiters are a space and a comma.
StringTokenizer st = new StringTokenizer(str, delimiters);
Output:
Number of tokens: 5
Tokens are:
He
is
a
gentle
man
.
9. Lecture Notes
Explanation:
In this example program, we take a string and break it into tokens
whenever a space and comma are found in the string. The tokens are
retrieved from the string tokenizer object as string and then displayed on
the console. Look at the below figure.
9. Lecture Notes
Split() method:
The split() method of String class takes a regular expression as a delimiter. Look at the source
code.
Program code 2:
public class StringTokens {
public static void main(String[] args)
{
// Take a string.
String str = "You are very sweet girl";
Output:
Tokens are:
You
are
very
sweet
girl
9. Lecture Notes
Tokenizing and Formatting
String tokenization and formatting can be used to process and reformat tokens extracted from a string.
For example, we might want to capitalize the first letter of each word in a sentence. Let's look at a
complete example demonstrating tokenizing and formatting using StringTokenizer.
Example: Tokenizing and Formatting a Sentence
Input String: "hello geeks, how are you doing today?"
Objective: Tokenize the string and format each token by capitalizing the first letter of each word.
Code:
import java.util.StringTokenizer;
public class TokenizingAndFormatting {
public static void main(String[] args) {
String str = "hello geeks, how are you doing today?";
StringTokenizer tokenizer = new StringTokenizer(str, " ,?");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String formattedToken = formatToken(token);
System.out.println(formattedToken);
}
}
private static String formatToken(String token) {
if (token.length() == 0) return token;
return token.substring(0, 1).toUpperCase() + token.substring(1).toLowerCase();
}
}
Output:
Hello
Geeks
How
Are
You
Doing
Today
9. Lecture Notes
Locating Data via Pattern Matching, Tokenizing
Locating data via pattern matching and tokenizing involves identifying specific patterns in a string and
then breaking the string down into tokens based on those patterns. This is useful in various text
processing tasks, such as extracting information from text, validating inputs, and data transformation.
java has a dedicated package, called java.util.regex, to deal with Regular Expression. This package
consists of two classes, Matcher and Pattern, an interface MatchResult, and an exception called
PatternSyntaxException.
Regular Expression is quite an extensive topic in itself. Let’s not deal with is here; instead, let’s focus
only on the tokenization preliminary through the Matcher and Pattern classes. These classes provide
supreme flexibility in the process of tokenization with a complexity to become a topic in itself. A
pattern object represents a compiled regular expression that is used by the Matcher object to perform
three functions, such as:
•Match input string against the pattern.
•Match input string, starting at the beginning against the pattern.
•Scan and look out for the next subsequence that matches the pattern.
9. Lecture Notes
Example: Locating and Tokenizing Emails in a Text
System.out.println("Located Emails:");
for (String email : emails) {
System.out.println(email);
}
System.out.println("\nTokens:");
StringTokenizer tokenizer = new StringTokenizer(text, " ,.@");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
private static ArrayList<String> locateEmails(String text) {
ArrayList<String> emails = new ArrayList<>();
Pattern emailPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA Z]{2,}");
Matcher matcher = emailPattern.matcher(text);
while (matcher.find()) {
emails.add(matcher.group());
}
return emails;
}
}
Output:
Located Emails:
[email protected]
[email protected]
Tokens:
Contact
us
at
support
example
com
or
sales
9. Lecture Notes
OBJECT SERIALIZATION:
Serialization in Java is the concept of representing an object’s state as a byte stream. The byte stream has
all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java
helps transport the code from one JVM to another and then de-serialize it there.
Deserialization is the exact opposite process of serialization where the byte data type stream is converted
back to an object in the memory. The best part about these mechanisms is that both are JVM-
independent, meaning you serialize on one JVM and de-serialize on another.
What are the Advantages of Serialization?
Serialization offers a plethora of benefits. Some of its primary advantages are:
•Used for marshaling (traveling the state of an object on the network)
•To persist or save an object’s state
•JVM independent
•Easy to understand and customize
Points to Note About Serialization in Java?
To serialize an object, there are a few conditions to be met. Some other key points need to be highlighted
before you proceed further in the article. These are the conditions and points to remember while using
serialization in Java.
•Serialization is a marker interface with no method or data member
•You can serialize an object only by implementing the serializable interface
•All the fields of a class must be serializable; otherwise, use the transient keyword (more about it later)
•The child class doesn’t have to implement the Serializable interface, if the parent class does
•The serialization process only saves non-static data members, but not static or transient data members
•By default, the String and all wrapper classes implement the Serializable interface
•Serialization interface:
The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does
not have any methods and fields. Thus classes implementing it do not have to implement any methods.
Classes implement it if they want their instances to be Serialized or Deserialized.
Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done
using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to
recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is
done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file.
Declaration :public interface Serializable
9. Lecture Notes
Writing and Reading Serializable Objects:
Let’s look at an example to understand how to serialize and de-serialize an object in Java.
The following program code will serialize a student object and save it to a file named
student.ser.
9. Lecture Notes
9. Lecture Notes
Example for Deserialization in Java:
In the code below, you will look at how to deserialize the student object that was have serialized
in the above example.
9.Lecture Notes
Transient Keyword
To prevent the serialization of a class’s data members, use the transient keyword with them. For
instance, if a program accepts the username and password of a user. The original password, however,
should not be kept in the file. Here, we can use the transient keyword, which instructs JVM to ignore
its original value and instead store the object’s default value when it reads the keyword.
9.Lecture Notes
Syntax
The syntax to use this keyword can be:
When there are data members that were derived from other data members inside the same class
instance, the transient modifier is used.
It can be applied to data members that don’t show the object’s current state.
Also, non-serialized objects or classes can utilize transient modifiers for their data members.
Differences Between Transient and Volatile keyword
Instance variables can be excluded from serialization by using the transient keyword in
conjunction with them.
9.Lecture Notes
compiler consistently read the value from the main memory and follow the ‘happens-before’
In this example, we have created two classes Student and PersistExample. The age data
member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.
9. Lecture Notes
PersistExample.java
import java.io.*;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
class PersistExample{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
9. Lecture Notes
out.close();
f.close();
System.out.println("success");
}
}
Output:
success
Physical I/O operation is thousands times slower than memory access. Hence, a chunk of data
is often cache or buffer to improve the throughput. As illustrated from the above diagram, many
layers of cache exist between your Java application and physical disk.
9.Lecture Notes
Disk Buffer is RAM that is built into the disk drive to store a block of data from the disk. The
cost of transferring data from the disk surface to the disk buffer is by far the slowest and the
most expensive operation, because it involves physical movement of the disk.
OS Buffer: OS does its own buffering as it can cache more data and manage it more elegantly.
This buffer can also be shared among the applications.
Application Buffer: Application may optionally buffer its own data.
Here are some key points about Java NIO:
Buffers: Buffers are containers for fixed amounts of data of specific primitive types. They
include:
ByteBuffer: For bytes.
CharBuffer: For characters.
IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer: For other data types
NIO data transfer is through the so-called buffers implemented in java.nio.Buffer class. A
Buffer is similar to an array, except that it is implemented much more efficiently by closely
coupled with the underlying operating system. A Buffer is a contiguous, linear storage. Similar
to an array, a Buffer has a fixed capacity.
9.Lecture Notes
CCharsets: Charsets provide named mappings between Unicode characters and bytes. They
include:
harset: Named mappings like US-ASCII and UTF-8.
CharsetDecoder: Decodes bytes into characters.
CharsetEncoder: Encodes characters into bytes
Channels: Channels represent open connections to entities capable of I/O operations. Types of
channels include:
ReadableByteChannel: Reads bytes.
WritableByteChannel: Writes bytes.
ByteChannel: Reads and writes bytes (combines ReadableByteChannel and
WritableByteChannel)
9.Lecture Notes
Java SequenceInputStream Class
Java SequenceInputStream class is used to read data from multiple streams. It reads data
sequentially (one by one).
Java SequenceInputStream Class declaration
Let's see the declaration for Java.io.SequenceInputStream class:
public class SequenceInputStream extends InputStream
Constructors of SequenceInputStream class
Constructor Description
SequenceInputStream(InputStream s1, creates a new input stream by reading the data
InputStream s2) of two input stream in order, first s1 and then
s2.
SequenceInputStream(Enumeration e) creates a new input stream by reading the data
of an enumeration whose type is InputStream.
Method Description
int read() It is used to read the next byte of data from the input
stream.
int read(byte[] ary, int off, int len) It is used to read len bytes of data from the input stream
into the array of bytes.
int available() It is used to return the maximum number of byte that can
be read from an input stream.
void close() It is used to close the input stream.
Example that reads the data from two files and writes into another file
In this example, we are writing the data of two files testin1.txt and testin2.txt into another file
named testout.txt.
package com.javatpoint;
import java.io.*;
class Input1{
public static void main(String args[])throws Exception{
FileInputStream fin1=new FileInputStream("D:\\testin1.txt");
FileInputStream fin2=new FileInputStream("D:\\testin2.txt");
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
SequenceInputStream sis=new SequenceInputStream(fin1,fin2);
int i;
while((i=sis.read())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin1.close();
fin2.close();
System.out.println("Success..");
}
}
Output:
Succeess...
testout.txt:
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.
9.Lecture Notes
SequenceInputStream example that reads data using enumeration
If we need to read the data from more than two files, we need to use Enumeration.
Enumeration object can be obtained by calling elements() method of the Vector class. Let's
see the simple example where we are reading the data from 4 files: a.txt, b.txt, c.txt and d.txt.
package com.javatpoint;
import java.io.*;
import java.util.*;
class Input2{
public static void main(String args[])throws IOException{
//creating the FileInputStream objects for all the files
FileInputStream fin=new FileInputStream("D:\\a.txt");
FileInputStream fin2=new FileInputStream("D:\\b.txt");
FileInputStream fin3=new FileInputStream("D:\\c.txt");
FileInputStream fin4=new FileInputStream("D:\\d.txt");
//creating Vector object to all the stream
Vector v=new Vector();
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
//creating enumeration object by calling the elements method
Enumeration e=v.elements();
//passing the enumeration object in the constructor
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close();
}
}
The a.txt, b.txt, c.txt and d.txt have following information:
a.txt:
Welcome
b.txt:
to
c.txt:
java
d.txt:
programming
Output:
Welcometojavaprogramming
9.Lecture Notes
Method Description
int available() It is used to return the number of bytes that
can be read from the input stream.
int read() It is used to read the next byte of data from the
input stream.
boolean markSupported()
void mark(int readlimit) It is used to mark the current position in the
input stream.
long skip(long x) It is used to skip over and discard x bytes of
data.
void unread(int b) It is used to pushes back the byte by copying it
to the pushback buffer.
void unread(byte[] b) It is used to pushes back the array of byte by
copying it to the pushback buffer.
Method Description
import java.io.*;
public class ReaderExample{
public static void main(String[] args) throws Exception {
char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};
CharArrayReader reader = new CharArrayReader(ary);
PushbackReader push = new PushbackReader(reader);
int i;
while( (i = push.read())!= -1) {
if(i == '-') {
int j;
if( (j = push.read()) == '-'){
System.out.print("#*");
}else {
push.unread(j); // push back single character
System.out.print((char)i);
}
}else {
System.out.print((char)i);
}
}
}
}
Output
1#*2-34#*-56