0% found this document useful (0 votes)
110 views47 pages

Advanced Java Unit 4 Digital Notes

Uploaded by

23102208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views47 pages

Advanced Java Unit 4 Digital Notes

Uploaded by

23102208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

1

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

10 Part A Questions & Answers 76

11 Part B Questions 78

12 Supportive Online Certifications 79

13 Real-Time Applications 80

14 Content Beyond the Syllabus 81

15 Assessment Schedule 84

16 Prescribed Text Books & Reference Books 85

17 Mini Projects I - V 5
86-93
1. Course Objectives
OBJECTIVES: ( To be updated )

The Course will enable learners to:

 Gain a comprehensive understanding of the Java Collections Framework and its various

interfaces and implementations.

 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

matching with regular expressions.

 Understand advanced Stream API features and gain proficiency in using regular expressions

for text processing.

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

if the map contains a specific key and a specific value.


UNIT II I/O OPERATIONS, SERIALIZATION, AND DATE HANDLING 9+6
Date – Calendar – Comparable interface – Observer Interface – Streams - Types of
Streams - The Byte-stream I/O hierarchy - Character Stream Hierarchy – Random
Access File class – the java.io. Console Class – Serialization – Dates - Numbers, and
Currency - Working with Dates - Numbers and Currencies.
List of Exercises
1. Create a class representing a complex object with nested data structures.
Serialize the object to a file, then deserialize it back and verify that the object
remains intact.

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.

UNIT IV ADVANCED STRING PROCESSING, OBJECT SERIALIZATION, 9+6


AND I/O TECHNIQUES

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

- Regex in Java - java.util.regex Package Pattern Class - Matcher Class - String


Manipulation with Regex - Splitting Strings - Replacing Text (replaceAll, replaceFirst) -
Replacing with Backreferences.

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.

3. Develop a program that utilizes regular expressions to perform string manipulation

tasks such as splitting strings, replacing text, and extracting specific patterns.

TOTAL: 45+30=75 PERIODS

TEXT BOOKS:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals," 12th Edition, 2019.

2. Joshua Bloch, "Effective Java," 3rd Edition, 2018.


3. Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams, and Functional-Style
Programming," 1st Edition, 2014.

4. Herbert Schildt, "Java: The Complete Reference," 11th Edition, 2018.

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

22CS305 Advanced Java Programming

22CS202 – Java programming

22CS101 – problem solving using C++

10
4. Course Outcomes
At the end of this course, the students will be able to:

CO# Course Outcomes KL

Utilize the Java Collections Framework to solve complex data structure


CO1 K3
problems..
Demonstrate proficiency in Java I/O operations and manage data
CO2 K3
efficiently.
Learn to utilize the Stream API for complex data processing by applying
CO3 K3
functional programming techniques..
CO4 Understand and implement advanced object serialization techniques. K3

CO5 Effectively use regular expressions for advanced text processing tasks. K3

CO6 Build simple applications using advanced java programming concepts. 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

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted
in iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal

Unit III Activity : - Mind Map Diagram

 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

utilized in Java programming.

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.

StringTokenizer Class Declaration

StringTokenizer class can be declared in a general form as follows:

public class StringTokenizer

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.

3. StringTokenizer(String str, String delim, boolean delimAsToken): This form of constructor


constructs StringTokenizer with specified string, delimiter, and returnValue.

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.

To use StringTokenizer class in java, we need to create an object of StringTokenizer class is as


follows:

StringTokenizer st = new StringTokenizer(str, "delimiter");

Example

import java.util.StringTokenizer;public

