You are on page 1of 19

[UNIT-3 Lang And I/O Packages]

Java. lang package - Wrapper Classes– Simple type wrappers – Using clone() and the Cloneable
Interface -IO Package - Introduction – Input Stream and Output Stream classes - Data Output Stream
and Data Input Stream classes –FileInput Stream – File Output Stream. - Reader and Writer Classes –
File Reader and File Writer.

Wrapper classes in Java

The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.

Primitive Data Types

Primitive Data Types act as the basic building blocks of data manipulation in Java. They are in-built
or predefined in Java. The eight Primitive Data Types include byte, short, int, long, float, double,
boolean and char. This is predefined by the language.

Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to
use the wrapper classes.

o Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an object,
it will change the original value.

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 1


[UNIT-3 Lang And I/O Packages]

o Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects only. All classes of
the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.

We can also use the valueOf() method to convert primitive types into corresponding objects.

public class Autoboxing{


public static void main(String args[]){

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 2


[UNIT-3 Lang And I/O Packages]

int a=20;
Integer i=Integer.valueOf(a);
Integer j=a;
System.out.println(a+" "+i+" "+j);
}}
OUTPUT: 20 20 20

Unboxing

 The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing.
 To convert objects into the primitive types, we can use the corresponding value methods
(intValue(), doubleValue(), etc., present in each wrapper class.

public class Unboxing{


public static void main(String args[]){
Integer a=new Integer(3);
int i=a.intValue();
int j=a;
System.out.println(a+" "+i+" "+j);
}}
OUTPUT: 3 3 3

Advantages of Wrapper Classes

 In Java, sometimes we might need to use objects instead of primitive data types. For example,
while working with collections.

ArrayList<int> list = new ArrayList<>(); // error

ArrayList<Integer> list = new ArrayList<>(); // runs perfectly

In such cases, wrapper classes help us to use primitive data types as objects.

 We can store the null value in wrapper objects. For example,

int a = null; // generates an error

Integer a = null; // runs perfectly

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 3


[UNIT-3 Lang And I/O Packages]

 Primitive types are more efficient than corresponding objects. Hence, when efficiency is the
requirement, it is always recommended primitive types.

Cloneable in Java

 Cloneable is an interface that is used to create the exact copy of an object. It exists in java.lang
package. A class must implement the Cloneable interface if we want to create the clone of the
class object.
 The clone() method of the Object class is used to create the clone of the object. However, if the
class doesn't support the cloneable interface, then the clone() method generates the
CloneNotSupportedException.
 The syntax of the clone() method is given below.

protected Object clone() throws CloneNotSupportedException

 We can also create a copy of an object by using the new keyword, but it will take a lot of
processing time. Therefore, using the clone() method is efficient for this purpose. Consider the
following example to create a copy of an object using the clone() method.

public class Student implements Cloneable {


int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
Student s = new Student(101, "John");
System.out.println(s.id + " " + s.name);
try {
Student s1 = (Student)s.clone();
System.out.println(s1.id + " " + s1.name);
}catch (Exception e) {

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 4


[UNIT-3 Lang And I/O Packages]

System.out.println(s.toString());
} }}

Output:

101 John

101 John

In the above example, the reference variables s and s1 contains the same values, and the object s is
copied to another object by the clone() method.

I/O Packages:

 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
 We can perform file handling in Java by Java I/O API.
 Java input stream classes can be used to read data from input sources such as keyboard or a file.
Similarly output stream classes can be used to write data on a display or a file again.
 The java.io package consists of input and output streams used to read and write data to files or
other input and output sources.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

There are 3 categories of classes in java.io package:

 Input Streams.
 Output Streams.
 Error Streams.

Java supports three streams that are automatically attached with the console.

1. System.out: Standard output stream


2. System.in: Standard input stream
3. System.err: Standard error stream

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 5


[UNIT-3 Lang And I/O Packages]

Input Streams

As we know input source consists of data that needs to be read in order to extract information from it.
Input Streams help us to read data from the input source. It is an abstract class that provides a
programming interface for all input streams.

Input streams are opened implicitly as soon as it is created. To close the input stream, we use
a close() method on the source object.

SYNTAX: InputStream variable_name = new FileInputStream("Textfile_name");

Output Streams

