0% found this document useful (0 votes)
5 views

JAVA UNIT II (Part-2)

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JAVA UNIT II (Part-2)

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

R20 OOPS THROUGH JAVA

STREAM BASED I/O(JAVA.IO)


Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
to make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.

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

code to print output and an error message to the console.


1. System.out.println("simple message");
2. System.err.println("error message");

the code to get input from console.


1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character

JAVA Unit-2 CMR Technical Campus


OUTPUTSTREAM VS INPUTSTREAM

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.

Syeda Sumaiya Afreen Page 1


R20 OOPS THROUGH JAVA

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.

Useful methods of OutputStream

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.

Useful methods of InputStream

Meth Descrip
od tion
1) public abstract int read()throws reads the next byte of data from the input stream. It

Syeda Sumaiya Afreen Page 2


R20 OOPS THROUGH JAVA
IOException returns -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes that


IOException can be read from the current input stream.
3) public void close()throws IOException is used to close the current input stream.

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 CLASSES

Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream.

Syeda Sumaiya Afreen Page 3


R20 OOPS THROUGH JAVA
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.

Some important Byte stream classes.


Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStrea Used for Buffered Output Stream.
m
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data
type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

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:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO


Package\\testout. txt"));

Syeda Sumaiya Afreen Page 4


R20 OOPS THROUGH JAVA
declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream

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.

The important points about BufferedInputStream are:


o When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.

declaration for Java.io.BufferedInputStream class:


public class BufferedInputStream extends FilterInputStream

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

Syeda Sumaiya Afreen Page 5


R20 OOPS THROUGH JAVA
11. bin.close();
12. fin.close();
13. }catch(Exception
e){System.out.println(e);} 14. } }

Here, we are assuming that you have following data in


CMRTC

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

declaration for java.io.DataOutputStream class:


public class DataOutputStream extends FilterOutputStream implements DataOutput

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

Here, we are assuming that you have following data in "testout.txt"


JAVA
file: Output:
J-A-V-A

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.

declaration for Java.io.FileOutputStream class:


public class FileOutputStream extends OutputStream

Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception
e){System.out.println(e);} 10. } }

Output:
Success...
The content of a text file testout.txt is set with the
data A. testout.txt
A

example 2: write string


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{

Syeda Sumaiya Afreen Page 7


R20 OOPS THROUGH JAVA
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. String s="Welcome to CMRTC.";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception
e){System.out.println(e);} 12. } }

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.

declaration for java.io.FileInputStream class:


public class FileInputStream extends InputStream

example 1: read single character


1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8. fin.close();
9. }catch(Exception
e){System.out.println(e);} 10. } }

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

example 2: read all characters


1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
Syeda Sumaiya Afreen Page 8
R20 OOPS THROUGH JAVA
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=0;
7. while((i=fin.read())!=-1){
8. System.out.print((char)i);
9. }
10. fin.close();
11. }catch(Exception
e){System.out.println(e);} 12. } }

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

Syeda Sumaiya Afreen Page 9