class Main {

public static void main(String[] args) {

String sentence = "A blessing on disguise";

StringTokenizer tokenizer = new StringTokenizer(sentence);

System.out.println("Tokens in the sentence:");

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:

StringTokenizer st = new StringTokenizer("Hello Scientech Easy", ",");

Similarly, to break a string whenever a comma, or semi-colon, or both are found, we can specify
delimiters as follows:

String delimiters = ",;";

StringTokenizer st = new StringTokenizer("Hello Scientech Easy", delimiters);

Similarly, to break a string with default delimiters such as space, tab, or newline, we can create object as:

"StringTokenizer st = new StringTokenizer("Hello Scientech Easy"););

Methods of StringTokenizer in Java


StringTokenizer class has defined the following methods that are as follows:
1. int countTokens(): This method counts and returns the number of tokens available in the
StringTokenizer object.
2. boolean hasMoreTokens(): This method checks if there are more tokens available in the
StringTokenizer object or not. If the next token is available, it will return true.
3. String nextToken(): This method returns the next token from the string tokenizer object.
4. String nextToken(String delim): It returns the next token from the string tokenizer object based
on the delimiter.
5. boolean hasMoreElements(): It returns the same value as the hasMoreTokens method.
6. Object nextElement(): It returns the same value as the nextToken method, but its return type is
Object.
9. Lecture Notes
Java StringTokenizer Example Programs

import java.util.StringTokenizer;
public class StringTokens {
public static void main(String[] args)
{
// Take a string.
String str = "He is a gentle man";

// Take a string for delimiters.


String delimiters = " ,"; // Here, delimiters are a space and a comma.

// Create an object of string tokenizer and break into tokens. Here, delimiters are a space and a comma.
StringTokenizer st = new StringTokenizer(str, delimiters);

// Counts the number of tokens available in string tokenizer object.


int counts = st.countTokens();
System.out.println("Number of tokens: " +counts);

// Now retrieve tokens from st and display them.


System.out.println("Tokens are: ");
while(st.hasMoreTokens()){
String tokens = st.nextToken();
System.out.println(tokens);
}
}
}

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

// Take a string for delimiters.


String delimiters = "[ ,]+"; // Here, delimiters are a space and a comma.

// Split the string into tokens using String.split() method.


System.out.println("Tokens are: ");
String[] s = str.split(delimiters);

for(int i = 0 ; i < s.length; i++) {


System.out.println(s[i]);
}
}
}

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

Input String: "Contact us at [email protected] or [email protected]. Visit our website at


https://example.com."
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

public class PatternMatchingAndTokenizing {


public static void main(String[] args) {
String text = "Contact us at [email protected] or [email protected]. Visit our website at
https://example.com.";
ArrayList<String> emails = locateEmails(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:

The writeObjembgct() method of the ObjectOutputStream class for serialization and


readObject() method of the InputObjectStream class for deserialization purpose.

Syntax for the writeObject() method:

public final void writeObject(Object o) throws IO ExceptionSyntax for the readObject()


method:

public final Object readObject() throws IOException, ClassNotFoundException

Let’s look at an example to understand how to serialize and de-serialize an object in Java.

Example for Serialization 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

 Transient is a variables modifier used in serialization.


 In Java, Serialization is used to convert an object into a stream of the byte. The byte stream
consists of the data of the instance as well as the type of data stored in that instance.
Deserialization performs exactly opposite operation. It converts the byte sequence into original
object data.
 During the serialization, when we do not want an object to be serialized we can use
a transient keyword.
 When JVM comes across transient keyword, it ignores original value of the variable and save
default value of that variable data type.
 transient keyword plays an important role to meet security constraints.
 There are various real-life examples where we don’t want to save private data in file. Another use
of transient keyword is not to serialize the variable whose value can be calculated/derived using
other serialized objects or system such as age of a person, current date, etc.
 Practically we serialized only those fields which represent a state of instance, after all serialization
is all about to save state of an object to a file.
 It is good habit to use transient keyword with private confidential fields of a class during
serialization.

Why Use Transient In Java?

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:

private transient <member variable>;


or
transient private <member variable>;

When To Use The Transient Keyword?

 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’

relationship on the visibility of the volatile variable in between various threads.


 Volatile keywords can be used along with static keywords, but transient keywords cannot be
used.
 During deserialization, transient variables are provided with default values, and the application
code must manage their assignment or the value restoration.
 Example
 We have declared a class as Student, it has three data members id, name and age. If you
serialize the object, all the values will be serialized but we don't want to serialize one value,
e.g. age then we can declare the age data member as transient.

 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

Now write the code for deserialization.


DePersist.java
import java.io.*;
class DePersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
in.close(); } }
Output:
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
9.Lecture Notes
SerialVersionUID

