Unit 5 Notes
Unit 5 Notes
Parsing is the division of text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning
StringTokenizer, specify an input string and a string that contains delimiters
Delimiters are characters that separate tokens.
The default set of delimiters consists of the whitespace characters: space, tab, newline, and
carriage return.
StringTokenizer parse “key=value” pairs Consecutive sets of “key=value” pairs are
separated by a semicolon.
Constructors
StringTokenizer(String str, String delimiters, boolean delimAsToken)
str is the string that will be tokenized
delimiters is a string that specifies the delimiters
delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed
Methods
hasMoreTokens( )-returns true while there are more tokens to be extracted
int countTokens( )- Using the current set of delimiters, the method determines the number of tokens
left to be parsed and returns the result.
boolean hasMoreElements( )- Returns true if one or more tokens remain in the string and returns
false if there are none.
Object nextElement( )- Returns the next token as an Object.
Ex:
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=2002";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
BitSet
A BitSet class creates a special type of array that holds bit values.
array can increase in size as needed.
similar to a vector of bits
constructors
BitSet(int size)
Methods
void and(BitSet bitSet)- ANDs the contents of the invoking BitSet object with those
specified by bitSet. The result is placed into the invoking object.
void andNot(BitSet bitSet)- For each 1 bit in bitSet, the corresponding bit in the invoking
BitSet is cleared
int cardinality( )- Returns the number of set bits in the invoking object.
void clear(int startIndex, int endIndex)- Zeros the bits from startIndex to endIndex–1.
boolean equals(Object bitSet)- Returns true if the invoking bit set is equivalent to the one
passed in bitSet. Otherwise, the method returns false.
1
BitSet get(int startIndex, int endIndex)- Returns a BitSet that consists of the bits from
startIndex to endIndex–1. The invoking object is not changed.
boolean isEmpty( )- Returns true if all bits in the invoking object are zero.
void xor(BitSet bitSet)- XORs the contents of the invoking BitSet object with that specified
by bitSet. The result is placed into the invoking object.
Ex:
import java.util.BitSet;
class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
Date class
The Date class encapsulates the current date and time.
The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface.
constructors:
Date( )- Creates a date object representing current date and time.
Date(long millisec)- Creates a date object for the given milliseconds since January 1, 1970, 00:00:00
GMT
2
Methods
Method Description
boolean after(Date date) tests if current date is after the given date.
boolean before(Date date) tests if current date is before the given date.
boolean equals(Date date) compares current date with given date for equality.
static Date from(Instant instant) returns an instance of Date object from Instant date.
void setTime(long time) changes the current date and time to given time.
Ex:
import java.util.Date;
class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970 GMT
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
}
}
output
Mon Apr 22 09:51:52 CDT 2002
Milliseconds since Jan. 1, 1970 GMT = 1019487112894
Calendar Class
JCalendar class 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.
Method Description
public void add(int field, int Adds the specified (signed) amount of time to the given
amount) calendar field.
3
public boolean after (Object when) The method Returns true if the time represented by this
Calendar is after the time represented by when Object.
public boolean before(Object when) The method Returns true if the time represented by this
Calendar is before the time represented by when Object.
public final void clear(int field) Set the given calendar field value and the time value of this
Calendar undefined.
public int compareTo(Calendar The compareTo() method of Calendar class compares the time
anotherCalendar) values (millisecond offsets) between two calendar object.
public int getFirstDayOfWeek() Returns the first day of the week in integer form.
public final Date getTime() This method gets the time value of calendar object and
Returns date.
public long getTimeInMillis() Returns the current time in millisecond. This method has long
as return type.
public TimeZone getTimeZone() This method gets the TimeZone of calendar object and
Returns a TimeZone object.
public int getWeeksInWeekYear() Return total weeks in week year. Weeks in week year is
returned in integer form.
public void set(int field, int value) Sets the specified calendar field by the specified value.
public final void setTime(Date date) Sets the Time of current calendar object. A Date object id
passed as the parameter.
public void setTimeZone(TimeZone Sets the TimeZone with passed TimeZone value (object) as
value) the parameter.
Ex:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
output
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
4
2 years later: Sat May 04 18:47:02 IST 2019
Random
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.Following are the important points about Random −
The class uses a 48-bit seed, which is modified using a linear congruential formula.
The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits.
constructors
Random()
This creates a new random number generator.
Random(long seed)
This creates a new random number generator using a single long seed.
Methods
2 boolean nextBoolean()
This method returns the next pseudorandom, uniformly distributed boolean value from this
random number generator's sequence.
This method generates random bytes and places them into a user-supplied byte array.
4 double nextDouble()
This method returns the next pseudorandom, uniformly distributed double value between 0.0
and 1.0 from this random number generator's sequence.
5 float nextFloat()
This method returns the next pseudorandom, uniformly distributed float value between 0.0
and 1.0 from this random number generator's sequence.
6 double nextGaussian()
This method returns the next pseudorandom, Gaussian ("normally") distributed double value
5
with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
8 int nextInt(int n)
This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive), drawn from this random number generator's sequence.
9 long nextLong()
This method returns the next pseudorandom, uniformly distributed long value from this
random number generator's sequence.
This method sets the seed of this random number generator using a single long seed.
GregorianCalendar
The java.util.GregorianCalendar class is a concrete subclass of Calendar and provides the standard
calendar system used by most of the world.Following are the important points about
GregorianCalendar −
It is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the
support of a single discontinuity, which corresponds by default to the Gregorian date when
the Gregorian calendar was instituted.
The Julian calendar specifies leap years every four years, whereas the Gregorian calendar
omits century years which are not divisible by 400.
Constructors
1
GregorianCalendar()
This constructs a default GregorianCalendar using the current time in the default time zone
with the default locale.
2
GregorianCalendar(int year, int month, int dayOfMonth)
This constructs a GregorianCalendar with the given date set in the default time zone with the
default locale.
6
Methods
This method adds the specified (signed) amount of time to the given calendar field, based on the
calendar's rules.
2 Object clone()
This method converts the time value (millisecond offset from the Epoch) to calendar field
values.
This method converts calendar field values to the time value (millisecond offset from the
Epoch).
This method returns the maximum value that this calendar field could have, taking into
consideration the given time value and the current values of the getFirstDayOfWeek,
getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.
This method returns the minimum value that this calendar field could have, taking into
consideration the given time value and the current values of the getFirstDayOfWeek,
getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.
This method returns the highest minimum value for the given calendar field of this
GregorianCalendar instance.
9 Date getGregorianChange()
7
10 int getLeastMaximum(int field)
This method returns the lowest maximum value for the given calendar field of this
GregorianCalendar instance.
This method returns the maximum value for the given calendar field of this GregorianCalendar
instance.
This method returns the minimum value for the given calendar field of this GregorianCalendar
instance.
13 TimeZone getTimeZone()
14 int hashCode()
This method generates the hash code for this GregorianCalendar object.
This method adds or subtracts (up/down) a single unit of time on the given time field without
changing larger fields.
This method adds a signed amount to the specified calendar field without changing larger fields.
19 setTimeZone(TimeZone zone)
This method sets the time zone with the given time zone value.
Byte Streams
The byte stream classes provide a rich environment for handling byte-oriented I/O.
A byte stream can be used with any type of object, including binary data.
This versatility makes byte streams important to many types of programs.
InputStream
InputStream is an abstract class that defines Java’s model of streaming byte input. All of the
methods in this class will throw an IOException on error conditions.
8
Methods
Method Description
1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.
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.
Methods
Method Description
FileInputStream
9
Methods
int available() It is used to return the estimated number of bytes that can be read from
the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input stream.
off, int len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel It is used to return the unique FileChannel object associated with the file
getChannel() input stream.
protected void It is used to ensure that the close method is call when there is no more
finalize() reference to the file input stream.
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
FileOutputStream Class
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
10
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
ByteArrayInputStream
Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as
stream. the data is read from a byte array.
Constructors
Constructor Description
ByteArrayInputStream(byte[] ary, int Creates a new byte array input stream which
offset, int len) uses ary as its buffer array that can read up to
specified len bytes of data from an array.
11
Methods
Methods Description
int available() It is used to return the number of remaining bytes that can be
read from the input stream.
int read() It is used to read the next byte of data from the input stream.
boolean markSupported() It is used to test the input stream for mark and reset method.
long skip(long x) It is used to skip the x bytes of input from the input stream.
void mark(int It is used to set the current marked position in the stream.
readAheadLimit)
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.
Constructors
Constructor Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if necessary.
12
Methods
Method Description
void write(byte[] b, int off, It is used for writing len bytes from specified byte array starting
int len from the offset off to the byte array output stream.
void writeTo(OutputStream It is used for writing the complete content of a byte array output
out) stream to the specified output stream.
void reset() It is used to reset the count field of a byte array output stream to zero
value.
FilterInputStream Class
Java FilterInputStream class implements the InputStream. It contains different sub classes
as BufferedInputStream, DataInputStream for providing additional functionality.
Methods
Method Description
int available() It is used to return an estimate number of bytes that can be read from
the input stream.
int read() It is used to read the next byte of data from the input stream.
int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream.
long skip(long n) It is used to skip over and discards n bytes of data from the input
stream.
boolean It is used to test if the input stream support mark and reset method.
markSupported()
void mark(int It is used to mark the current position in the input stream.
readlimit)
13
Ex:
import java.io.*;
int k =0;
while((k=filter.read())!=-1){
System.out.print((char)k);
file.close();
filter.close();
FilterOutputStream Class
Java FilterOutputStream class implements the OutputStream class. It provides different sub classes
such as BufferedOutputStream and DataOutputStream to provide additional functionality.
Methods
Method Description
void write(int b) It is used to write the specified byte to the output stream.
void write(byte[] ary) It is used to write ary.length byte to the output stream.
void write(byte[] b, int off, int It is used to write len bytes from the offset off to the output
len) stream.
14
void flush() It is used to flushes the output stream.
Ex:
import java.io.*;
byte b[]=s.getBytes();
filter.write(b);
filter.flush();
filter.close();
file.close();
System.out.println("Success...");
BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
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.
15
Constructors
Constructor Description
Methods
Method Description
int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input
stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified
off, int ln) byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
void reset() It repositions the stream at a position the mark method was last called on
this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
16
boolean It tests for the input stream to support the mark and reset methods.
markSupported()
Ex:
import java.io.*;
try{
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
Constructors
Constructor Description
17
stream.
Methods
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int It write the bytes from the specified byte-input stream into a
off, int len) specified byte array, starting with the given offset
Ex:
import java.io.*;
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
18
fout.close();
System.out.println("success");
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.
Methods
It is used to test if the input stream support mark and reset method.
Method Description
int available() It is used to return the number of bytes that can be read from the input
stream.
int read() It is used to read the next byte of data from the input stream.
boolean
markSupported()
void mark(int readlimit) It is used to mark the current position in the input stream.
void unread(int b) It is used to pushes back the byte by copying it to the pushback buffer.
void unread(byte[] b) It is used to pushes back the array of byte by copying it to the
pushback buffer.
Ex:
19
import java.io.*;
int i;
if(i == '#') {
int j;
System.out.print("**");
}else {
push.unread(j);
System.out.print((char)i);
}else {
System.out.print((char)i);
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. methods
don't throw IOException.
20
Method Description
void println(boolean b) It prints the specified boolean value and terminates the line.
void println(char c) It prints the specified char value and terminates the line.
Ex:
import java.io.FileOutputStream;
import java.io.PrintStream;
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
21
fout.close();
System.out.println("Success?");
Character stream
Reader
Reader is an abstract class for reading character streams.
Constructor
Methods
22
Int read(char[] cbuf) It reads characters into an array.
abstract int read(char[] cbuf, int off, It reads characters into a portion of an
int len) array.
Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Writer
Constructor
Constructor Description
23
Writer() It creates a new character-stream writer whose critical sections will
synchronize on the writer itself.
Methods
Method Description
Ex:
import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
24
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
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.
Methods
Method Description
int read(char[] b, int off, It is used to read characters into the portion of an array.
int len)
boolean markSupported() It is used to tell whether the stream supports mark() operation.
Ex:
import java.io.CharArrayReader;
25
public class CharArrayExample{
int k = 0;
char ch = (char) k;
System.out.println(k);
Output
j : 106
a : 97
v : 118
a : 97
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.
Methods
Method Description
26
String toString() It is used for converting an input data to a string.
void write(char[] c, int off, int len) It is used to write a character to the buffer.
void write(String str, int off, int len) It is used to write a portion of string to the buffer.
Ex:
import java.io.CharArrayWriter;
import java.io.FileWriter;
out.write("Welcome to java");
27
FileWriter f1=new FileWriter("D:\\a.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
Output
a.txt:
Welcome to java
b.txt:
Welcome to java
c.txt:
Welcome to java
d.txt:
Welcome to java
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
Constructors
28
Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't
file) exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.
Methods
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
Ex:
import java.io.FileReader;
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
29
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.No need to convert string into byte array because it provides
method to write string directly.
Constructors
Constructor Description
FileWriter(File file) Creates a new file. It gets file name in File object.
Methods
Method Description
Ex:
import java.io.FileWriter;
try{
30
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to java.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used
to read data line by line by readLine() method. It makes the performance fast.
Constructors
Constructor Description
Methods
Method Description
int read(char[] cbuf, int It is used for reading characters into a portion of an array.
off, int len)
boolean markSupported() It is used to test the input stream support for the mark and
reset method.
31
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.
void reset() It repositions the stream at a position the mark method was
last called on this input stream.
void close() It closes the input stream and releases any of the system
resources associated with the stream.
Ex:
import java.io.*;
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
br.close();
fr.close();
32
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.
Constructors
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the
default size for an output buffer.
BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses the
size) specified size for an output buffer.
Methods
Method Description
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
Ex:
import java.io.*;
33
FileWriter writer = new FileWriter("D:\\testout.txt");
buffer.write("Welcome to java.");
buffer.close();
System.out.println("Success");
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.
Methods
Method Description
boolean markSupported() It is used to tell whether the stream supports mark() operation.
void unread (int c) It is used to pushes back the character by copying it to the
pushback buffer.
void unread (char[] cbuf) It is used to pushes back an array of character by copying it to
the pushback buffer.
34
void close() It is used to close the stream.
import java.io.*;
int i;
if(i == '-') {
int j;
System.out.print("#*");
}else {
System.out.print((char)i);
}else {
System.out.print((char)i);
PrintWriter class
Java PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.
Methods
35
Method Description
boolean checkError() It is used to flushes the stream and check its error
state.
import java.io.File;
36
import java.io.PrintWriter;
writer.flush();
writer.close();
writer1.flush();
writer1.close();
Stream tokenizer
Java.io.StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens
to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted strings, and
various comment styles.
Class declaration
Field
37
static int TT_NUMBER − A constant indicating that a number token has been read.
static int TT_WORD − A constant indicating that a word token has been read.
int ttype − After a call to the nextToken method, this field contains the type of the token just
read.
Class constructors
StreamTokenizer(Reader r)
This creates a tokenizer that parses the given character stream.
Class methods
int nextToken()
This method parses the next token from the input stream of this tokenizer.
Ex:
import java.io.*;
FileNotFoundException, IOException
38
{
token.commentChar('a');
int t;
switch (t)
case StreamTokenizer.TT_NUMBER:
break;
case StreamTokenizer.TT_WORD:
break;
39
Number : 2.0
Number : 3.0
Word : good morning
Word : Hello
Serialization
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type and the
types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that
is, the type information and bytes that represent the object and its data can be used to recreate the
object in memory.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods
for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one
method in particular stands out −
The ObjectInputStream class contains the following method for deserializing an object −
This method retrieves the next Object out of the stream and deserializes it. The return value is Object,
so you will need to cast it to its appropriate data type.
Example
Notice that for a class to be serialized successfully, two conditions must be met −
40
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the file a
.ser extension.
Example
import java.io.*;
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
out.writeObject(e);
out.close();
fileOut.close();
41
} catch (IOException i) {
i.printStackTrace();
Deserializing an Object
Example
import java.io.*;
Employee e = null;
try {
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
c.printStackTrace();
return;
System.out.println("Deserialized Employee...");
42
System.out.println("Name: " + e.name);
Output
Deserialized Employee...
SSN: 0
Number:101
The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()
method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the
class. If the JVM can't find a class during the deserialization of an object, it throws a
ClassNotFoundException.
Generic
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 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.
Example
43
public class Box<T> {
private T t;
public T get() {
return t;
}
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
Output
Integer Value :10
String Value :Hello World
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).
44
Ex:
public class GenericMethodTest {
System.out.println();
Integer[] intArray = { 1, 2, 3, 4, 5 };
Output
45
12345
HELLO
Generic Interfaces
Generics also work with interfaces. Generic interfaces are specified just like generic classes. For
example :
The MyInterface is a generic interface that declares the method called myMethod( ). In general, a
generic interface is declared in the same way as is a generic class. In this case, the type parameter is T.
Next, MyInterface is implemented by MyClass. Myclass is a non generic class. if a class implements
a specific type of generic interface, then the implementing class does not need to be generic.
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
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.
46
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract
child) pathname and a child pathname string.
File(String parent, It creates a new File instance from a parent pathname string
String child) and a child pathname string.
File(URI uri) It creates a new File instance by converting the given file:
URI into an abstract pathname.
Boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.
47
Boolean isFile() It tests whether the file denoted by this abstract
pathname is a normal file.
Ex:
import java.io.*;
try {
48
if (file.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
} }
output
49