R20 OOPS THROUGH JAVA
5. FileInputStream fin2=new FileInputStream("D:\\testin2.txt");
6. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
7. SequenceInputStream sis=new SequenceInputStream(fin1,fin2);
8. int i;
9. while((i=sis.read())!=-1)
10. {
11. fout.write(i);
12. }
13. sis.close();
14. fout.close();
15. fin1.close();
16. fin2.close();
17. System.out.println("Succe
ss.."); 18. } }

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.

declaration for Java.io.ByteArrayOutputStream class:


public class ByteArrayOutputStream extends OutputStream

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.

declaration for Java.io.ByteArrayInputStream class:


public class ByteArrayInputStream extends InputStream

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.

declaration for java.io.FilterOutputStream class:


public class FilterOutputStream extends OutputStream

Syeda Sumaiya Afreen Page 11


R20 OOPS THROUGH JAVA
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. FileOutputStream file = new FileOutputStream(data);
6. FilterOutputStream filter = new FilterOutputStream(file);
7. String s="Welcome to CMRTC CSE.";
8. byte b[]=s.getBytes();
9. filter.write(b);
10. filter.flush();
11. filter.close();
12. file.close();
13. System.out.println("Success..
."); 14. } }

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

Here, we are assuming that you have following data in


Welcome to CMRTC CSE

"testout.txt" file:CSE
Welcome to CMRTC Output:

Syeda Sumaiya Afreen Page 12


R20 OOPS THROUGH JAVA

PushbackInputStream Class
Java PushbackInputStream class overrides InputStream and provides extra functionality to another
input stream. It can unread a byte which is already read and push back one byte.

declaration for java.io.PushbackInputStream class:


public class PushbackInputStream extends FilterInputStream

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.

declaration for Java.io.PrintStream class:


public class PrintStream extends FilterOutputStream implements Closeable. Appendable

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

simple example of printing integer value by format specifier using printf()


method of java.io.PrintStream class.

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

BufferedReader Handles buffered input stream.

Syeda Sumaiya Afreen Page 14


R20 OOPS THROUGH JAVA

BufferedWriter Handles buffered output stream.


FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

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.

Some of the implementation classes are:


BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader

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.

declaration for Java.io.FileWriter class:


public class FileWriter extends OutputStreamWriter

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.

Syeda Sumaiya Afreen Page 16


R20 OOPS THROUGH JAVA
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.
It is character-oriented class which is used for file handling in java.

declaration for Java.io.FileReader class:


public class FileReader extends InputStreamReader
Example:
1. import java.io.FileReader;
2. public class FileReaderExample {
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("D:\\testout.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.print((char)i);
8. fr.close();
9. } }

Here, we are assuming that you have following data in


Welcome to CMRTC CSE.

"testout.txt" file: Output:


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.

declaration for Java.io.BufferedWriter class:


public class BufferedWriter extends Writer

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

Welcome to CMRTC CSE II CSE D.

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.

declaration for Java.io.BufferedReader class:


public class BufferedReader extends Reader

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.

declaration for Java.io.CharArrayReader class:


public class CharArrayReader extends Reader

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

Syeda Sumaiya Afreen Page 19


R20 OOPS THROUGH JAVA
C : 67
M : 77
R : 82
T : 84
C : 67
C : 67
S : 83
E : 69

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.

declaration for Java.io.CharArrayWriter class:


public class CharArrayWriter extends Writer

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

Syeda Sumaiya Afreen Page 20


R20 OOPS THROUGH JAVA
Java PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.

declaration for Java.io.PrintWriter class:


public class PrintWriter extends Writer

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.

Syeda Sumaiya Afreen Page 21


R20 OOPS THROUGH JAVA
9. outputStreamWriter.write("Hello
World"); 10.
11. outputStreamWriter.close();
12. } catch (Exception e) {
13. e.getMessage()
; 14. }}}

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

The file.txt contains text "Hello World" the InputStreamReader


reads Character by character from the file

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.

declaration for java.io.PushbackReader class:


public class PushbackReader extends FilterReader