 The serialVersionUID attribute is an identifier that is used to serialize/deserialize an object of


a Serializable class.
 The serialization at runtime associates with each serializable class a version number called a
serialVersionUID, which is used during deserialization to verify that the sender and receiver of a
serialized object have loaded classes for that object that are compatible with respect to serialization.
 It is because SerialVersionUID is used to ensure that during deserialization the same class (that
was used during serialize process) is loaded.
 Serialization at the time of serialization, with every object sender side JVM will save a Unique
Identifier.
 JVM is responsible to generate that unique ID based on the corresponding .class file which is
present in the sender system.
Deserialization at the time of deserialization, receiver side JVM will compare the unique ID
associated with the Object with local class Unique ID i.e. JVM will also create a Unique ID based on
the corresponding .class file which is present in the receiver system.
9. Lecture Notes
 If both unique ID matched then only deserialization will be performed. Otherwise, we will get
Runtime Exception saying InvalidClassException. This unique Identifier is nothing
but SerialVersionUID.
 There are also certain problem associations depending on the default SerialVersionUID
generated by JVM as listed below:
 Both sender and receiver should use the same JVM with respect to platform and version also.
Otherwise, the receiver is unable to deserialize because of different SerialVersionUID.
 Both sender and receiver should use the same ‘.class’ file version. After serialization, if there
is any change in the ‘.class’ file at the receiver side then the receiver is unable to deserialize.
 To generate SerialVersionUID internally JVM may use complex algorithms which may create
performance problems.
 Implementation:
 We can solve the above problem by configuring our own SerialVersionUID. We can
configure our own SerialVersionUID for which we need 3 classes as follows:
 Random class which contains two variables which are going to Serialize, let it be ‘Geeks’
 Class for sender side which is going to Serialize an object
 Class for receiver side which is going to deserialize
9. Lecture Notes
Syntax:
private static final long SerialVersionUID = 101;
Example
import java.io.*;
class Employee implements Serializable {
private static final long serialVersionUID = 5462223600l;
int empId;
String name;
String location;
Employee(int empId, String name, String location) {
this.empId = empId;
this.name = name;
this.location = location;
}
void empData() {
System.out.println("Employee Id is: "+ empId);
System.out.println("Employee Name is: "+ name);
System.out.println("Employee Location is: "+ location);
}
}
public class EmployeeTest {
public static void main(String[] args)throws Exception{
Employee emp = new Employee(115, "Raja", "Hyderabad");
emp.empData();
FileOutputStream fos = new FileOutputStream("E:\Employee.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(emp);
System.out.println("Object Serialized"); } }
Output
Employee Id is: 115
Employee Name is: Raja
Employee Location is: Hyderabad
Object Serialized
9.Lecture Notes
Advanced Input & Output (I/O)
 JDK 1.4 introduced the so-called New I/O (or NIO), in java.nio package and its auxiliary
packages, to support high performance and intensive I/O operations. NIO is meant to complement
the existing Standard I/O (in java.io package), not as a replacement.
 Java NIO (New Input/Output) is a high-performance networking and file handling API
introduced in JDK 4. It serves as an alternative to the standard Java I/O system, offering advanced
features and a different programming model.

 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.

Methods of SequenceInputStream class

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.

Java SequenceInputStream Example


In this example, we are printing the data of two files testin.txt and testout.txt.
package com.javatpoint;
import java.io.*;
class InputStreamExample {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
9.Lecture Notes
inst.close();
input1.close();
input2.close();
}
}
Here, we are assuming that you have two files: testin.txt and testout.txt which have following
information:
testin.txt:
Welcome to Java IO Programming.
testout.txt:
It is the example of Java SequenceInputStream class.
After executing the program, you will get following output:
Output:
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.

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

Java PushbackInputStream Class

Java PushbackInputStream class overrides InputStream and provides extra functionality to


another input stream. It can unread a byte which is already read and push back one byte.
Class declaration
Let's see the declaration for java.io.PushbackInputStream class:
public class PushbackInputStream extends FilterInputStream
Class Methods
It is used to test if the input stream support mark and reset method.

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.

void reset() It is used to reset the input stream.


void close() It is used to close the input stream.

Example of PushbackInputStream class


import java.io.*;
public class InputStreamExample {
public static void main(String[] args)throws Exception{
String srg = "1##2#34###12";
byte ary[] = srg.getBytes();
ByteArrayInputStream array = new ByteArrayInputStream(ary);
PushbackInputStream push = new PushbackInputStream(array);
int i;
9.Lecture Notes
while( (i = push.read())!= -1) {
if(i == '#') {
int j;
if( (j = push.read()) == '#'){
System.out.print("**");
}else {
push.unread(j);
System.out.print((char)i);
}
}else {
System.out.print((char)i);
}
}
}
}
Output:
1**2#34**#12

Java PushbackReader Class


Java PushbackReader class is a character stream reader. It is used to pushes back a character into
stream and overrides the FilterReader class.
Class declaration
Let' s see the declaration for java.io.PushbackReader class:
public class PushbackReader extends FilterReader
Class Methods

Method Description

int read() It is used to read a single character.


void mark(int readAheadLimit) It is used to mark the present position in a
stream.
boolean ready() It is used to tell whether the stream is ready to
be read.
boolean markSupported() It is used to tell whether the stream supports
mark() operation.
long skip(long n) It is used to skip the character.
void unread (int c) It is used to pushes back the character by
copying it to the pushback buffer.
void unread (char[] cbuf) It is used to pushes back an array of character
by copying it to the pushback buffer.

void reset() It is used to reset the stream.


void close() It is used to close the stream.
9.Lecture Notes

Example of PushbackReader class

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

You might also like