0% found this document useful (0 votes)
14 views96 pages

Java IO and Collection Frameworks Guide

Uploaded by

amigoh129
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)
14 views96 pages

Java IO and Collection Frameworks Guide

Uploaded by

amigoh129
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

Java Programming

Java IO, Files and Java Collection Frameworks

Dr. Pradeep K V
Associate Professor (Sr.)
School of Computer Science and Engineering
VIT - Chennai

Dr. Pradeep K V Java Programming 1/ 42


Contents

Java IO Streams
Java InputStream & Java OutputStream
Java FileInputStream & Java FileOutputStream
Java ByteArrayInputStream & Java ByteArrayOutputStream
Java ObjectInputStream & Java ObjectOutputStream
Java BufferedInputStream & Java BufferedOutputStream
Java PrintStream
Java Reader & Java Writer
Java InputStreamReader & Java OutputStreamWriter
Java FileReader & Java FileWriter
Java BufferedReader & Java BufferedWriter
Java StringReader & Java StringWriter
Java PrintWriter
Java Files
Java Collection Frameworks
JavJava Collection Interface, Map Interface, Set Interface
Examples : Java List, ArrayList, Vector, Stack, Map, HashMap, Set, and
HashSet

Dr. Pradeep K V Java Programming 2/ 42


Introduction to Java IO Streams

In Java, streams are the sequence of data that are read from the source
and written to the destination.
class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

In the above Program, [Link] is used to print a string.


Here, the [Link] is a type of output stream.
Similarly, there are input streams to take input.

Dr. Pradeep K V Java Programming 3/ 42


What is Stream?

A stream is a sequence of data.


In Java, a stream is composed of bytes.
It’s called a stream because it is like a stream of water that continues to
flow.
In Java, 3 streams are created automatically. All these streams are
attached with the console.
[Link]: standard output stream
[Link]: standard input stream
[Link]: standard error stream

Example :
[Link]("simple message");
[Link]("error message");
Types of Streams :
Byte Stream
Character Stream

Dr. Pradeep K V Java Programming 4/ 42


Java Byte Streams... I

Byte stream : is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called
InputStream and OutputStream.
1 Java InputStream Class: It is of the [Link] package is an abstract
superclass that represents an input stream of bytes.
Subclass of InputStream :

Create an InputStream :
[Link]; // Import Package First

// Creates an InputStream
InputStream object1 = new FileInputStream();

Here, we have created an input stream using FileInputStream.


It is because InputStream is an abstract class.
Hence we cannot create an object of InputStream.

Dr. Pradeep K V Java Programming 5/ 42


Java Byte Streams... II

Methods of InputStream : different methods that are implemented by its


subclasses.
1. read() - reads one byte of data from the input stream

2. read(byte[] array) - reads bytes from the stream and


stores in the specified array

3. available() - returns the number of bytes available


in the input stream

4. mark() - marks the position in the input stream


up to which data has been read

5. reset() - returns the control to the point in


the stream where the mark was set

6. markSupported() - checks if the mark() and reset() method


is supported in the stream

7. skips() - skips and discards the specified number of bytes


from the input stream

8. close() - closes the input stream

Dr. Pradeep K V Java Programming 6/ 42


Java Byte Streams... III

import [Link];
import [Link];

public class FileIOStream {


public static void main(String args[]) {
byte[] array = new byte[400];
try {
InputStream input = new FileInputStream("[Link]");
[Link]("Available bytes in the file: "
+ [Link]());
// Read byte from the input stream
[Link](array);
[Link]("Data read from the file: ");

// Convert byte array into string


String data = new String(array);
[Link](data);

// Close the input stream


[Link]();
}
catch (Exception e) { [Link](); }
}
}

Dr. Pradeep K V Java Programming 7/ 42


Java Byte Streams... IV

/*Available bytes in the file: 296


Data read from the file:
Java is a class-based, object-oriented programming language
that is designed to have as few implementation dependencies
as possible. ...
Java applications are typically compiled to bytecode that can
run on any Java virtual machine (JVM) regardless of the
underlying computer architecture.*/

2 Java OutputStream Class: It is of the [Link] package is an abstract


superclass that represents an output stream of bytes.
Subclasses of OutputStream

Dr. Pradeep K V Java Programming 8/ 42


Java Byte Streams... V

Create an OutputStream

[Link] // Import this Package

// Creates an OutputStream
OutputStream object = new FileOutputStream();

Methods of OutputStream : different methods that are implemented by its


subclasses.
1. write() -
writes the specified byte to the output stream

2. write(byte[] array) -
writes the bytes from the specified array to the output stream

3. flush() - forces to write all data present in output stream


to the destination

4. close() - closes the output stream

Dr. Pradeep K V Java Programming 9/ 42


Java Byte Streams... VI

import [Link];
import [Link];

public class FileOutStream {


public static void main(String args[]) {
String data = "Java is a class-based, OOP language \n"
+ "that is designed to have as few implementation \n"
+ "dependencies as possible. ... \n";
try {
OutputStream out = new FileOutputStream("[Link]");

byte[] dataBytes = [Link](); // Converts Str to Bytes.


[Link](dataBytes); // Writes data to the output stream
[Link](); // Closes the output stream
}
catch (Exception e) { [Link](); }
}
}

/*[Link]
Java is a class-based, object-oriented programming language
that is designed to have as few implementation dependencies
as possible. ... */

Dr. Pradeep K V Java Programming 10/ 42


Java Character Streams... I

Character stream is used to read and write a single character of data.


All the character stream classes are derived from base abstract classes
Reader and Writer.
1 Java Reader Class : It is of the [Link] package is an abstract superclass
that represents a stream of characters.
Subclasses of Reader Class :

Create a Reader :
[Link] // import this package

// Creates a Reader
Reader input = new FileReader();

Dr. Pradeep K V Java Programming 11/ 42


Java Character Streams... II

Methods of Reader Class


1. ready() - checks if the reader is ready to be read

2. read(char[] array) - reads the characters from the stream


and stores in the specified array

3. read(char[] array, int start, int length) - reads the no of


characters equal to length from the stream and
stores in the specified array starting from the start

4. mark() - marks the position in the stream up to


which data has been read

5. reset() - returns the control to the point in the stream


where the mark is set

6. skip() - discards the specified number of characters


from the stream

Dr. Pradeep K V Java Programming 12/ 42


Java Character Streams... III

import [Link];
import [Link];

class ReaderClass {
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[400];
try {
// Creates a reader using the FileReader
Reader input = new FileReader("[Link]");
// Checks if reader is ready
[Link]("Is there data in the stream? "
+ [Link]());
// Reads characters
[Link](array);
[Link]("Data in the stream:");
[Link](array);
// Closes the reader
[Link]();
}
catch(Exception e) { [Link](); }
}
}

Dr. Pradeep K V Java Programming 13/ 42


Java Character Streams... IV

2 Java Writer Class : It is of the [Link] package is an abstract superclass


that represents a stream of characters.
Subclasses of Writer :

Create a Writer :
[Link] // Import this package first;

// Creates a Writer
Writer output = new FileWriter();

Dr. Pradeep K V Java Programming 14/ 42


Java Character Streams... V

Methods a Writer :
1. write(char[] array) - writes the characters from the specified
array to the output stream

2. write(String data) - writes the specified string to the writer

3. append(char c) - inserts the specified character to the current


writer

4. flush() - forces to write all the data present in the writer


to the corresponding destination

5. close() - closes the writer