Example:
1. import java.io.*;
2. public class ReaderExample{
3. public static void main(String[] args) throws
Exception { 4. char ary[] = {'1','-','-','2','-

Syeda Sumaiya Afreen Page 22


R20 OOPS THROUGH JAVA
','3','4','-','-','-','5','6'};
5. CharArrayReader reader = new CharArrayReader(ary);
6. PushbackReader push = new PushbackReader(reader);
7. int i;
8. while( (i = push.read())!=
-1) { 9. if(i == '-') {
10. int j;
11. if( (j = push.read()) == '-'){
12. System.out.print("#*");
13. }else {
14. push.unread(j); // push back single character
15. System.out.print((char)i);
16. }
17. }else {
18. System.out.print((char)i);
19. }}} }

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!

Syeda Sumaiya Afreen Page 23


R20 OOPS THROUGH JAVA
Example:
1. import java.io.*;
2. public class FileDemo2 {
3. public static void main(String[]
args) { 4.
5. String path = "";
6. boolean bool = false;
7. try {
8. // createing new files
9. File file = new File("testFile1.txt");
10. file.createNewFile();
11. System.out.println(file);
12. // createing new canonical from file object
13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists();
17. // returns absolute pathname
18. path = file2.getAbsolutePath();
19. System.out.println(bool);
20. // if file exists
21. if (bool) {
22. // prints
23. System.out.print(path + " Exists? " + bool);
24. }
25. } catch (Exception e) {
26. // if any error occurs
27. e.printStackTrace();
28. }
29. }
30. }

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:

Syeda Sumaiya Afreen Page 24


R20 OOPS THROUGH JAVA
"info.properties"
"info.properties".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
apache-tomcat-9.0.0.M19.tar
bestreturn_org.rtf
BIODATA.pages
BIODATA.pdf
BIODATA.png
struts2jars.zip workspace
BIODATA.png
struts2jars.zip
workspace
RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations.

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

Syeda Sumaiya Afreen Page 25


R20 OOPS THROUGH JAVA

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.

declaration for Java.io.Console class:


public final class Console extends Object implements Flushable

System class provides a static method console() that returns the singleton instance of Console class.
public static Console console(){}

code to get the instance of Console class.

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

Example: read password


1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is:
"+pass); 9. } }
Output
Syeda Sumaiya Afreen Page 26
R20 OOPS THROUGH JAVA
Enter password:
Password is: 123

SERIALIZATION

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is


mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted


into an object. The serialization and deserialization process is platform-independent, it means
you can serialize an object in a platform and deserialize in different platform.

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.

It must be implemented by the class whose object you want to persist.


The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Example:
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;

Syeda Sumaiya Afreen Page 27


R20 OOPS THROUGH JAVA
7. this.name =
name; 8. } }

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

Syeda Sumaiya Afreen Page 28


R20 OOPS THROUGH JAVA
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception
e){System.out.println(e);} 13. } }

211 ravi

Serialization with Inheritance (IS-A Relationship)


If a class implements serializable then all its sub classes will also be
serializable. Let's see the example given below:
1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name =
name;
8. } }

1. class Student extends Person{


2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fe
e; 8.} }

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.

Java Serialization with the static data member


If there is any static data member in a class, it will not be serialized because static is the part
of class not object.
1. class Employee implements Serializable{
2. int id;
3. String name;
4. static String company="SSS IT Pvt Ltd";//it won't be serialized
5. public Student(int id, String name) {
6. this.id = id;
7. this.name =
name; 8. } }

Syeda Sumaiya Afreen Page 29


R20 OOPS THROUGH JAVA

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.

Points to remember for Java Enum


o Enum improves type safety
o Enum can be easily used in switch
o Enum can be traversed
o Enum can have fields, constructors and methods
o Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class

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.

Java Enum Example: Defined outside class

Syeda Sumaiya Afreen Page 31


R20 OOPS THROUGH JAVA
1. enum Season { WINTER, SPRING, SUMMER, FALL }
2. class EnumExample2{
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.printl
n(s); 6. }}

Output:
WINTER

Java Enum Example: Defined inside class


1. class EnumExample3{
2. enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
3. public static void main(String[] args) {
4. Season s=Season.WINTER;//enum type is required to access WINTER
5. System.out.printl
n(s); 6. }}

Output:
WINTER

Java Enum Example: main method inside Enum


If you put main() method inside the enum, you can run the enum directly.
1. enum Season {
2. WINTER, SPRING, SUMMER, FALL;
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.printl
n(s); 6. } }

Output:
WINTER

Initializing specific values to the enum constants


The enum constants have an initial value which starts from 0, 1, 2, 3, and so on. But, we can
initialize the specific value to the enum constants by defining fields and constructors. As
specified earlier, Enum can have fields, constructors, and methods.

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

Syeda Sumaiya Afreen Page 32


R20 OOPS THROUGH JAVA
"+s.value); 11. }}

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

3. public static Season[]


values() 4. {

5. return
(Season[])$VALUES.clone(); 6. }

7. public static Season


valueOf(String s) 8. {
9. return (Season)Enum.valueOf(Season, s);
10. }
11. private Season(String s, int i, int j)
12. {
13. super(s, i);
14. value = j;
15. }

Syeda Sumaiya Afreen Page 33


R20 OOPS THROUGH JAVA
16. public static final Season WINTER;
17. public static final Season SUMMER;
18. private int value;
19. private static final Season $VALUES[];
20. static
21. {
22. WINTER = new Season("WINTER", 0, 10);
23. SUMMER = new Season("SUMMER", 1, 20);
24. $VALUES = (new Season[] {
25. WINTER,
SUMMER 26. });
27. } }

