Osmania University Matrusri Engineering College Hyderabad UNIT-3 JAVA NOTES WITH BACKGROUND
Osmania University Matrusri Engineering College Hyderabad UNIT-3 JAVA NOTES WITH BACKGROUND
UNIT-III
Collections: Overview of Java Collection frame work, commonly used Collection classes – Array
List, Linked List, Hash Set, Tree Set, Collection Interfaces – Collection, List, Set. Accessing
Collection via iterator, working with Map. Legacy classes and interfaces – Vector, Hashtable, Stack,
Dictionary, Enumeration interface.
Other Utility classes: String Tokenizer, Date, Calendar, Gregorian Calendar, ScannerJava
Input/Output:exploring java.io, Java I/O classes and interfaces, File, Stream classes, byte
stream,character stream, serialization.
Course Objective: To understand fundamentals of object-oriented programming in Java which
includes defining classes, invoking methods, difference between applet and applicationprograms, using
class libraries
Course Outcome Develop the ability to solve real-world problems through software development
in high-level programming language using Large APIs of Java as well as the Java standard class
library.
The java.util package contains several classes to group/collect homogeneous and heterogeneous
objects without size limitations. These classes are used called Java collection framework classes
Basically, Java collection framework classes are Java data structures. These classes internally use
several standard data structures and algorithms such as a growable array, vector, stack, queue, linked
list, doubly linked list, hash table, balance tree. All collection object size is automatically incremental
and decremental.
Java Collection Framework classes are:-
Growable in nature i.e. based on our requirement we can increase or decrease the size.
They can hold both homogeneous & heterogeneous objects.
Every collection class is implemented based on some standard data structure. Hence for every
requirement pre-defined method support is available.
Java collection class is used exclusively with static methods that operate on or return collections. It
inherits Object class.
The important points about Java Collections class are:
Java Collection class supports the polymorphic algorithms that operate on collections.
Java Collection class throws a NullPointerException if the collections or class objects provided
to them are null.
List of Collection Classes:
1) Array List
2) Linked List
3) Vector
4) Stack
5) Priority Queue
6) Array Deque
7) Hash Set
8) Tree Set
9) LinkedHashSet
10) SortedSet
1
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
ARRAY LIST : ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is needed.
class GFG {
// Main Method
public static void main(String[] args)
{ // Declaring the ArrayList with
// initial size n
ArrayList<Integer> al = new ArrayList<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
al.add(i);
// Printing elements
System.out.println(al);
// Remove element at index 3
al.remove(3);
// Displaying the ArrayList
// after deletion
System.out.println(al);
// Printing elements one by one
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
}}
LINKED LIST: LinkedList class is an implementation of the LinkedList data structure which is a linear
data structure where the elements are not stored in contiguous locations and every element is a separate
object with a data part and address part. The elements are linked using pointers and addresses.
// working of LinkedList
import java.io.*;
import java.util.*;
class GFG { // Main Method
public static void main(String[] args)
{ // Declaring the LinkedList
LinkedList<Integer> ll = new LinkedList<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
ll.add(i);
// Printing elements
System.out.println(ll);
// Remove element at index 3
ll.remove(3);
// Displaying the List
// after deletion
System.out.println(ll);
2
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
// Printing elements one by one
for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}}
HASH SET: The HashSet class is an inherent implementation of the hash table data structure. The
objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are
inserted based on their hashcode. This class also allows the insertion of NULL elements.
// working of a HashSet
import java.util.*;
public class HashSetDemo {
// Main Method
public static void main(String args[])
{ // Creating HashSet and
// adding elements
HashSet<String> hs = new HashSet<String>();
hs.add("Geeks");
hs.add("For");
hs.add("Geeks");
hs.add("Is");
hs.add("Very helpful");
// Traversing elements
Iterator<String> itr = hs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
} } }
TREE SET: The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a
set using their natural ordering whether or not an explicit comparator is provided. This must be
consistent with equals if it is to correctly implement the Set interface.
// working of a TreeSet
import java.util.*;
public class TreeSetDemo {
// Main Method
public static void main(String args[])
{ // Creating TreeSet and
// adding elements
TreeSet<String> ts = new TreeSet<String>();
ts.add("Geeks");
ts.add("For");
ts.add("Geeks");
ts.add("Is");
ts.add("Very helpful");
3
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
// Traversing elements
Iterator<String> itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next()); } } }
COLLECTION INTERFACES
1. Collection interface
2. List interface
3. Set interface
4. SortedSet interface
5. Map interface
6. Map.Entry Interface
7. SortedMap interface
8. Queue interface
9. Deque interface
10. Enumeration interface
LIST INTERFACE: A List represents an ordered or sequenced group of elements. It may contain
duplicate elements. It extends the collection interface.
// Java program to Demonstrate List Interface
import java.util.*;
class GFG {
public static void main(String[] args)
{ // Creating an object of List interface
// implemented by the ArrayList class
List<Integer> l1 = new ArrayList<Integer>();
// Adding elements to object of List interface
// Custom inputs
l1.add(0, 1);
l1.add(1, 2);
// Print the elements inside the object
System.out.println(l1);
// Now creating another object of the List
// interface implemented ArrayList class
// Declaring object of integer type
List<Integer> l2 = new ArrayList<Integer>();
// Again adding elements to object of List interface
// Custom inputs
l2.add(1);
l2.add(2);
l2.add(3);
// Will add list l2 from 1 index
4
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
l1.addAll(1, l2);
System.out.println(l1);
// Removes element from index 1
l1.remove(1);
// Printing the updated List 1
System.out.println(l1);
// Prints element at index 3 in list 1
// using get() method
System.out.println(l1.get(3));
// Replace 0th element with 5
// in List 1
l1.set(0, 5);
// Again printing the updated List 1
System.out.println(l1); }}
SET INTERFACE: The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited.Set also adds a stronger contract on the behavior of the
equals and hashCode operations, allowing Set instances to be compared meaningfully even if their
implementation types differ.
// Java program to Demonstrate Set Interface
import java.util.Set;
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Creating a set using the HashSet class
Set<Integer> set1 = new HashSet<>();
// Add elements to the set1
set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);
// Creating another set using the HashSet class
Set<Integer> set2 = new HashSet<>();
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
// Union of two sets
set2.addAll(set1);
System.out.println("Union is: " + set2);
}}
ACCESSING COLLECTION VIA ITERATOR
Java Iterator Interface of java collections allows us to access elements of the collection and is used to
iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a
collection and perform operations on each element. Iterator is a universal iterator as it can be applied to
any Collection object. We can traverse only in the forward direction using iterator. Using ListIterator
which extends Iterator, can traverse in both directions. Both read and remove operations can be
performed by the iterator interface.
// Java program to show the usage of Iterator()
import java.util.Iterator;
5
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
import java.util.LinkedList;
import java.util.List;
public class JavaIteratorExample1 {
public static void main(String[] args)
{ // create a list
List<String> list = new LinkedList<>();
list.add("Welcome");
list.add("to");
list.add("GFG");
System.out.println("The list is given as : "+ list);
// get the iterator on the list
Iterator<String> itr = list.iterator();
// Returns true if there are more number of
// elements.
while (itr.hasNext()) {
// Returns the next element.
System.out.println(itr.next());
}
// Removes the last element.
itr.remove();
System.out.println(
"After the remove() method is called : "+ list);
}}
WORKING WITH MAP
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as
an entry. A Map contains unique keys.A Map is useful if you have to search, update or delete elements
on the basis of a key. There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, LinkedHashMap, and TreeMap.
6
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
//Demonstration of Map
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}}}
LEGACY CLASSES AND INTERFACES
It only defined several classes and interfaces that provide methods for storing objects. When
Collections framework were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes. All the legacy classes are
synchronized. The java.util package defines the following legacy classes:
List of Legacy Classes:
HashTable
Stack
Dictionary
Properties
Vector
There is only one Legacy interface that is Enumeration interface.
VECTOR: Vector is a special type of ArrayList that defines a dynamic array. ArrayList is not
synchronized while vector is synchronized. The vector class has several legacy methods that are not
present in the collection framework.
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{ Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{ System.out.println(data.nextElement()); } } }
7
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
HASHTABLE: The Hashtable class is similar to HashMap. It also contains the data into key/value
pairs. It doesn't allow to enter any null key and value because it is synchronized. Just like Vector,
Hashtable also has the following four constructors.
import java.util.*;
class HashtableExample
{ public static void main(String args[])
{ Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
student.put(new Integer(103), "Aria");
student.put(new Integer(104), "Ally");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{ Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
} } }
STACK: Stack class extends Vector class, which follows the LIFO(LAST IN FIRST OUT) principal
for its elements. The stack implementation has only one default constructor, i.e., Stack()
import java.util.*;
class StackExample {
public static void main(String args[]) {
Stack stack = new Stack();
stack.push("Emma");
stack.push("Adele");
stack.push("Aria");
stack.push("Ally");
stack.push("Paul");
Enumeration enum1 = stack.elements();
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
stack.pop();
stack.pop();
stack.pop();
System.out.println("\nAfter removing three elements from stack");
Enumeration enum2 = stack.elements();
while(enum2.hasMoreElements())
System.out.print(enum2.nextElement()+" "); }}
DICTIONARY: The Dictionary class operates much like Map and represents the key/value storage
repository. The Dictionary class is an abstract class that stores the data into the key/value pair. We
can define the dictionary as a list of key/value pairs.
8
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
import java.util.*;
public class DictionaryExample
{ public static void main(String[] args)
{ // Initializing Dictionary object
Dictionary student = new Hashtable();
// Using put() method to add elements
student.put("101", "Emma");
student.put("102", "Adele");
student.put("103", "Aria");
student.put("104", "Ally");
student.put("105", "Paul");
// Using the remove() method
System.out.println("\nDelete : " + student.remove("103"));
System.out.println("The name of the deleted student : " +
student.get("123"));
System.out.println("\nThe size of the student dictionary is : " +
student.size());
} }
ENUMERATION INTERFACE
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the
elements in a collection of objects.This legacy interface has been superceded by Iterator. Although not
deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods
defined by the legacy classes such as Vector and Properties, is used by several other API classes, and
is currently in widespread use in application code.
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement()); } } }
STRING TOKENIZER
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a
String. It is a legacy class of Java. It doesn't provide the facility to differentiate numbers, quoted
strings, identifiers etc. In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.
9
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is Matrusri"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
} } }
DATE
The class Date represents a specific instant in time, with millisecond precision. The Date class of
java.util package implements Serializable, Cloneable and Comparable interface. It provides
constructors and methods to deal with date and time with java.
Constructors:
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min, int sec)
Date(String s)
// Java program to demonstrate Date
import java.util.*;
public class Main
{ public static void main(String[] args)
{ Date d1 = new Date();
System.out.println("Current date is " + d1);
}}
CALENDAR AND GREGORIAN CALENDAR
Calendar class in Java is an abstract class that provides methods for converting date between a specific
instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object
class and implements the Comparable, Serializable, Cloneable interfaces.As it is an Abstract class, so
we cannot use a constructor to create an instance. Instead, we will have to use the static method
Calendar.getInstance() to instantiate and implement a sub-class.
Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone
with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale aLocale)
import java.util.*;
public class Calendar1 {
public static void main(String args[])
{ Calendar c = Calendar.getInstance();
System.out.println("The Current Date is:" + c.getTime());
}}
SCANNER JAVA INPUT/OUTPUT
Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient
if you want an input method for scenarios where time is a constraint like in competitive programming.
To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream. We may pass an object of class File if we want to read
input from a file.
10
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
To read strings, we use nextLine().
To read a single character, we use next().charAt(0). next() function returns the next token/word
in the input as a string and charAt(0) function returns the first character in that string.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
} }
EXPLORING JAVA.IO
Java programming language comes with a variety of APIs that helps the developers to code more
efficiently. One of those APIs is Java IO API. Java IO API helps the users to read and write data. In
simple words, we can say that the Java IO helps the users to take the input and produce output based
on that input. Almost every application or code requires some input and output produced based on that
input.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 operations 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 I/O CLASSES AND INTERFACES
The following listing of classes is provided by the java.io package shown in the table:
Class Description
BufferedInputStream It used for creating an internal buffer array. It supports the mark and
reset methods.
BufferedOutputStream This class used for writes byte to output stream. It implements a
buffered output stream.
BufferedReader This class provides read text from character input stream and buffering
characters. It also reads characters, arrays and lines.
BufferedWriter This class provides write text from character output stream and
buffering characters. It also writes characters, arrays and lines.
ByteArrayInputStream It contains the internal buffer and read data from the stream.
ByteArrayOutputStream This class used for data is written into byte array. This is implement in
output stream class.
CharArrayReader It used for char input stream and implements a character buffer.
CharArrayWriter This class also implements a character buffer and it uses an writer.
DataInputStream This class reads the primitive data types from the input stream in a
machine format.
DataOutputStream This class writes the primitive data types from the output stream in
machine format.
File This class shows a file and directory pathnames.
FileInputStream It contains the input byte from a file and implements an input stream.
FileOutputStream It uses for writing data to a file and also implements an output stream.
FilePermission It provides the permission to access a file or directory.
FileReader This class used for reading characters file.
FileWriter This class used for writing characters files.
FilterInputStream This class overrides all methods of InputStream and contains some
other input stream.
11
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
FilterOutputStream This class overrides all methods of OutputStream and contains some
other output stream.
FilterReader It reads the data from the filtered character stream.
FilterWriter It writes data from the filtered character stream.
InputStream This class represents an input stream of bytes.
InputStreamReader It reads bytes and decodes them into characters.
LineNumberReader This class has a line numbers
ObjectInputStream This class used for recover the object to serialize previously.
ObjectInputStream.GetField This class access to president fields read form input stream.
ObjectOutputStream This class used for write the primitive data types and also write the
object to read by the ObjectInputStream.
ObjectOutputStream.GetField This class access to president fields write in to ObjectOutput.
ObjectStreamClass Serialization's descriptor for classes.
ObjectStreamField This class describes the serializable field.
OutputStream This class represents an output stream of bytes.
OutputStreamWriter It writes bytes and decodes them into characters.
PipedInputStream In this class the data bytes are written into piped output stream. This
class also connected into a piped output stream.
PipedOutputStream This class also communicates the piped input stream into piped output
stream. It creates communication between both.
PipedReader It is a piped character-input stream.
PipedWriter It is a piped character-output stream.
PrintStream This class adds the functionality of another output stream.
PrintWriter This class adds the functionality of another input stream.
PushbackInputStream It also include the another function of input stream. Such as: "push
back" or "unread" one byte.
PushbackReader This is a character stream reader and reads the data push back into the
stream.
RandomAccessFile It supports both reading and writing to a random access file.
Reader It used for reading character stream.
SequenceInputStream It represents the logical concatenation of other input stream.
SerializablePermission This is a serializable permission class.
StreamTokenizer It takes an input stream and parse it into "tokens" . The token to be
allowed at the read time.
StringReader This is a character string class. It has character read source.
StringWriter This is also a character string class. It uses to shows the output in the
buffer.
Writer It uses for writing to character stream.
The following Interfaces are provided by the java.io package shown in the table:
Interface Description
DataInput This interface can be used for reading byte stream and reconstructing the java
primitive data types.
DataOutput This interface can be used for writing the byte stream and converting data from
the java primitive data types.
ObjectInput This interface used for reading of objects and it extends the DataInput
interface.
ObjectOutput This interface used for writing of objects and it extends the DataOutputinterface.
ObjectStreamConstants This interface used for Constants writing into Serialization Objects Stream.
Serializable This interface implementing in the java.io.Serializable interface.
12
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
FILE
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io
package. The File class can be used by creating an object of the class and then specifying the name of
the file.File Handling is an integral part of any programming language as file handling enables us to
store the output of any particular program in a file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.
// Importing File Class
import java.io.File;
class GFG {
public static void main(String[] args)
{
// File name specified
File obj = new File("myfile.txt");
System.out.println("File Created!");
}}
Copy contents of one file to another
import java.io.*; import java.io.*;
public class CopyFile
{ public static void main(String args[]) throws IOException
{ FileInputStream in = null; FileOutputStream out = null;
try{ in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt"); int c;
while ((c = in.read()) != -1)
{ out.write(c);
}}finally
{ if (in != null)
{ in.close();
} if (out != null)
{ out.close();}}}}
STREAM CLASSES
A stream is a sequence of objects that supports various methods which can be pipelined to produce the
desired result.The features of Java stream are
A stream is not a data structure instead it takes input from the Collections, Arrays or I/O
channels.
Streams don’t change the original data structure, they only provide the result as per the
pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various
intermediate operations can be pipelined. Terminal operations mark the end of the stream and
return the result.
//a simple program to demonstrate the use of stream in java
import java.util.*;
import java.util.stream.*;
class Demo
{public static void main(String args[])
{ // create a list of integers
List<Integer> number = Arrays.asList(2,3,4,5);
// demonstration of map method
List<Integer> square = number.stream().map(x -> x*x).collect(Collectors.toList());
System.out.println(square);
13
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
// create a list of String
List<String> names=Arrays.asList("Reflection","Collection","Stream");
// demonstration of filter method
List<String> result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> show=names.stream().sorted().collect(Collectors.toList());
System.out.println(show);
// create a list of integers
List<Integer> numbers = Arrays.asList(2,3,4,5,2);
// collect method returns a set
Set<Integer> squareSet=numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
number.stream().map(x->x*x).forEach(y->System.out.println(y));
// demonstration of reduce method
int even=number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
System.out.println(even);}}
BYTE STREAM
ByteStream classes are used to read bytes from the input stream and write bytes to the output stream.
In other words, we can say that ByteStream classes read/write the data of 8-bits. We can store video,
audio, characters, etc., by using ByteStream classes. These classes are part of the java.io package.
The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream.
These classes are abstract and the super classes of all the Input/Output stream classes.
SNO CLASS DESCRIPTION
1 BufferedInputStream This class provides methods to read bytes from the byte array.
2 ByteArrayInputStream This class provides methods to read Java primitive data types.
3 DataInputStream This class provides methods to read bytes from a file.
4 FileInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.
5 FilterInputStream This class provides methods to read objects.
6 ObjectInputStream This class provides methods to read from a piped output stream to
which the piped input stream must be connected.
7 PipedInputStream This class provides methods to connect multiple Input Stream and
read data from them.
8 SequenceInputStream This class provides methods to connect multiple Input Stream and
read data from them.
//Program to demonstrate Byte Stream
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
14
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
public class InputOutputStreamExample {
public static void main(String[] args) throws IOException {
byte content[] = "Jtp is the best website to learn new technologies".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content);
File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content); }}
CHARACTER STREAM
The java.io package provides CharacterStream classes to overcome the limitations of ByteStream
classes, which can only handle the 8-bit bytes and is not compatible to work directly with the
Unicode characters. CharacterStream classes are used to work with 16-bit Unicode characters. They
can perform operations on characters, char arrays and Strings.
import java.io.*;
public class PrintWriterDemo
{ public static void main(String args[]) throws Exception
{ String data = "This is a line of text inside the file.";
try { PrintWriter output = new PrintWriter("output.txt");
output.print(data);
output.close();
System.out.println("Success?");
} catch (Exception e) {
e.getStackTrace(); } } }
SERIALIZATION
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is
the reverse process where the byte stream is used to recreate the actual Java object in memory. This
mechanism is used to persist the object.The byte stream created is platform independent. So, the object
serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
15
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
16