import [Link];
import [Link];

public class WriterClass {

public static void main(String args[]) {

String data = "Java is a class-based, OOP language \n"


+ "that is designed to have as few implementation \n"
+ "dependencies as possible. ... \n";

Dr. Pradeep K V Java Programming 15/ 42


Java Character Streams... VI

try {
// Creates a Writer using FileWriter
Writer output = new FileWriter("[Link]");

// Writes string to the file


[Link](data);

// Closes the writer


[Link]();
}
catch (Exception e) { [Link](); }
}
}

/*[Link]
Java is a class-based, object-oriented programming language
that is designed to have as few implementation dependencies
as possible. ... */

Dr. Pradeep K V Java Programming 16/ 42


Input-Output Stream Hierarchy’s

Dr. Pradeep K V Java Programming 17/ 42


Java ByteArrayInputStream Class... I
It is of the [Link] package can be used to read an array of input data (in
bytes). And extends the InputStream abstract class.
Create a ByteArrayInputStream :
import [Link] // import this package first
// Creates a ByteArrayInputStream that reads entire array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);
// Creates a ByteArrayInputStream that reads a portion of array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr,
int start, int length);

Methods of ByteArrayInputStream :
1. read() - reads the single byte from the array
present in the input stream

2. read(byte[] array) - reads bytes from the input stream


and stores in the specified array

3. read(byte[] array, int start, int length) -


reads the number of bytes equal to length from
the stream and stores in the specified array
starting from the position start.

4. available() - To get the number of available bytes

Dr. Pradeep K V Java Programming 18/ 42


Java ByteArrayInputStream Class... II

in the input stream.

5. skip() - To discard and skip the specified number of bytes

6. close() - To close the input stream.

7. finalize() - ensures that the close() method is called.

8. mark() - marks the position in input stream up to which


data has been read.

9. reset() - returns the control to the point in the input


stream where the mark was set.

10. markSupported() - checks if the input stream


supports mark() and reset()

Dr. Pradeep K V Java Programming 19/ 42


Java ByteArrayInputStream Class... III

import [Link];

public class ByteInputSTREAM {


public static void main(String[] args) {
byte[] array = {10, 20, 30, 40}; // Creates an Byte Array
try {
ByteArrayInputStream input = new ByteArrayInputStream(array);
[Link]("Available bytes at the beginning: "
+ [Link]());
[Link](2); // skip first 2 bytes.
[Link]("The bytes read from the input stream: ");

for(int i= 0; i < [Link]; i++) {


// Reads the bytes
int data = [Link]();
if (data!=-1) [Link](data + ", ");
}
[Link](); // close the ByteArrayInputStream
}
catch(Exception e) { [Link](); }
}
}
// Available bytes at the beginning: 4
// The bytes read from the input stream: 30, 40,

Dr. Pradeep K V Java Programming 20/ 42


Java ByteArrayOutputStream Class... I

It is of the [Link] package can be used to write an array of output data


(in bytes).
Create a ByteArrayIOututStream :
import [Link]
// Creates a ByteArrayOutputStream with default size
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Creating a ByteArrayOutputStream with specified size
ByteArrayOutputStream out = new ByteArrayOutputStream(int size);
// Default Size = 32 Bytes;

Methods of ByteArrayOutputStream :
1. write(int byte) : writes the specified byte to the output stream

2. write(byte[] array) : writes the bytes from the specified array


to the output stream

3. write(byte[] arr, int start, int length) : writes the number of


bytes equal to length to the output stream from an array
starting from the position start

4. writeTo(ByteArrayOutputStream out1) : writes the entire data of


the current output stream to the specified output stream

Dr. Pradeep K V Java Programming 21/ 42


Java ByteArrayOutputStream Class... II

Access Data from ByteArrayOutputStream


5. toByteArray() : returns the array present inside the output stream
6. toString() : returns the entire data of the output stream
in string form

Other Methods
7. size() : returns the size of the array in the output stream
8. flush() : clears the output stream

import [Link];

class ByteOutputSTREAM {
public static void main(String[] args) {
String data = "At least we agree that buying a glass house" +
"was a lousy idea.";
try {
// Creates an output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] array = [Link](); // converts a string to Byte Array.

// Writes data to the output stream


[Link](array);

// Retrieves data from the output stream in string format

Dr. Pradeep K V Java Programming 22/ 42


Java ByteArrayOutputStream Class... III

String streamData = [Link]();


[Link]("Data using toString(): " + streamData);

byte[] byteData = [Link]();


[Link]("Data using toByteArray(): ");
for(int i=0; i<[Link]; i++) {
[Link]((char)byteData[i]);
}
[Link]();
}
catch(Exception e) { [Link](); }
}
}

// Data using toString(): At least we agree that buying a


// glass house was a lousy idea.
// Data using toByteArray(): At least we agree that buying a
// glass house was a lousy idea.

Dr. Pradeep K V Java Programming 23/ 42


Java ObjectInputStream Class... I

It is of the [Link] package can be used to read objects. And extends the
InputStream abstract class.
Create a ObjectInputStream :

import [Link] // import package first


// Creates a file input stream linked with the specified file
FileInputStream fileStream = new FileInputStream(String file);
// Creates an object input stream using the file input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);

Methods of ObjectInputStream :
1. read() : reads a byte of data from the input stream

2. readBoolean() : reads data in boolean form

3. readChar() : reads data in character form

4. readInt() : reads data in integer form

5. readObject() : reads the object from the input stream

Dr. Pradeep K V Java Programming 24/ 42


Java ObjectInputStream Class... II

6. available() : returns the available number of bytes


in the input stream
7. mark() : marks the position in input stream up to which
data has been read
8. reset() : returns the control to the point in the
input stream where the mark was set
9. skipBytes() : skips and discards the specified bytes
from the input stream
10. close() : closes the object input stream

import [Link]; import [Link];


import [Link]; import [Link];
import [Link];

class Dog implements Serializable {


String name, breed;
public Dog(String N, String B) { name = N; breed = B; }
}

class ObjectInputSTREAM {
public static void main(String[] args) {
// Creates an object of Dog class

Dr. Pradeep K V Java Programming 25/ 42


Java ObjectInputStream Class... III

Dog dog = new Dog("Baloo", "Australian Cattle");


try {
// Creates an ObjectInputStream, ObjectOutputStream & FileOutputStream
ObjectInputStream input = new ObjectInputStream(fileStream);
ObjectOutputStream output = new ObjectOutputStream(file);
FileOutputStream file = new FileOutputStream("[Link]");

[Link](dog); // Writes objects to output stream


FileInputStream fileStream = new FileInputStream("[Link]");

Dog newDog = (Dog) [Link](); // Reads the objects

[Link]("Dog Name: " + [Link]);


[Link]("Dog Breed: " + [Link]);

[Link](); [Link]();
}
catch (Exception e) { [Link](); }
}
}

// Dog Name: Baloo


// Dog Breed: Australian Cattle

Dr. Pradeep K V Java Programming 26/ 42


Java ObjectOutputStream Class... I

It is of the [Link] package can be used to write objects. And it extends


the OutputStream abstract class.
Create a ObjectOutputStream :

import [Link] // import package first


// Creates a FileOutputStream linked with the specified file
FileOutputStream fileStream = new FileOutputStream(String file);
// Creates the ObjectOutputStream
ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