Java Enum in a switch statement


1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY}
3. public static void main(String args[]){
4. Day
day=Day.MONDA
Y;
5.
6. switch(day){
7. case SUNDAY:
8. System.out.println("sunday");
9. break;
10. case MONDAY:
11. System.out.println("monday");
12. break;
13. default:
14. System.out.println("other day");
15. }
16.
}}

Output:
Monday

AUTOBOXING AND UNBOXING:


The automatic conversion of primitive data types into its equivalent Wrapper type is known
as boxing and opposite operation is known as unboxing. This is the new feature of Java5. So
java programmer doesn't need to write the conversion code.
Advantage: No need of conversion between primitives and Wrappers manually so less coding
is required. Example: Autoboxing
1. class BoxingExample1{
2. public static void main(String args[]){
3. int a=50;
Syeda Sumaiya Afreen Page 34
R20 OOPS THROUGH JAVA
4. Integer a2=new Integer(a);//Boxing
5. Integer a3=5;//Boxing
6. System.out.println(a2+"
"+a3); 7. } }

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

Autoboxing and Unboxing with method overloading


In method overloading, boxing and unboxing can be performed. There are some rules
for method overloading with boxing:
o Widening beats boxing
o Widening beats varargs
o Boxing beats varargs

1. Autoboxing where widening beats boxing


If there is possibility of widening and boxing, widening beats boxing.
class Boxing1{

static void m(int i){System.out.println("int");}

static void m(Integer i){System.out.println("Integer");}

public static void main(String args[]){

Syeda Sumaiya Afreen Page 35


R20 OOPS THROUGH JAVA
short
s=30;
m(s);

} }
Output:int

2) Example of Autoboxing where widening beats varargs


If there is possibility of widening and varargs, widening beats var-args.

class Boxing2{

static void m(int i, int


i2){System.out.println("int int");} static void
m(Integer... i){System.out.println("Integer...");}
public static void main(String args[]){

short
s1=30,s2=40;
m(s1,s2);

} }
Output:int int

3) Example of Autoboxing where boxing beats varargs


class Boxing3{

static void m(Integer


i){System.out.println("Integer");} static void
m(Integer... i){System.out.println("Integer...");}
public static void main(String args[]){

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.

Following are the rules to define Generic Methods −


• All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next example).
• Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that specifies
a generic type name.
• The type parameters can be used to declare the return type and act as placeholders for
the types of the arguments passed to the generic method, which are known as actual
type arguments.
• A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double
and char)

Example:

Syeda Sumaiya Afreen Page 37


R20 OOPS THROUGH JAVA
public class
GenericMethodTest
{

// generic method
printArray

public static < E > void printArray( E[] inputArray )


{

// Display
array
elements for(E
element :
inputArray) {

System.out.printf("%s ", element);


Output
}
Array integerArray contains:
System.out.println();
12345
}

Array doubleArray
public static contains:
void main(String args[]) {

1.1 //2.2 3.3arrays


Create 4.4of Integer, Double and
Character Integer[] intArray = { 1, 2, 3,
4, 5 };
Array characterArray contains:
Double[] doubleArray = { 1.1, 2.2,
3.3, 4.4 }; Character[] charArray = {
H E'H',L'E',L'L',O'L', 'O' };

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:
}

Syeda Sumaiya Afreen Page 38


R20 OOPS THROUGH JAVA
public class MaximumTest {

// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {

T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0) {

max = y; // y is the largest so far

Syeda Sumaiya Afreen Page 39


R20 OOPS THROUGH JAVA

public static void main(String args[]) { System.out.printf("Max of %d,


%d and %d is %d\n\n",

3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7,


maximum( 6.6, 8.8, 7.7 ));

Output

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

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 void add(T t) { this.t


= t;

public T get() {
return t;

public static void main(String[] args) { Box<Integer> integerBox =


new Box<Integer>(); Box<String> stringBox = new
Box<String>();

integerBox.add(new Integer(10)); stringBox.add(new


String("Hello World"));

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

Syeda Sumaiya Afreen Page 41

You might also like