The output of the executed program has to be stored in a file for further use. Output streams help us to
write data to a output source(may be file). Similarly like input streams output streams are also
abstract classes that provides a programming interface for all output streams.

The output stream is opened as soon as it is created and explicitly closed by using the close() method.

SYNTAX: FileOutputStream variable_name = new FileOutputStream("Textfile_name");

Error Streams

Error streams are the same as output streams. In some ide’s error is displayed in different colors
(other than the color of output color). It gives output on the console the same as output streams.

SYNTAX: try{
// Block of code
}
catch excepted_error(Exception e){
// This will print the Exception on the screen
System.out.println(e);
}

Streams based on data

There are two types of streams based on data:

 Byte Stream: used to read or write byte data.


 Character Stream: used to read or write character data.

Why We Need IO Streams in Java?

In day-to-day work, we do not enter the input into the programs manually. Also, the result of the
program needs to be stored somewhere for further use.

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 6


[UNIT-3 Lang And I/O Packages]

So, IO streams in Java provide us with input and output streams that help us to extract data from the
files and write the data into the files. Normally, we can create, delete, and edit files using Java.io.

In short, all the file manipulation is done using Java IO streams. Java IO streams also handle user
input functionality.

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

OutputStream Hierarchy

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 7


[UNIT-3 Lang And I/O Packages]

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

InputStream Hierarchy

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 8


[UNIT-3 Lang And I/O Packages]

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.

import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("E:\\testout.txt");

fout.write(65);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

} }

OUTPUT

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

testout.txt

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 9


[UNIT-3 Lang And I/O Packages]

Example 2: write string

import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("E:\\testout.txt");

String s="Welcome to CSE.";

byte b[]=s.getBytes();//converting string into byte array

fout.write(b);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

} }

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 10


[UNIT-3 Lang And I/O Packages]

The content of a text file testout.txt is set with the data Welcome to CSE.

testout.txt

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

Java FileInputStream class methods

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 11


[UNIT-3 Lang And I/O Packages]

Java FileInputStream example 1: read all characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
} }

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

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 12


[UNIT-3 Lang And I/O Packages]

METHODS

import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "welcome to cse";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} } }

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 13


[UNIT-3 Lang And I/O Packages]

Java 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 class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader,
PipedReader, StringReader.

import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("output.txt");
int data = reader.read();

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 14


[UNIT-3 Lang And I/O Packages]

while (data != -1) {


System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
} } }

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

Methods of FileWriter class

Java FileWriter Example

import java.io.FileWriter;

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 15


[UNIT-3 Lang And I/O Packages]

public class FileWriterExample {


public static void main(String args[]){
try{
FileWriter fw=new FileWriter("E:\\testout.txt");
fw.write("Welcome to CSE Department.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
} }

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.

Methods of FileReader class

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 16


[UNIT-3 Lang And I/O Packages]

import java.io.FileReader;

public class FileReaderExample {

public static void main(String args[])throws Exception{

FileReader fr=new FileReader("D:\\testout.txt");

int i;

while((i=fr.read())!=-1)

System.out.print((char)i);

fr.close();

} }

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

This class works machine-independent, allowing an application to read primitive data from an
input stream. These generally use the data output stream, which can be used after the input stream
to read the data.

Declaration:

public class DataInputStream extends FilterInputStream implements DataInput

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 17


[UNIT-3 Lang And I/O Packages]

Java DataOutputStream Class

This class works on the principle of allowing an application to write primitive data types to the
output stream in a machine-independent way. These can be read by the input stream written by the
data output stream.

Declaration:

public class DataOutputStream extends FilterInputStream implements DataOutput

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 18


[UNIT-3 Lang And I/O Packages]

import java.io.*;

public class DataStream {

public static void main(String[] args) throws IOException {

FileOutputStream file = new FileOutputStream("E:\\testout.txt");

DataOutputStream data = new DataOutputStream(file);

data.writeInt(5);

data.writeDouble(65.55);

data.writeChar('t');

FileInputStream file1 = new FileInputStream("E:\\testout.txt");

DataInputStream data1 = new DataInputStream(file1);

int a=data1.readInt();

double b=data1.readDouble();

char c=data1.readChar();

System.out.println("Values-->" +a+ "\n" +b+ "\n" +c);

} }

LALITHA R, AP/CSE, SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY Page 19

You might also like