Methods of ObjectOutputStream :
1. write() : writes a byte of data to the output stream
2. writeBoolean() : writes data in boolean form
3. writeChar() : writes data in character form
4. writeInt() : writes data in integer form
5. writeObject() : writes object to the output stream
6. flush() : clears all the data from the output stream
7. drain() : puts all the buffered data in the output stream
8. close() : closes the output stream

Dr. Pradeep K V Java Programming 27/ 42


Java ObjectOutputStream Class... II

import [Link]; import [Link];


import [Link]; import [Link];
class ObjectOutputSTREAM {
public static void main(String[] args) {
int data1 = 50;
String data2 = "This is an Example of ObjectOutputStream";
try {
FileOutputStream file = new FileOutputStream("[Link]");
// Creates an ObjectOutputStream
ObjectOutputStream output = new ObjectOutputStream(file);
// writes objects to output stream
[Link](data1); [Link](data2);
// Reads data using the ObjectInputStream
FileInputStream fileStream = new FileInputStream("[Link]");
ObjectInputStream objStream = new ObjectInputStream(fileStream);
[Link]("Integer data :" + [Link]());
[Link]("String data: " + [Link]());
[Link](); [Link]();
} catch (Exception e) { [Link](); }
}
}

// Integer data :50


// String data: This is an Example of ObjectOutputStream

Dr. Pradeep K V Java Programming 28/ 42


Buffered Input & Output Stream... I

Both BufferedInputStream & BufferedOutputStream class of the


[Link] package is used with other input/output streams to
Create a BufferedInputStream & BufferedOutputStream :
import [Link] // import package
// Creates a FileInputStream
FileInputStream file = new FileInputStream(String path);
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferInputStream(file);

import [Link] // import package


// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String path);
// Creates a BufferedOutputStream
BufferedOutputStream buffer = new BufferOutputStream(file);

read/write the data (in bytes) more efficiently.

Dr. Pradeep K V Java Programming 29/ 42


Buffered Input & Output Stream... II

Methods of BufferedInputStream & BufferedOutputStream :


1. read() : reads a single byte from the input stream

2. read(byte[] arr) : reads bytes from the stream and


stores in the specified array

3. read(byte[] arr, int start, int length) :


reads the number of bytes equal to the length from the stream &
stores in the specified array starting from the position start

4. available() : To get the number of available bytes in the i/p stream

5. skip() : To discard and skip the specified number of bytes

6. mark() : mark the position in i/p stream up to which data


has been read

7. reset() : returns the control to the point in the i/p stream


where the mark was set

8. write() - writes a single byte to the internal buffer


of the output stream

9. write(byte[] array) - writes the bytes from the specified array

Dr. Pradeep K V Java Programming 30/ 42


Buffered Input & Output Stream... III

to the output stream

10. write(byte[] arr, int start, int length) - writes the number of bytes
equal to length to the output stream from an array starting
from the position start

11. flush() To clear the internal buffer

12. close() : To close the buffered input/output stream

Consider the Given [Link] File :

/* [Link]

Java is a class-based, object-oriented programming language


that is designed to have as few implementation dependencies
as possible. ...
Java applications are typically compiled to bytecode that can
run on any Java virtual machine (JVM) regardless of the
underlying computer architecture.

*/

import [Link]; import [Link];


import [Link]; import [Link];

Dr. Pradeep K V Java Programming 31/ 42


Buffered Input & Output Stream... IV

public class BufferInputOutputStream {


public static void main(String args[]) {
try {
// Creates and Opens both [Link] and [Link]
FileInputStream ifile = new FileInputStream("[Link]");
FileOutputStream ofile = new FileOutputStream("[Link]");

// Creates a BufferedInputStream & BufferedOutputStream


BufferedInputStream ibuffer = new BufferedInputStream(ifile);
BufferedOutputStream obuffer = new BufferedOutputStream(ofile);

// Returns the available number of bytes


[Link]("Available bytes at the beginning: "
+ [Link]());

// Reads 3 bytes from the file


[Link](); [Link](); [Link]();
// Returns the Remaining available number of bytes
[Link]("Available bytes after 3 read() : "
+ [Link]());

[Link](5); // Skip next 5 Bytes (Chars)


[Link]("Available bytes After skip(): "
+ [Link]());

Dr. Pradeep K V Java Programming 32/ 42


Buffered Input & Output Stream... V

// Read from File [Link] and Write into [Link]


int i = [Link]();
while (i != -1) {
[Link](i);
// Reads next byte from the input stream
i = [Link]();
}
//close both ibuffer and obuffer;
[Link](); [Link]();
}

catch (Exception e) { [Link](); }


}
}

// Available bytes at the beginning: 296


// Available bytes at the end: 293
// Available bytes After skip(): 288

/* [Link] (Generated through the program)

a class-based, object-oriented programming language


that is designed to have as few implementation dependencies

Dr. Pradeep K V Java Programming 33/ 42


Buffered Input & Output Stream... VI

as possible. ...
Java applications are typically compiled to bytecode that can
run on any Java virtual machine (JVM) regardless of the
underlying computer architecture.

*/

Dr. Pradeep K V Java Programming 34/ 42


Java PrintStream Class... I

It is of the [Link] package can be used to write output data in commonly


readable form (text) instead of bytes. And it extends the abstract class
OutputStream.
It converts the primitive data (integer, character) into the text format
instead of bytes. It then writes that formatted data to the output stream.
It does not throw any input/output exception and has a feature of auto
flushing.
Create a BufferedInputStream
import [Link]

Using other output streams (Option-1)


// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);
// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush);
Using filename (Option-2)
// Creates a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);
// Creates a PrintStream using some character encoding
PrintStream output = new PrintStream(String file, boolean autoFlush,
Charset cs);

Dr. Pradeep K V Java Programming 35/ 42


Java PrintStream Class... II

Methods of PrintStream
1. print() : prints the specified data to the output stream
2. println() : prints the data to the output stream along
with a new line character at the end
3. close() : closes the print stream
4. checkError() : checks if there is an error in the stream
and returns a boolean result
5. append() : appends the specified data to the stream

import [Link];
class PrintSTREAM {
public static void main(String[] args) {
String data = "My favorite Subject in school is nothing\n";
int age=30;
[Link](data); // Prints on Console
try {
PrintStream output = new PrintStream("[Link]");
[Link](data); // Write into a File
[Link]("I am %d years old.", age);
[Link]();
}catch(Exception e) { [Link](); }
}
} // Analyse Program and Guess the Output ?

Dr. Pradeep K V Java Programming 36/ 42


Java InputStreamReader & OutputStreamWriter... I

They are of the [Link] package can be used to convert Bytes data into
Character data & viceversa.
Both works with other input/output streams and are known as a bridge
between byte streams and character streams.
InputStreamReader reads bytes from the input stream as characters.
OutputStreamWriter converts its characters into bytes.
Create an InputStreamReader & OutputStreamWriter
[Link];
// Creates an InputStream
FileInputStream file = new FileInputStream(String path);
// Creates an InputStreamReader or with Character encoding
InputStreamReader input = new InputStreamReader(file);
InputStreamReader input = new InputStreamReader(file, Charset cs);

[Link];
// Creates an OutputStream
FileOutputStream file = new FileOutputStream(String path);
// Creates an OutputStreamWriter or with Character encoding
OutputStreamWriter output = new OutputStreamWriter(file);
OutputStreamWriter output = new OutputStreamWriter(file, Charset cs);

Dr. Pradeep K V Java Programming 37/ 42


Java InputStreamReader & OutputStreamWriter... II

Methods of InputStreamReader & OutputStreamWriter :

