Java Unit II Part II
Java Unit II Part II
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
UNIT-II PART-II
UNIT-II
Stream in java
In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows
us to read from and write to it. A stream can be linked to a data source, or data destinations,
like a console, file or network connection by java IO system. The stream-based IO
operations are faster than normal IO operations.
In java, the stream-based IO operations are performed using two separate streams input
stream and output stream. The input stream is used for input operations, and the output
stream is used for output operations. The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the
console.
✔ [Link]: standard output stream for console output operations.
✔ [Link]: standard input stream for console input operations.
✔ [Link]: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
✔ Byte Stream
✔ Character Stream
The following picture shows how streams are categorized, and various built-in classes used
by the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to
handle data streams in Java.
The following picture shows the classes used for byte stream operations.
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
int available()
1
It returns the number of bytes that can be read from the input stream.
int read()
2
It reads the next byte from the input stream.
int read(byte[] b)
3
It reads a chunk of bytes from the input stream and store them in its byte array, b.
void close()
4 It closes the input stream and also frees any resources connected with this input
stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
void write(int n)
1
It writes byte(contained in an int) to the output stream.
void write(byte[] b)
2
It writes a whole byte array(b) to the output stream.
void flush()
3
It flushes the output steam by forcing out buffered bytes to be written out.
void close()
4 It closes the output stream and also frees any resources connected with this output
stream.
try {
[Link]("Enter any character: ");
char c = (char)[Link]();
[Link]("You have entered '" + c + "'");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
Enter any character: A
You have entered 'A'
We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.
Example:
//Example - Writing data into a file
import [Link].*;
[Link]([Link]());
[Link]("Writing data into a file is success!");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
C:\javaclass>java WritingDemo
In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream. The unicode set is basically a type of character set where each character corresponds
to a specific numeric value within the given character set, and every programming language
has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used for
character stream based output operations.
The Reader and Writer classes have several existing classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
[Link]. Method with Description
1 int read()
It reads the next character from the input stream.
5 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed
('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
6 boolean ready()
It tells whether the stream is ready to be read.
7 void close()
It closes the input stream and also frees any resources connected with this input
stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes single character.
7 Writer append(char c)
It appends the specified character to the writer.
10 void close()
It closes the output stream and also frees any resources connected with this output
stream.
We can use the BufferedReader class to read data from the console. The
BufferedInputStream class needs InputStreamReaderclass. The BufferedReader use a
method read( ) to read a value from the console, or file, or socket.
name = [Link]();
try {
[Link](msg);
[Link]("Writing done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 11
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Writing done!!!
Reading input data using the BufferedReader class is the traditional technique. This way of
the reading method is used by wrapping the [Link] (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from
the console.
The BufferedReader class has defined in the [Link] package.
Example:
//Reading console input using BufferedReader class in java
import [Link].*;
try {
[Link]("Please enter your name : ");
name = [Link]();
[Link]("Hello, " + name + "!");
}
catch(Exception e) {
[Link](e);
}
finally {
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 12
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]();
}
}
}
Output:
Reading input data using the Scanner class is the most commonly used method. This way
of the reading method is used by wrapping the [Link] (standard input stream) which is
wrapped in a Scanner, we can read input from the console.
Consider the following example code to understand how to read console input using
Scanner class.
Example:
import [Link];
}
}
Output:
Reading input data using the Console class is the most commonly used method. This class
was introduced in Java 1.6 version.
The Console class has defined in the [Link] package.
if(con != null) {
name = [Link]("Please enter your name : ");
[Link]("Hello, " + name + "!!");
}
else {
[Link]("Console not available.");
}
}
}
Output:
The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.
Both print() and println() methods are used with [Link] stream.
The print() method writes console output in the same line. This method can be used with
console output only.
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 14
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The println() method writes console output in a separate line (new line). This method can be
used with console and also with other output sources.
Let's look at the following code to illustrate print() and println() methods.
Example:
public class WritingPrintDemo {
for(int i:list)
[Link](i); //prints in same line
[Link]("");
for(int i:list)
[Link](i); //Prints in separate lines
}
}
Output:
010203040 //prints in same line
0 //Prints in separate lines
10
20
30
40
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to
the console, it also accept escape sequences.
for(int i:list) {
[Link](i);
[Link]('\n');
}
}
}
Output:
A to Z //print A,B,C …to Z (vertical)
The File is a built-in class in Java. In java, the File class has been defined in the [Link]
package. The File class represents a reference to a file or directory. The File class has
various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
1 File(String pathname)
It creates a new File instance by converting the given pathname string into an
abstract pathname. If the given string is the empty string, then the result is the empty
abstract pathname.
It creates a new File instance from a parent abstract pathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking the
single-argument File constructor on the given child pathname string.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not
name a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the
application; false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to
write to the file; false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if
the named file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is
successfully deleted; false otherwise.
16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual
machine terminates.
17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary
parent directories; false otherwise.
21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the
operation succeeded; false otherwise.
22 String[] list()
It returns an array of strings containing names of all the files and directories in the
current directory.
24 File[] listFiles()
It returns an array of file references containing names of all the files and directories
in the current directory.
}
Output:
C:\javaclass>java FileClassTest
Executable File : false
Name of the file: [Link]
Path of the file: C:\javaclass\[Link]
Parent name: C:\javaclass
Write mode: false
Read mode: false
File Reading & Writing in Java
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.
The following example program that reads data from a file and writes the same to another
file using FileInoutStream and FileOutputStream classes.
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 20
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Example:
import [Link].*;
public class FileReadingTest {
try {
in = new FileInputStream("C:\\javaclass\\[Link]");
out = new FileOutputStream("C:\\javaclass\\[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing has been success!!!");
}
catch(Exception e){
[Link](e);
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Output:
Reading and Writing has been success!!!
The following example program that reads data from a file and writes the same to another
file using FileReader and FileWriter classes.
Example:
import [Link].*;
public class FileIO {
try {
in = new FileReader("C:\\javaclass\\[Link]");
out = new FileWriter("C:\\javaclass\\[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 22
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Output:
Reading and Writing in a file is done!!!
RandomAccessFile in Java
In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be accessed
randomly. The RandomAccessFile class has several methods used to move the cursor position in a
file.
A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
● r - Creates the file with read mode; Calling write methods will result in an
IOException.
● rw - Creates the file with read and write mode.
● rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
● rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.
1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range
0-255.
2 int read(byte[] b)
It reads byte of data from file upto [Link], -1 if end of file is reached.
4 boolean readBoolean()
It reads a boolean value from from the file.
5 byte readByte()
It reads signed eight-bit value from file.
6 char readChar()
It reads a character value from file.
7 double readDouble()
It reads a double value from file.
8 float readFloat()
It reads a float value from file.
9 long readLong()
It reads a long value from file.
10 int readInt()
It reads a integer value from file.
11 void readFully(byte[] b)
It reads bytes initialising from offset position upto [Link] from the buffer.
13 String readUTF()
t reads in a string from the file.
15 long length()
It returns the length of the file.
16 void write(int b)
It writes the specified byte to the file from the current cursor position.
17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the file as a four-byte quantity, high byte first.
18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the file as an eight-byte quantity,
high byte first.
Example:
import [Link].*;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
[Link]("Use of read() method : " + f_ref.read());
f_ref.seek(0);
// readBoolean() method :
[Link]("Use of readBoolean() : " + f_ref.readBoolean());
// readByte() method :
[Link]("Use of readByte() : " + f_ref.readByte());
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
[Link]("Use of readChar() : " + f_ref.readChar());
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
[Link]("Use of readDouble() : " + f_ref.readDouble());
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
[Link]("Use of readFloat() : " + f_ref.readFloat());
f_ref.seek(0);
// Create array upto [Link]
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);
f_ref.seek(0);
In java, the Serialization is the process of converting an object into a byte stream so that it
can be stored on to a file, or memory, or a database for future access. The deserialization is
reverse of serialization. The deserialization is the process of reconstructing the object from
the serialized state.
Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.
Serialization in Java
We must have to implement the Serializable interface for serializing the object.
The Serializable interface must be implemented by the class whose object needs to be
persisted.
The String class and all the wrapper classes implement the [Link] interface by
default.
Example: [Link]
import [Link];
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream.
Example:
import [Link].*;
Output:
Operation done
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 29
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization.
In a java programming language, the Deserialization is achieved with the help of class
ObjectInputStream. This class provides a method readObject() to deserializing an object.
Let's see an example where we are reading the data from a deserialized object.
Example: [Link]
import [Link].*;
class Depersist{
public static void main(String args[]){
try{
Enum in Java
In java, an Enumeration is a list of named constants. The enum concept was introduced in
Java SE 5 version.
In java, the enumeration concept was defined based on the class concept. When we create an
enum in java, it converts into a class type. This concept enables the java enum to have
constructors, methods, and instance variables.
All the constants of an enum are public, static, and final. As they are static, we can access
directly using enum name.
The main objective of enum is to define our own data types in Java, and they are said to be
enumeration data types.
To create enum in Java, we use the keyword enum. The syntax for creating enum is similar
to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a method.
Example:
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}
}
Output:
Today is FRIDAY
All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
● Every enum is converted to a class that extends the built-in class Enum.
● Every constant of an enum is defined as an object.
● As an enum represents a class, it can have methods, constructors. It also gets a few
extra methods from the Enum class, and one of them is the values() method.
All the wrapper classes in Java were defined in the [Link] package.
The following table shows the primitive type and its corresponding wrapper class.
1 byte Byte
2 short Short
3 int Interger
4 long Long
5 float Float
6 double Double
7 char Character
8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class
object is called autoboxing or simply boxing. For example, converting an int value to an
Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.
Note:
We can also perform autoboxing manually using the method valueOf( ), which is provided
by every wrapper class.
Example: [Link]
import [Link].*;
}
}
Output:
num = 100, i = 100, j = 100
The compiler automatically performs the auto un-boxing when a wrapper class object has
assigned to a primitive type.
Note:
We can also perform auto un-boxing manually using the method intValue( ), which is
provided by Integer wrapper class. Similarly every wrapper class has a method for auto
un-boxing.
Example: [Link]
import [Link].*;
public class AutoUnboxingExample {
public static void main(String[] args) {
// Auto un-boxing : Wrapper to primitive
Integer num = 200;
int i = num;
int j = [Link]();
Generics in Java
The java generics is a language feature that allows creating methods and class which can
handle any type of data values. The generic programming is a way to write generalized
programs, java supports it by java generics.
The java generics is similar to the templates in the C++ programming language.
Note:
● Most of the collection framework classes are generic classes.
● The java generics allows only non-primitive type, it does not support primitive types
like int, float, char, etc.
● Generic Method
● Generic Class
Using a generic method, we can create a single method that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately.
Example: GenericFunctions
public class GenericFunctions {
[Link](45.6f, 10);
[Link](10, 10);
[Link]("Hi", 'c');
}
}
Output:
([Link], [Link])
([Link], [Link])
([Link], [Link])
In the above example code, the method displayData( ) is a generic method that allows a
different type of parameter values for every function call.
A generic class declaration looks like a non-generic class declaration, except that the class
name is followed by a type parameter section.
Example:
public class GenericsExample<T> {
T obj;
public GenericsExample(T anotherObj) {
[Link] = anotherObj;
}
public T getData() {
return [Link];
}