JAVA UNIT II (Part-2)
JAVA UNIT II (Part-2)
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 for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Meth Descrip
od tion
1) public void write(int)throws is used to write a byte to the current output
IOException stream.
2) public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Meth Descrip
od tion
1) public abstract int read()throws reads the next byte of data from the input stream. It
InputStream Hierarchy
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream.
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer
to store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
we are writing the textual information in the BufferedOutputStream object which is connected
to the FileOutputStream object. The flush() flushes the data of one stream and send it into
another. It is required if you have connected the one stream with another.
Example:
1. import java.io.*;
2. public class BufferedOutputStreamExample{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Welcome to CMRTC.";
7. byte b[]=s.getBytes();
8. bout.write(b);
9. bout.flush();
10. bout.close();
11. fout.close();
12. System.out.println("succ
ess"); 13. } }
Output:
Success
testout.txt
Welcome to CMRTC.
BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
Example:
1. import java.io.*;
2. public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
"testout.txt"
CMRTC file: Output:
DataOutputStream Class
Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by
a data input stream.
Example:
1. import java.io.*;
2. public class OutputExample {
3. public static void main(String[] args) throws IOException {
4. FileOutputStream file = new FileOutputStream(“D:\\testout.txt”);
5. DataOutputStream data = new DataOutputStream(file);
6. data.writeInt(65);
7. data.flush();
8. data.close();
9. System.out.println("Succcess.
.."); 10. } }
Output:
Succcess...
testout.txt:
A
DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by
a data input stream.
Declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput
Example:
1. import java.io.*;
2. public class DataStreamExample {
Syeda Sumaiya Afreen Page 6
R20 OOPS THROUGH JAVA
3. public static void main(String[] args) throws IOException {
4. InputStream input = new FileInputStream("D:\\testout.txt");
5. DataInputStream inst = new DataInputStream(input);
6. int count = input.available();
7. byte[] ary = new byte[count];
8. inst.read(ary);
9. for (byte bt : ary) {
10. char k = (char) bt;
11. System.out.print(k+"
-"); 12. } } }
FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
Output:
Success...
The content of a text file testout.txt is set with the
data A. testout.txt
A
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to CMRTC.
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Note: Before running the code, a text file named as "testout.txt" is required to be
created.
Welcome In
to this file, we are having following content:
CMRTC.
After executing the above program, you will get a single character from the file which is 87
(in byte form). To see the text, you need to convert it into character.
Output:
W
Output:
Welcome to javaTpoint
SequenceInputStream Class
Java SequenceInputStream class is used to read data from multiple streams. It reads data
sequentially (one by one).
the declaration for Java.io.SequenceInputStream class:
public class SequenceInputStream extends InputStream
Example:
1. import java.io.*;
2. class InputStreamExample {
3. public static void main(String args[])throws Exception{
4. FileInputStream input1=new FileInputStream("D:\\test1.txt");
5. FileInputStream input2=new FileInputStream("D:\\test2.txt");
6. SequenceInputStream inst=new SequenceInputStream(input1, input2);
7. int j;
8. while((j=inst.read())!=-1){
9. System.out.print((char)j);
10. }
11. inst.close();
12. input1.close();
13. input2.clos
e();
14. } }
Test1.txt:
Welcome to CMRTC.
Test2.txt:
CSE.
After executing the program, you will get following
output: Output:
Welcome to CMRTCCSE.
Example that reads the data from two files and writes into another file
1. import java.io.*;
2. class Input1{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin1=new FileInputStream("D:\\testin1.txt");
Output:
Succeess...
testout.txt:
Welcome CMRTCCSE
ByteArrayOutputStream Class
Java ByteArrayOutputStream class is used to write common data into multiple files. In
this stream, the data is written into a byte array which can be written to multiple streams
later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams. The buffer
of ByteArrayOutputStream automatically grows according to data.
Example:
1. import java.io.*;
2. public class DataStreamExample {
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
5. FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");
6. ByteArrayOutputStream bout=new ByteArrayOutputStream();
7. bout.write(65);
8. bout.writeTo(fout1);
9. bout.writeTo(fout2);
10. bout.flush();
11. bout.close();//has no effect
12. System.out.println("Succes
s..."); 13. } }
Output
Success...
A
Syeda Sumaiya Afreen Page 10
A
R20 OOPS THROUGH JAVA
:
f1.txt:
f2.txt:
ByteArrayInputStream Class
The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the
name suggests, it can be used to read byte array as input stream.
Java ByteArrayInputStream class contains an internal buffer which is used to read byte array
as stream. In this stream, the data is read from a byte array. The buffer of
ByteArrayInputStream automatically grows according to data.
Example
1. import java.io.*;
2. public class ReadExample {
3. public static void main(String[] args) throws
IOException { 4. byte[] buf = { 35, 36, 37,
38 };
5. // Create the new byte array input stream
6. ByteArrayInputStream byt = new ByteArrayInputStream(buf);
7. int k = 0;
8. while ((k = byt.read()) != -1) {
9. //Conversion of a byte into character
10. char ch = (char) k;
11. System.out.println("ASCII value of Character is:" + k + "; Special
character is: " + ch); 12. }}}
Output:
ASCII value of Character is:35; Special character is: #
ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &
FilterOutputStream Class
Java FilterOutputStream class implements the OutputStream class. It provides different sub
classes such as BufferedOutputStream and DataOutputStream to provide additional
functionality. So it is less used individually.
Output:
Success...
testout.txt
Welcome to CMRTC CSE.
FilterInputStream Class
Java FilterInputStream class implements the InputStream. It contains different sub
classes as BufferedInputStream, DataInputStream for providing additional functionality. So it
is less used individually.
declaration for java.io.FilterInputStream class
public class FilterInputStream extends InputStream
Example:
1. import java.io.*;
2. public class FilterExample {
3. public static void main(String[] args) throws IOException {
4. File data = new File("D:\\testout.txt");
5. FileInputStream file = new FileInputStream(data);
6. FilterInputStream filter = new BufferedInputStream(file);
7. int k =0;
8. while((k=filter.read())!=-1){
9. System.out.print((char)k);
10. }
11. file.close();
12. filter.close
();
13. } }
"testout.txt" file:CSE
Welcome to CMRTC Output:
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.
Example:
1. import java.io.*;
2. public class InputStreamExample {
3. public static void main(String[] args)throws
Exception{ 4. String srg = "1##2#34###12";
5. byte ary[] = srg.getBytes();
6. ByteArrayInputStream array = new ByteArrayInputStream(ary);
7. PushbackInputStream push = new PushbackInputStream(array);
8. int i;
9. while( (i = push.read())!=
-1) { 10. if(i == '#') {
11. int j;
12. if( (j = push.read()) == '#'){
13. System.out.print("**");
14. }else {
15. push.unread(j);
16. System.out.print((char)i);
17. }
18. }else {
19. System.out.print((char)i);
20. }
21. } }}
Output:
1**2#34**#12
PrintStream Class
The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush() method.
Moreover, its methods don't throw IOException.
Example:
1. import java.io.FileOutputStream;
2. import java.io.PrintStream;
Syeda Sumaiya Afreen Page 13
R20 OOPS THROUGH JAVA
3. public class PrintStreamTest{
4. public static void main(String args[])throws Exception{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(2016);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12. System.out.println("Succ
ess?"); 13. } }
Output
Success...
The content of a text file testout.txt is set with the below data
2016
Hello Java
Welcome to Java
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=19;
4. System.out.printf("%d",a); //Note: out is the object of
printstream 5. } }
Output
19
CHARACTER STREAM CLASSES
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes
Stream class Description
Writer
It is an abstract class for writing to character streams. The methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses will override some
of the methods defined here to provide higher efficiency, functionality or both.
Example:
1. import java.io.*;
2. public class WriterExample {
3. public static void main(String[] args) {
4. try {
5. Writer w = new FileWriter("output.txt");
6. String content = "I love my country";
7. w.write(content);
8. w.close();
9. System.out.println("Done");
10. } catch (IOException e) {
11. e.printStackTrace(
); 12. } } }
Output:
Done
output.txt:
I love my country
Reader
Java Reader is an abstract class for reading character streams. The only methods that a subclass
must implement are read(char[], int, int) and close(). Most subclasses, however, will override
some of the methods to provide higher efficiency, additional functionality, or both.
Example:
1. import java.io.*;
2. public class ReaderExample {
3. public static void main(String[] args) {
Syeda Sumaiya Afreen Page 15
R20 OOPS THROUGH JAVA
4. try {
5. Reader reader = new FileReader("file.txt");
6. int data = reader.read();
7. while (data != -1) {
8. System.out.print((char) data);
9. data = reader.read();
10. }
11. reader.close();
12. } catch (Exception ex) {
13. System.out.println(ex.getMessag
e()); 14. } } }
file.txt
I love my country
:I love my country
Output
FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented
class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it
provides method to write string directly.
Example:
1. import java.io.FileWriter;
2. public class FileWriterExample {
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("testout.txt");
6. fw.write("Welcome to CMRTC CSE.");
7. fw.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("Success...");
10. } }
Output:
Success...
testout.txt:
Welcome to CMRTC CSE.
BufferedWriter Class
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
Example:
1. import java.io.*;
2. public class BufferedWriterExample {
3. public static void main(String[] args) throws Exception {
4. FileWriter writer = new FileWriter("D:\\testout.txt");
5. BufferedWriter buffer = new BufferedWriter(writer);
6. buffer.write("Welcome to CMRTC CSE II CSE D.");
7. buffer.close();
8. System.out.println("Succ
ess"); 9. } }
Output:
success
BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can
Syeda Sumaiya Afreen Page 17
R20 OOPS THROUGH JAVA
be used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.
Example:
1. import java.io.*;
2. public class BufferedReaderExample {
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("testout.txt");
5. BufferedReader br=new BufferedReader(fr);
6. int i;
7. while((i=br.read())!=-1){
8. System.out.print((char)i);
9. }
10. br.close();
11. fr.close();
12. } }
Here, we are assuming that you have following data in "testout.txt" file:
Output:
Welcome to CMRTC CSE II CSE D.
we are connecting the BufferedReader stream with the InputStreamReader stream for
reading the line by line data from the keyboard.
Example:
1. import java.io.*;
2. public class BufferedReaderExample{
3. public static void main(String args[])throws Exception{
4. InputStreamReader r=new InputStreamReader(System.in);
5. BufferedReader br=new BufferedReader(r);
6. System.out.println("Enter your name");
7. String name=br.readLine();
8. System.out.println("Welcome
"+name); 9. } }
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain
we are reading and printing the data until the user prints
stop. Example:
1. import java.io.*;
2. public class BufferedReaderExample{
3. public static void main(String args[])throws Exception{
4. InputStreamReader r=new InputStreamReader(System.in);
Syeda Sumaiya Afreen Page 18
R20 OOPS THROUGH JAVA
5. BufferedReader br=new BufferedReader(r);
6. String name="";
7. while(!name.equals("stop")){
8. System.out.println("Enter data: ");
9. name=br.readLine();
10. System.out.println("data is: "+name);
11. }
12. br.close();
13. r.close();
14. } }
Output:
Enter data: CMRTC
data is: CMRTC
Enter data: CSE
data is: CSE
Enter data: stop
data is: stop
CharArrayReader Class
The CharArrayReader is composed of two words: CharArray and Reader. The
CharArrayReader class is used to read character array as a reader (stream). It inherits Reader
class.
Example:
1. import java.io.CharArrayReader;
2. public class CharArrayExample{
3. public static void main(String[] ag) throws
Exception { 4. char[] ary = { 'C', 'M', 'R',
'T', 'C', 'C', 'S', 'E'};
5. CharArrayReader reader = new CharArrayReader(ary);
6. int k = 0;
7. // Read until the end of a file
8. while ((k = reader.read()) != -1) {
9. char ch = (char) k;
10. System.out.print(ch + " : ");
11. System.out.println(
k); 12.} } }
Output
CharArrayWriter Class
The CharArrayWriter class can be used to write common data to multiple files. This
class inherits Writer class. Its buffer automatically grows when data is written in this stream.
Calling the close() method on this object has no effect.
Example:
1. import java.io.CharArrayWriter;
2. import java.io.FileWriter;
3. public class CharArrayWriterExample {
4. public static void main(String args[])throws Exception{
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("Welcome to CMRTC CSE");
7. FileWriter f1=new FileWriter("D:\\a.txt");
8. FileWriter f2=new FileWriter("D:\\b.txt");
9. FileWriter f3=new FileWriter("D:\\c.txt");
10. FileWriter f4=new FileWriter("D:\\d.txt");
11. out.writeTo(f1);
12. out.writeTo(f2);
13. out.writeTo(f3);
14. out.writeTo(f4);
15. f1.close();
16. f2.close();
17. f3.close();
18. f4.close();
19. System.out.println("Succes
s..."); 20. } }
Output
Success...
After executing the program, you can see that all files have common data: Welcome to
javaTpoint. a.txt:
Welcome to CMRTC CSE
b.txt:
Welcome to CMRTC CSE
c.txt:
Welcome to CMRTC CSE
d.txt:
Welcome to CMRTC CSE
PrintWriter class
simple example of writing the data on a console and in a text file testout.txt using Java
PrintWriter class.
1. import java.io.File;
2. import java.io.PrintWriter;
3. public class PrintWriterExample {
4. public static void main(String[] args) throws Exception {
5. //Data to write on Console using PrintWriter
6. PrintWriter writer = new PrintWriter(System.out);
7. writer.write("Welcome to CMR TC.");
8. writer.flush();
9. writer.close();
10. //Data to write in File using PrintWriter
11. PrintWriter writer1 =null;
12. writer1 = new PrintWriter(new File("testout.txt"));
13. writer1.write("CSE Department.");
14. writer1.flush();
15. writer1.close();
16. } }
Outpt
Welcome to CMR TC.
The content of a text file testout.txt is set with the data CSE Department.
OutputStreamWriter
OutputStreamWriter is a class which is used to convert character stream to byte stream, the
characters are encoded into byte using a specified charset. write() method calls the encoding
converter which converts the character into bytes.
The resulting bytes are then accumulated in a buffer before being written into the underlying
output stream. The characters passed to write() methods are not buffered. We optimize the
performance of OutputStreamWriter by using it with in a BufferedWriter so that to avoid
frequent converter invocation.
Example:
1. Import java.io.*;
2. public class OutputStreamWriterExample {
3. public static void main(String[]
args) { 4.
5. try {
6. OutputStream outputStream = new FileOutputStream("output.txt");
7. Writer outputStreamWriter = new
OutputStreamWriter(outputStream); 8.
InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and
decodes them into characters using a specified charset. The charset that it uses may be
specified by name or may be given explicitly, or the platform's default charset may be
accepted.
Example:
1. Import java.io.*;
2. public class InputStreamReaderExample {
3. public static void main(String[] args) {
4. try {
5. InputStream stream = new FileInputStream("file.txt");
6. Reader reader = new InputStreamReader(stream);
7. int data = reader.read();
8. while (data != -1) {
9. System.out.print((char) data);
10. data = reader.read();
11. }
12. } catch (Exception e) {
13. e.printStackTrace(
); 14. } } }
Output:
Hello World
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.
Example:
1. import java.io.*;
2. public class ReaderExample{
3. public static void main(String[] args) throws
Exception { 4. char ary[] = {'1','-','-','2','-
Output
1#*2-34#*-56
File Class
The File class is an abstract representation of file and directory pathname. A pathname can
be either absolute or relative.
The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.
Example:
1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[]
args) { 4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. e.printStackTrace(
); 14. } } }
Output:
New File is created!
Output:
testFile1.txt
/home/Work/Project/File/testFile1.txt
true
/home/Work/Project/File/testFile1.txt Exists? true
Example:
1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File f=new File("/Users/sonoojaiswal/Documents");
5. String filenames[]=f.list();
6. for(String filename:filenames){
7. System.out.println(filena
me); 8. } } }
Output:
If end-of-file is reached before the desired number of byte has been read than EOFException
is thrown. It is a type of IOException.
Example:
1. import java.io.IOException;
2. import
java.io.RandomAccessFile; 3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random
access file." after running the program it will contains
This class is used for reading I love my country and my peoplele.
CONSOLE CLASS
The Java Console class is be used to get input from console. It provides methods to read
texts and passwords.
If you read password using Console class, it will not be displayed to the user. The
java.io.Console class is attached with system console internally.
System class provides a static method console() that returns the singleton instance of Console class.
public static Console console(){}
Console c=System.console();
Example:
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcom
e "+n); 8. } }
Output
Enter your name: Bhaskar
Welcome Bhaskar
SERIALIZATION
For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
Advantages
It is mainly used to travel object's state on the network (which is known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability. The Cloneable and
Remote are also marker interfaces.
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Example: Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method
of ObjectOutputStream class provides the functionality to serialize the object. We are saving
the state of the object in the file named f.txt.
1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception
e){System.out.println(e);} 16. } }
success
Example: Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
211 ravi
Now you can serialize the Student class object that extends the Person class which is
Serializable. Parent class properties are inherited to subclasses so if parent class is
Serializable, subclass would also be.
ENUMS
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER,
and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK)
etc. According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly.
Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated
JAVA Unit-2 Data Type) is used to define an enum in Java. CMR Technical Campus
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in
Java enum.
Example:
1. class EnumExample1{
2. //defining the enum inside the class
Syeda Sumaiya Afreen Page 30
R20 OOPS THROUGH JAVA
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //main method
5. public static void main(String[] args) {
6. //traversing the enum
7. for (Season s : Season.values())
8. System.out.printl
n(s); 9. }}
Output:
WINTER
SPRING
SUMMER
FALL
example of Java enum where we are using value(), valueOf(), and ordinal() methods of Java enum.
1. class EnumExample1{
2. //defining enum within class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //creating the main method
5. public static void main(String[] args) {
6. //printing all enum
7. for (Season s : Season.values()){
8. System.out.printl
n(s); 9. }
10. System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
11. System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
12. System.out.println("Index of SUMMER is:
"+Season.valueOf("SUMMER").ordinal()); 13. }}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Note: Java compiler internally adds values(), valueOf() and ordinal() methods within the enum
at compile time. It internally creates a static and final class for the enum.
Output:
WINTER
Output:
WINTER
Output:
WINTER
Example:
1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4. private int value;
5. private Season(int value){
6. this.value=val
ue; 7. } }
8. public static void main(String args[]){
9. for (Season s : Season.values())
10. System.out.println(s+"
Output:
WINTER 5
SPRING 10
SUMMER 15
FALL 20
Note: Constructor of enum type is private. If you don't declare private compiler internally creates
private constructor.
1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=val
ue; 6. } }
Internal code generated by the compiler for the above example of enum type
1. final class Season extends
Enum 2. {
5. return
(Season[])$VALUES.clone(); 6. }
Output:
Monday
Output:50 5
Example: Unboxing
1. class UnboxingExample1{
2. public static void main(String args[]){
3. Integer i=new Integer(50);
4. int a=i;
5. System.out.println(a);
6. } }
Output:50
Autoboxing and Unboxing with comparison operators
Autoboxing can be performed with comparison
operators Example:
1. class UnboxingExample2{
2. public static void main(String args[]){
3. Integer i=new
Integer(50); 4.
5. if(i<100){ //unboxing internally
6. System.out.println(i);
7. }
8. } }
Output:50
} }
Output:int
class Boxing2{
short
s1=30,s2=40;
m(s1,s2);
} }
Output:int int
int
a=30;
m(a);
} }
Syeda Sumaiya Afreen Page 36
R20 OOPS THROUGH JAVA
Output:Integer
GENERICS
It would be nice if we could write a single sort method that could sort the elements in an
Integer array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of related
types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid
types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects,
then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.
Generic Methods
You can write a single generic method declaration 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:
// generic method
printArray
// Display
array
elements for(E
element :
inputArray) {
Array doubleArray
public static contains:
void main(String args[]) {
System.out.println("Array
Bounded Type Parameters integerArray
contains:"); printArray(intArray); // pass
There may be times when you'll want to restrict the kinds of types that are allowed to be
an Integer array
passed to a type parameter.
System.out.println("\nArray doubleArray
Forcontains:");
example, a method that //operates
printArray(doubleArray); pass on numbers might only want to accept instances of Number or
its subclasses. This is what bounded type parameters are for.
a Double array
To System.out.println("\nArray
declare a bounded characterArray
type parameter, list the type parameter's name, followed by the extends
contains:"); printArray(charArray); // pass a
keyword, followed by its upper bound.
Character array
}
Example:
}
if(y.compareTo(max) > 0) {
3, 4, 5, maximum( 3, 4, 5 ));
Output
Max of 3, 4 and 5 is 5
Generic Classes
A generic class declaration looks like a non-generic class declaration, except that the class
name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
public class Box<T> {
private T t;
public T get() {
return t;
Output
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
Syeda Sumaiya Afreen Page 40
}
}
R20 OOPS THROUGH JAVA
Integer Value :10
String Value :Hello World