InputStreamReader Methods : -

1. read() : reads a single character from the reader


2. read(char[] array) : reads the characters from the reader
and stores in the specified array
3. read(char[] array, int start, int length) : reads the number
of characters equal to length from the reader and
stores in the specified array starting from the start
5. ready() : checks if the stream is ready to be read
6. mark() : mark the position in stream up to which data has been read
7. reset() : returns the control to the point in the stream
where the mark was set

OutputStreamWriter Methods : -

1. write() : writes a single character to the writer


2. write(char[] array) : writes the characters from the specified
array to the writer
3. write(String data) : writes the specified string to the writer
4. flush() : forces to write all the data present in the writer to
the corresponding destination
5. append() : inserts the specified character to the current writer

Dr. Pradeep K V Java Programming 38/ 42


Java InputStreamReader & OutputStreamWriter... III

Common Methods
1. close() : To close the Input/Output stream
2. getEncoding() : used to get the type of encoding used to
store data in the input/output stream

/* Consider [Link]
Java is a class-based, object-oriented programming language
that is designed to have as few implementation dependencies
as possible. ...
Java applications are typically compiled to bytecode that can
run on any Java virtual machine (JVM) regardless of the
underlying computer architecture.
*/

import [Link].*;
import [Link];
class InputOutputStreamReaderWriter {
public static void main(String[] args) {
char[] array = new char[500] ;

try {

Dr. Pradeep K V Java Programming 39/ 42


Java InputStreamReader & OutputStreamWriter... IV

// Creates a FileInputStream
FileInputStream ifile = new FileInputStream("[Link]");
FileOutputStream ofile = new FileOutputStream("[Link]");

// Creates an InputStreamReader with default encoding


InputStreamReader input = new InputStreamReader(ifile);
InputStreamReader input2 = new InputStreamReader(ifile,
[Link]("UTF16"));
[Link]("Character encoding of input: "
+ [Link]());
[Link]("Character encoding of input: "
+ [Link]());
[Link](array);
// Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(ofile);
[Link](array);

[Link](); [Link]();
}
catch(Exception e) { [Link](); }
}
}

// Character encoding of input: UTF-16


// Character encoding of input: UTF8

Dr. Pradeep K V Java Programming 40/ 42


Java InputStreamReader & OutputStreamWriter... V

/* [Link] (File Generated)


Java is a class-based, object-oriented programming language
that is designed to have as few implementation dependencies
as possible. ...
Java applications are typically compiled to bytecode that can
run on any Java virtual machine (JVM) regardless of the
underlying computer architecture.
*/

Dr. Pradeep K V Java Programming 41/ 42


Java FileReader and FileWriter Class... I

They are of the [Link] package can be used to read/write data (in
characters) from files. They extends InputStreamReader and
OutputStreamReader Classess respectively.
Create an FileReader & FileWriter :
import [Link] // import package first;
// Using the name of the file
FileReader input = new FileReader(String name);
FileReader input = new FileReader(String file, Charset cs);

// Using an object of the file


FileReader input = new FileReader(File fileObj);

import [Link] // import package first;


// Using the name of the file
FileWriter output = new FileWriter(String name);
FileWriter input = new FileWriter(String file, Charset cs);

// Using an object of the file


FileWriter input = new FileWriter(File fileObj);

Dr. Pradeep K V Java Programming 42/ 42


Java FileReader and FileWriter Class... II

Methods of FileReader & FileWriter :


Methods of FileReader
1. read() : reads a single character from the reader
2. read(char[] array) : reads the characters from the reader and
stores in the specified array
3. read(char[] array, int start, int length) : reads the number of
characters equal to length from the reader and stores
in the specified array starting from the position start
4. ready() : checks if the file reader is ready to be read
5. mark() : mark the position in file reader up to which
data has been read
6. reset() : returns the control to the point in the reader
where the mark was set

Methods of FileWriter
1. write() : writes a single character to the writer
2. write(char[] array) : writes the characters from the specified
array to the writer
3. write(String data) : writes the specified string to the writer
4. flush() : forces to write all the data present in the writer to
the corresponding destination
5. append() : inserts the specified character to the current writer

Common Methods

Dr. Pradeep K V Java Programming 43/ 42


Java FileReader and FileWriter Class... III

1. getEncoding() : used to get the type of encoding that is used to


store/write data in the file
2. close() : To close the FileReader/FileWriter.

/* Consider [Link] as below

Java is a class-based, object-oriented programming language


that is designed to have as few implementation dependencies
as possible. ...

*/

import [Link].*;
import [Link];

class FileReaderWriter {
public static void main(String[] args) {
char[] array = new char[500]; // Creates an array of character
try {
// Creates a reader using the FileReader
FileReader input = new FileReader("[Link]");
FileWriter output = new FileWriter("[Link]");

[Link](array); // Reads characters from [Link]

Dr. Pradeep K V Java Programming 44/ 42


Java FileReader and FileWriter Class... IV

[Link](array); // Write Characters into [Link]

FileReader input2 = new FileReader("[Link]", [Link]("UTF1

// Returns the character encoding of the file reader


[Link]("Character encoding of input1: " + [Link]
[Link]("Character encoding of input2: " + [Link]
// Closes the reader and writer
[Link](); [Link](); [Link]();
}

catch(Exception e) { [Link](); }
} // Character encoding of input1: UTF8
} // Character encoding of input2: UTF-16

/* [Link] file is generated as

Java is a class-based, object-oriented programming language


that is designed to have as few implementation dependencies
as possible. ... */

Dr. Pradeep K V Java Programming 45/ 42


Java BufferedReader and BufferedWriter Class... I

They are of the [Link] package can be used with other readers/writers
to read/write data (in characters) more efficiently.

Create an BufferedReader & BufferedWriter :


import [Link] // import package first
// Creates a FileReader
FileReader file = new FileReader(String file);
// Creates a BufferedReader
BufferedReader buffer = new BufferedReader(file);
// Creates a BufferdReader with specified size internal buffer
BufferedReader buffer = new BufferedReader(file, int size);

import [Link] // import pakcage first


// Creates a FileWriter
FileWriter file = new FileWriter(String name);
// Creates a BufferedWriter
BufferedWriter buffer = new BufferedWriter(file);
// Creates a BufferedWriter with specified size internal buffer
BufferedWriter buffer = new BufferedWriter(file, int size);

Dr. Pradeep K V Java Programming 46/ 42


Java BufferedReader and BufferedWriter Class... II

Methods of BufferedReader & BufferedWriter :


Methods of BufferedReader
1. read() : reads a single character from the internal buffer
of the reader
2. read(char[] array) : reads the characters from the reader and
stores in the specified array
3. read(char[] array, int start, int length) : reads the number of
characters equal to length from the reader and stores
in the specified array starting from the position start
4. skip() : To discard and skip the specified number of characters
5. ready() : checks if the file reader is ready to be read
6. mark() : mark the position in reader up to which data has been read
7. reset() : returns the control to the point in the reader
where the mark was set

Methods of BufferedWriter
1. write() : writes a single character to the internal buffer
of the writer
2. write(char[] array) : writes the characters from the specified
array to the writer
3. write(String data) : writes the specified string to the writer
4. flush() : To clear the internal buffer
5. newLine() : inserts a new line to the writer
6. append() : inserts the specified character to the current write

Dr. Pradeep K V Java Programming 47/ 42


Java BufferedReader and BufferedWriter Class... III

Common Methods :
1. close() Method : To close the buffered reader/buffered writer

/* Consdier [Link]

Java is a class-based, object-oriented programming language


that is designed to have as few implementation dependencies
as possible. ...

*/

import [Link].*;
public class BufferedReaderWriter {
public static void main(String args[]) {

char[] array = new char[500]; // Creates an character array


try {
FileReader ifile = new FileReader("[Link]");
FileWriter ofile = new FileWriter("[Link]");

// Creates a BufferedReader
BufferedReader input = new BufferedReader(ifile);
BufferedWriter output = new BufferedWriter(ofile);

Dr. Pradeep K V Java Programming 48/ 42


Java BufferedReader and BufferedWriter Class... IV

// Skips the 10 characters


[Link](10); [Link](array);

// Reads the characters


[Link](array);

// closes the reader and writer


[Link](); [Link]();
}

catch (Exception e) { [Link](); }


}
}

/* [Link] file is generated.

class-based, object-oriented programming language


that is designed to have as few implementation dependencies
as possible. ...

*/

Dr. Pradeep K V Java Programming 49/ 42


Java StringReader & StringWriter I
They are of the [Link] package can be used to read/write data (in
characters) from strings. And extends the abstract class Reader.
Create an StringReader & StringWriter :
import [Link] // import package first
// Creates a StringReader
StringReader input = new StringReader(String data);

import [Link] // import package first


// Creates a StringWriter
StringWriter output = new StringWriter();
// Creates a StringWriter with specified string buffer capacity
StringWriter output = new StringWriter(int size);
Methods of StringReader & StringWriter :
// Methods of StringReader :
1. read() : reads a single character from the string reader
2. read(char[] array) : reads the characters from the reader
and stores in the specified array
3. read(char[] array, int start, int length) : reads the number
of characters equal to length from the reader and stores
in the specified array starting from the position start
4. skip() : To discard and skip the specified number of characters
5. ready() : checks if the string reader is ready to be read
6. mark() : marks the position in reader up to which data has been read

Dr. Pradeep K V Java Programming 50/ 42


Java StringReader & StringWriter II

7. reset() : returns the control to the point in the reader


where the mark was set

//Methods of StringWriter :
1. write() : writes a single character to the string writer
2. write(char[] array) : writes the characters from the
specified array to the writer
3. write(String data) : writes the specified string to the writer
4. getBuffer() : returns the data present in the string buffer
5. toString() : returns the data present in the string buffer
as a string
6. flush() : forces to write all the data present in the writer
to the string buffer
7. append() : inserts the specified character to the current writer
import [Link].*;

public class StringReaderWriter {


public static void main(String[] args) {
String data = "Java is a class-based, object-oriented programming \n"
+ "language that is designed to have as few implementation \n"
+ "dependencies as possible. ... ";
// Create a character array
char[] array = new char[500];
try {

Dr. Pradeep K V Java Programming 51/ 42


Java StringReader & StringWriter III

// Create a StringReader
StringReader input = new StringReader(data);
StringWriter output = new StringWriter();

[Link](5); // Use the skip() method


[Link](array); //Use the read method
[Link]("Data after skipping 5 characters:");
[Link](array);

[Link](data);
// Returns the string buffer
StringBuffer stringBuffer = [Link]();
[Link]("StringBuffer: " + stringBuffer);

// Returns the string buffer in string form


String string = [Link]();
[Link]("String: " + string);

[Link](); [Link](); // Close both Reader/Writer


}
catch(Exception e) { [Link](); }
}
}
/*
Data after skipping 5 characters:

Dr. Pradeep K V Java Programming 52/ 42


Java StringReader & StringWriter IV

is a class-based, object-oriented programming


language that is designed to have as few implementation
dependencies as possible. ...
StringBuffer: Java is a class-based, object-oriented programming
language that is designed to have as few implementation
dependencies as possible. ...
String: Java is a class-based, object-oriented programming
language that is designed to have as few implementation
dependencies as possible. ...
*/

Dr. Pradeep K V Java Programming 53/ 42


Java PrintWriter I

It is of the [Link] package can be used to write output data in a


commonly readable form (text). And extends the abstract class Writer.
It converts the primitive data (int, float, char, etc.) into the text format.
It then writes that formatted data to the writer.
Create an PrintWriter :
[Link] // import package first;
// Using other writers
// Creates a FileWriter
FileWriter file = new FileWriter("[Link]");
// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);
// Using other output streams
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("[Link]");
// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);
// Using Filename
// Creates a PrintWriter
PrintWriter output = new PrintWriter(String file, boolean autoFlush);
// Creates a PrintWriter using some character encoding
PrintWriter output = new PrintWriter(String file,
boolean autoFlush, Charset cs);

Dr. Pradeep K V Java Programming 54/ 42


Java PrintWriter II

Methods of PrintWriter :

1. print() : prints the specified data to the writer


2. println() : prints the data to the writer along with
a new line character at the end
3. printf() : used to print the formatted string.
4. close() : closes the print writer
5. checkError() : checks if there is an error in the writer
and returns a boolean result
6. append() : appends the specified data to the writer

import [Link];

class PRINTWRITER {

public static void main(String[] args) {

int age = 50;

String data = "Java is a class-based, OOP Language \n"


+ "that is designed to have as few implementation dependencies \n"
+ "as possible.... ";

Dr. Pradeep K V Java Programming 55/ 42


Java PrintWriter III

try {
PrintWriter output = new PrintWriter("[Link]");

[Link](data);
[Link]("\nI am %d years old.", age);
[Link]();
}

catch(Exception e) { [Link](); }
}
}

/* [Link] is Generated

Java is a class-based, OOP Language


that is designed to have as few implementation dependencies
as possible....
I am 50 years old.

*/

Dr. Pradeep K V Java Programming 56/ 42


Java Collection Frameworks

It is a framework that provides an architecture to store and manipulate the


group of objects.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Java Collection : represents a single unit of objects, i.e., a group.
Java Framework : It provides readymade architecture and represents a set
of classes and interfaces (Optinal)
Collection framework : represents a unified architecture for storing and
manipulating a group of objects. It has: Interfaces and its
implementations, i.e., Classes and Algorithms
Java collections framework : It provides a set of interfaces and classes
to implement various data structures and algorithms.

Dr. Pradeep K V Java Programming 57/ 42


Hierarchy of Collection Framework
The [Link] package contains all the classes and interfaces for the Collection
framework.

Dr. Pradeep K V Java Programming 58/ 42


Java Collection Framework

The [Link] package contains all the classes and interfaces for the Collection
framework.

JCF
It is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface
but provides implementations of its subinterfaces like List, Set, and Queue

Dr. Pradeep K V Java Programming 59/ 42


Collections Framework Vs. Collection Interface

Java Collection interface is the root interface of the collections framework.


The Java Collection framework includes other interfaces as well: Map and
Iterator. And may also have subinterfaces.
Subinterfaces of the Collection Interface:
List Interface : is an ordered collection that allows us to add and remove
elements like an array.
Set Interface : allows us to store elements in different sets similar to the set
in mathematics. It cannot have duplicate elements.
Queue Interface : is used when we want to store and access elements in
First In, First Out manner

Java Map Interface : allows elements to be stored in key/value pairs.


Keys are unique names that can be used to access a particular element in
a map. And, each Key has a single Value associated with it.

Java Iterator Interface : provides methods that can be used to access


elements of collections

Dr. Pradeep K V Java Programming 60/ 42


Java Collection Interface

The Collection interface is the root interface of the Java collections framework.

Methods of Collection : includes various methods that can be used to perform


different operations on objects.
1. add() - inserts the specified element to the collection
2. size() - returns the size of the collection
3. remove() - removes the specified element from the collection
4. iterator() - returns an iterator to access elements of the collection
5. addAll() - adds all the elements of a specified collection to
the collection
6. removeAll() - removes all the elements of the specified collection
from the collection
7. clear() - removes all the elements of the collection

Dr. Pradeep K V Java Programming 61/ 42


Methods of Collection interface I

1 public boolean add(E e) : is used to insert an element in collection.

2 public boolean addAll(Collection<? extends E> c) : is used to insert the


specified collection elements in the invoking collection.

3 public boolean remove(Object element) : used to delete an element.

4 public boolean removeAll(Collection<?> c) : used to delete all elements


of the specified collection from the invoking collection.

5 default boolean removeIf(Predicate<? super E> filter) : is used to delete


all the elements of the collection that satisfy the specified predicate.

6 public boolean retainAll(Collection<?> c) : It is used to delete all


the elements of invoking collection except the specified collection.

7 public int size() : returns the total no. of elements in the collection.

8 public void clear() : removes all elements from the collection.

9 public boolean contains(Object element) : used to search an element.

10 public boolean containsAll(Collection<?> c):


It is used to search the specified collection in the collection.

Dr. Pradeep K V Java Programming 62/ 42


Methods of Collection interface II

11 public Iterator iterator() : It returns an iterator.

12 public Object[] toArray() : It converts collection into array.

13 public <T> T[] toArray(T[] a) : It converts collection into array. Here


the runtime type of the returned array is that of the specified array.

14 public boolean isEmpty() : It checks if collection is empty.

15 default Stream<E> parallelStream() :


It returns a possibly parallel Stream with the collection as its source.

16 default Stream<E> stream() : It returns a sequential Stream with the


collection as its source.

17 default Spliterator<E> spliterator() :


It generates a Spliterator over the specified elements in the collection.

18 public boolean equals(Object element) : It matches two collections.

19 public int hashCode() : It returns the hash code number of the collection.

Dr. Pradeep K V Java Programming 63/ 42


Java List Interface... I

List Interface
It is an ordered collection that allows us to store and access elements
sequentially. And extends the Collection interface. Classes that Implement
List :

How to use List? : We must import [Link] package in order to use List.
// ArrayList implementation of List
List<String> list1 = new ArrayList<>();

// LinkedList implementation of List


List<String> list2 = new LinkedList<>();

Dr. Pradeep K V Java Programming 64/ 42


Java List Interface... II

Methods of List :
1. add() - adds an element to a list

2. addAll() - adds all elements of one list to another

3. get() - helps to randomly access elements from lists

4. iterator() - returns iterator object that can be used


to sequentially access elements of lists

5. set() - changes elements of lists

6. remove() - removes an element from the list

7. removeAll() - removes all the elements from the list

8. clear() - removes all the elements from the list


(efficient than removeAll())

9. size() - returns the length of lists

10. toArray() - converts a list into an array

11. contains() - returns true if a list contains specified element

Dr. Pradeep K V Java Programming 65/ 42


Example-1 : Implementation of ArrayList I

The ArrayList class of the Java collections framework provides the


functionality of resizable-arrays.
import [Link]; import [Link];

class ArrayLIST {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> MyList = new ArrayList<>();
List<Integer> MyList1 = new ArrayList<>();
[Link](10); [Link](20); // adding Elements into MyList-1
// Add elements to the list
[Link](1); [Link](5); [Link](3); [Link](7);
[Link](2,MyList1); // Adding Elements from MyList-1
[Link]("List: " + MyList);
[Link]("IndexOf : " + [Link](10));
// Access element from the list
[Link]("Accessed Element: " + [Link](2));
// Remove element from the list
[Link]("Removed Element: " + [Link](1));
[Link]("Accessed Element: " + [Link](3, 30));
[Link]("Size of MyList : " + [Link]());
[Link]("Is 10 Exists in the List : " + [Link](10));
[Link](null); // Sort Ascending Order;
[Link]("Sort List: " + MyList);

Dr. Pradeep K V Java Programming 66/ 42


Example-1 : Implementation of ArrayList II

[Link]("Is List Empty : " + [Link]());


[Link]();
[Link]("Is List Empty : " + [Link]());
}
}

/*
List: [1, 5, 10, 20, 3, 7]
IndexOf : 2
Accessed Element: 10
Removed Element: 5
Accessed Element: 3
Size of MyList : 5
Is 10 Exists in the List : true
Sort List: [1, 7, 10, 20, 30]
Is List Empty : false
Is List Empty : true

*/

Dr. Pradeep K V Java Programming 67/ 42


Java Vector I

The Vector class is an implementation of the List interface that allows us


to create resizable-arrays similar to the ArrayList class.

Java Vector vs. ArrayList :


The Vector class synchronizes each individual operation. This means
whenever we want to perform some operation on vectors, the Vector class
automatically applies a lock to that operation.
In ArrayList, methods are not synchronized. Instead, it uses the
[Link]() method that synchronizes the list as a whole.

Creating a Vector :
import [Link];
Vector<Type> vector = new Vector<>();

Example :
Vector<Integer> vector= new Vector<>();
Vector<String> vector= new Vector<>();

Dr. Pradeep K V Java Programming 68/ 42


Java Vector II

Methods of Vector :
1. add(element) - adds an element to vectors

2. add(index, element) - adds an element to the specified position

3. addAll(vector) - adds all elements of a vector to another vector

4. get(index) - returns an element specified by the index

5. iterator() - returns an iterator object to sequentially access


vector elements

6. remove(index) - removes an element from specified position

7. removeAll() - removes all the elements

8. clear() - removes all elements. It is more efficient than removeAll()

9. set() - changes an element of the vector

10. size() - returns the size of the vector

11. toArray() - converts the vector into an array

Dr. Pradeep K V Java Programming 69/ 42


Java Vector III

12. toString() - converts the vector into a String

13. contains() - searches the vector for specified element and


returns a boolean result

import [Link];

class JavaVectorClass {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
[Link]("Dog"); [Link]("Horse");
[Link]("Pig"); [Link]("Cat");
[Link]("Befor Sort Vector: " + animals);
[Link](null); // Sort Animals
[Link]("After Sort Vector: " + animals);
String element = [Link](1); // Using remove()
[Link]("Removed Element: " + element);
[Link]("Donkey");
[Link]("After Element Removed: " + animals);
[Link]("Indext of Pig: " + [Link]("Pig"));
[Link]("Check Horse : " + [Link]("Horse"));
[Link]("Check Parrot : " + [Link]("Parrot"));
[Link]("Cow");
[Link]("Check Size : " + [Link]());
[Link](3, "Dog");

Dr. Pradeep K V Java Programming 70/ 42


Java Vector IV

[Link]("After Set Vector: " + animals);


[Link](); // Using clear()
[Link]("Vector after clear(): " + animals);
[Link]("Check Empty or Not : " + [Link]());
}
}
/*
Befor Sort Vector: [Dog, Horse, Pig, Cat]
After Sort Vector: [Cat, Dog, Horse, Pig]
Removed Element: Dog
After Element Removed: [Cat, Horse, Pig, Donkey]
Indext of Pig: 2
Check Horse : true
Check Parrot : false
Check Size : 5
After Set Vector: [Cat, Horse, Pig, Dog, Cow]
Vector after clear(): []
Check Empty or Not : true
*/

Dr. Pradeep K V Java Programming 71/ 42


Java Stack I

The Stack class extends the Vector class.


In Stack, elements are stored and accessed in Last In First Out. i.e.,
elements are added/removed only at top of the stack.
Creating a Stack :
import [Link]
Stack<Type> stacks = new Stack<>();

Examples:
Stack<Integer> stacks = new Stack<>();
Stack<String> stacks = new Stack<>();

Methods of Stack :
Since Stack extends the Vector class, it inherits all the methods Vector

Other Methods
1. push() - To add an element to the top of the stack.
2. pop() - To remove an element from the top of the stack
3. peek() - returns an object from the top of the stack
4. search() - To search an element in the stack.
5. empty() - To check whether a stack is empty or not

Dr. Pradeep K V Java Programming 72/ 42


Java Stack II

import [Link];

class JavaSTACK {
public static void main(String[] args) {

Stack<String> animals= new Stack<>(); // Stack Created

[Link]("Horse"); [Link]("Cat"); [Link]("Dog");


[Link]("Stack: " + animals);

[Link]("Zibra");
[Link]("Stack: " + animals);
[Link]("Peek Element : " + [Link]());
[Link]("Element Poped : " + [Link]());
[Link]("Search Dog : " + [Link]("Dog"));
[Link]("Search Dog : " + [Link]("Dog"));

[Link]("Is the stack empty? " + [Link]());


[Link](); // Clear and Check for empty.
[Link]("Is the stack empty? " + [Link]());
}
}

/*

Dr. Pradeep K V Java Programming 73/ 42


Java Stack III

Stack: [Horse, Cat, Dog]


Stack: [Horse, Cat, Dog, Zibra]
Peek Element : Zibra
Element Poped : Zibra
Search Dog : 1
Search Dog : true
Is the stack empty? false
Is the stack empty? true
*/

Dr. Pradeep K V Java Programming 74/ 42


Java Map Interface I

It is of Java collections framework provides the functionality of the map


data structure.
Elements of Map are stored in key/value pairs. Keys are unique values
associated with individual Values.
It cannot contain duplicate keys. And, each key is associated with a single
value.

Dr. Pradeep K V Java Programming 75/ 42


Java Map Interface II

Methods of Map :
1. put(K, V) - Inserts the both (K,V) into the map as Element.
If the key is present, its value is replaced.

2. putAll() - Inserts all the entries from the specified map.

3. putIfAbsent(K, V) - Inserts the association if the 'K'


is not already associated with 'V'.

4. get(K) - Returns the value associated with 'K'.


If the key is not found, it returns null.
5. getOrDefault(K, defaultValue) - Returns the value associated with
the specified key 'K'. If the key is not found,
it returns the defaultValue.

6. containsKey(K) - Checks if 'K' is present in the map or not.

7. containsValue(V) - Checks if 'V' is present in the map or not.

8. replace(K, V) - Replace the value 'K' with the new 'V'.

9. replace(K, oldValue, newValue) - Replaces the value of the 'K'


with he new 'V' only if the 'K' is associated with 'V'.

Dr. Pradeep K V Java Programming 76/ 42


Java Map Interface III

10. remove(K) - Removes the entry from the map represented by 'K'.

11. remove(K, V) - Removes the entry from the map that has 'K' with 'V'.

12. keySet() - Returns a set of all the Key's present in a map.

13. values() - Returns a set of all the Values present in a map.

14. entrySet() - Returns a set of all the 'K'/'V' mapping in a map.

import [Link]; import [Link];

class HashMAP {
public static void main(String[] args) {
// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();
[Link]("One", 1); [Link]("Two", 2);
[Link]("Three", 3);
[Link]("Map: " + numbers);
[Link]("Keys: " + [Link]());
[Link]("Values: " + [Link]());
[Link]("Entries: " + [Link]());
[Link]("Get the Value at K :" + [Link]("Two"));

Dr. Pradeep K V Java Programming 77/ 42


Java Map Interface IV

[Link]("Contains K :" + [Link]("Two"));


[Link]("Contains K :" + [Link](4));
[Link]("Two", 20);
[Link]("After Replace Map Entries are : " + numbers);
[Link]("Two", 20, 2);
[Link]("After Replace Map Entries are : " + numbers);
[Link]("Removed Value: " + [Link]("Two");
}
}
/*
Map: {One=1, Two=2, Three=3}
Keys: [One, Two, Three]
Values: [1, 2, 3]
Entries: [One=1, Two=2, Three=3]
Get the Value at K :2
Contains K :true
Contains K :false
After Replace Map Entries are : {One=1, Two=20, Three=3}
After Replace Map Entries are : {One=1, Two=2, Three=3}
Removed Value: 2
*/

Dr. Pradeep K V Java Programming 78/ 42


Difference among different Maps

Dr. Pradeep K V Java Programming 79/ 42


Practice the Following...!

Java LinkedHashMap
Java WeakHashMap
Java EnumMap
Java SortedMap Interface
Java NavigableMap Interface
Java TreeMap
Java ConcurrentMap Interface
Java ConcurrentHashMap

The Above Data Structure have some additional Methods other than MAP,
Kindly go through it.

Dr. Pradeep K V Java Programming 80/ 42


Java Set Interface... I
It is of Java Collections framework provides the features of the
mathematical set in Java. And extends the Collection interface.
Unlike the List interface, Sets cannot contain duplicate elements.
The Following Classes uses the functionalities of Set Interface

Methods of Set Interface :


1. add() - adds the specified element to the set

2. addAll() - adds all the elements of the specified collection


to the set

3. iterator() - returns an iterator that can be used to access


elements of the set sequentially

4. remove() - removes the specified element from the set

5. removeAll() - removes all the elements from the set.

Dr. Pradeep K V Java Programming 81/ 42


Java Set Interface... II

6. retainAll() - retains all the elements in the set that are also
present in another specified set

7. clear() - removes all the elements from the set

8. size() - returns the length (number of elements) of the set

9. toArray() - returns an array containing all the elements of the set

10. contains() - returns true if the set contains the specified element

11. containsAll() - returns true if the set contains all the elements
of the specified collection

12. hashCode() - returns a hash code value


(address of the element in the set)

Dr. Pradeep K V Java Programming 82/ 42


Java Set Interface... III

Set Operations :
1. Union - to get the union of two sets x and y,
we can use [Link](y)

2. Intersection - to get the intersection of two sets x and y,


we can use [Link](y)

3. Subset - to check if x is a subset of y,


we can use [Link](x)

import [Link]; import [Link];

class HashSET {
public static void main(String[] args) {
// Creating a set using the HashSet class
Set<Integer> set1 = new HashSet<>();

// Add elements to the set1


[Link](2); [Link](3);
[Link]("Set1: " + set1);

// Creating another set using the HashSet class


Set<Integer> set2 = new HashSet<>();

Dr. Pradeep K V Java Programming 83/ 42


Java Set Interface... IV

// Add elements
[Link](1); [Link](2);
[Link]("Set2: " + set2);

// Set2 Intersection Set1


[Link](set1);
[Link]("Intersection of : " + set2);

// Set2 Union Set1


[Link](set1);
[Link]("Union is: " + set2);

[Link]("Subset of :"+ [Link](set2));


}
}
/*

Set1: [2, 3]
Set2: [1, 2]
Intersection of : [2]
Union is: [2, 3]
Subset of :true

*/

Dr. Pradeep K V Java Programming 84/ 42


Java Algorithms

The Java collections framework provides various algorithms that can be


used to manipulate elements stored in data structures.
Algorithms in Java are static methods that can be used to perform various
operations on collections.
Algorithms are generic in nature (i.e., Can apply on any Collections).
1. sort() : is used to sort elements.
2. shuffle() : is used to destroy, the order present in Data Strucutre.
It does just the opposite of the sorting.
3. reverse() : reverses the order of elements
4. fill() : replace every element with the specified value
5. copy() : creates a copy of elements from the source to destination
6. swap() : swaps the position of two elements in a collection
7. addAll() : adds all the elements of a collection to other collection
8. binarySearch() : searches for the specified element and its position.
9. frequency() : returns the count an element present in collection.
10. disjoint() : checks if two collections contain some common element
11. min() : are used to find the minimum element.
12. max() : are used to find the maximum element.

Dr. Pradeep K V Java Programming 85/ 42


Methods of Iterator interface I

Iterator interface provides the facility of iterating the elements in a forward


direction only.
It allows us to access elements of a collection. It has a subinterface
ListIterator.

Methods of Iterator:
1. hasNext() : returns true if the iterator has more elements
otherwise it returns false.
2. next() : returns the element and moves the cursor pointer
to the next element.
3. remove() : removes the last elements returned by the iterator.
4. forEachRemaining() : performs the specified action for each remaining
element of the collection

Dr. Pradeep K V Java Programming 86/ 42


Java ListIterator Interface I
It provides the functionality to access(bidirectional) elements of a list.
Methods of ListIterator:
1. hasNext() : returns true if there exists an element in the list
2. next() : returns the next element of the list
3. nextIndex() : returns the index of the element that the
next() method will return
4. previous() : returns the previous element of the list
5. previousIndex() : returns the index of the element that the
previous() method will return
6. remove() : removes the element returned by either
next() or previous()
7. set() : replaces the element returned by either next() or previous()
with the specified element
import [Link]; import [Link];

class LISTIterator {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
[Link](1); [Link](3); [Link](2);
[Link]("ArrayList: " + numbers);

// Creating an instance of ListIterator


ListIterator<Integer> iterate = [Link]();

Dr. Pradeep K V Java Programming 87/ 42


Java ListIterator Interface II

// Using the next() method


[Link]("Next Element: " + [Link]());

// Using the nextIndex()


[Link]("Position of Next Element: " + [Link]());

// Using the hasNext() method


[Link]("Is there any next element? " + [Link]());

[Link]("Previous Element: " + [Link]());

// Using the previousIndex()


[Link]("Position of the Previous element: " + [Link]
}
}
/*
ArrayList: [1, 3, 2]
Next Element: 1
Position of Next Element: 1
Is there any next element? true
Previous Element: 1
Position of the Previous element: -1
*/

Dr. Pradeep K V Java Programming 88/ 42


Java Serialization and DeSerialization

Serialization is a process of writing the state of an object into a


byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and For serializing the
object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream
class.
It is a mechanism to convert an object into stream of bytes so that it can
be written into a file, transported through a network or stored into
database.
De-serialization is just a vice versa.
Or
Serialization is converting an object to stream of bytes and
De-serialization is rebuilding the object from stream of bytes.
A class must implement [Link] interface to be eligible for
serialization.
Serializing the object done, by calling writeObject() method
ObjectOutputStream, and
Deserialization we call the readObject() method of ObjectInputStream
class.
Dr. Pradeep K V Java Programming 89/ 42
Example - Serialization and DeSerialization I

// [Link];

public class Student implements [Link]{


private int stuRollNum, stuAge;
private String stuName;
private transient String stuAddress;
private transient int stuHeight;

public Student(int roll, int age, String name, String address, int height){
[Link] = roll; [Link] = age;
[Link] = name; [Link] = address;
[Link] = height;
}
public int getStuRollNum() { return stuRollNum; }
public int getStuAge() { return stuAge; }
public String getStuName() { return stuName; }
public String getStuAddress() { return stuAddress; }
public int getStuHeight() { return stuHeight; }
}

// [Link]

import [Link]; import [Link];


import [Link];

Dr. Pradeep K V Java Programming 90/ 42


Example - Serialization and DeSerialization II

public class StudentSerialization {


public static void main(String args[]) {
Student obj = new Student(50396, 31, "Pradeep K V", "Chennai", 6);
try{
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](obj);
[Link](); [Link]();
[Link]("Serialization Done!!");
}catch(IOException ioe){ [Link](ioe); }
}
}

/* Serialization Done!! */
// [Link]

import [Link]; import [Link];


import [Link];
public class StudentDeSerialization {
public static void main(String args[]) {
Student o=null;

try{
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);

Dr. Pradeep K V Java Programming 91/ 42


Example - Serialization and DeSerialization III

o = (Student)[Link](); [Link](); [Link]();


}
catch(IOException ioe) { [Link](); return; }
catch(ClassNotFoundException cnfe) {
[Link]("Student Class is not found.");
[Link](); return;
}
[Link]("Student Name:"+[Link]());
[Link]("Student Age:"+[Link]());
[Link]("Student Roll No:"+[Link]());
[Link]("Student Address:"+[Link]());
[Link]("Student Height:"+[Link]());
}
}
/*
Student Name:Pradeep K V
Student Age:31
Student Roll No:50396
Student Address:null
Student Height:0
*/

Dr. Pradeep K V Java Programming 92/ 42


Java Transient Keyword I

Java transient keyword is used in serialization. If you define any data


member as transient, it will not be serialized.
Example : In 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 don’t
want to serialize one value, e.g. Age then we can declare the age data
member as transient.
import [Link].*;

class Emp implements Serializable {


private static final long serialversionUID = 50396L;
transient int a;
static int b;
String name;
int age;

// Default constructor
public Emp(String name, int age, int a, int b) {
[Link] = name; [Link] = age; this.a = a; this.b = b;
}
}

public class Serial_DeSerial_Test {

Dr. Pradeep K V Java Programming 93/ 42


Java Transient Keyword II

public static void printdata(Emp object1) {


[Link]("name = " + [Link]);
[Link]("age = " + [Link]);
[Link]("a = " + object1.a);
[Link]("b = " + object1.b);
}
public static void main(String[] args) {
Emp object = new Emp("Pradeep K V", 30, 2, 1000);
String filename = "[Link]";
// Serialization
try { // Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
[Link](object);
[Link](); [Link]();
[Link]("Object has been serialized Data \n"
+ "before Deserialization.");
printdata(object);
object.b = 2000; // value of static variable changed
}
catch (IOException ex) { [Link]("IOException is caught");

object = null;
// Deserialization

Dr. Pradeep K V Java Programming 94/ 42


Java Transient Keyword III

try { // Reading the object from a file


FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
object = (Emp)[Link]();
[Link](); [Link]();
[Link]("Object has been deserialized Data \n"
+ " after Deserialization.");
printdata(object);
}
catch (IOException ex) { [Link]("IOException is caught");
catch (ClassNotFoundException ex) {
[Link]("ClassNotFoundException is caught");
}
}
} /* Object has been serialized Data before Deserialization.
name = Pradeep K V
age = 30, a = 2, b = 1000
Object has been deserialized Data after Deserialization.
name = Pradeep K V
age = 30, a = 0, b = 2000 */

Dr. Pradeep K V Java Programming 95/ 42


Thanks

Dr. Pradeep K V Java Programming 96/ 42

You might also like