SlideShare a Scribd company logo
Stream
Java programs perform I/O through streams.
A stream is an abstraction that either produces or
consumes information.
A stream is linked to a physical device by the Java I/O
system.
Java defines two types of streams
1.Byte Streams
2.Character Streams
Byte streams provide a convenient means for
handling input and output of bytes.
Byte streams are used to read and write binary data.
Character streams provide a convenient means for
handling input and output of characters.
Character streams use Unicode.
Stream Classes
Stream-based I/O is built upon four abstract classes.
They are
1.InputStream:
2.OutputStream:
3.Reader:
4.Writer.
InputStream and OutputStream are designed for byte
streams.
Reader and Writer are designed for character
streams.
InputStream class
InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
methods of InputStream
InputStream class Hierarchy
OutputStream class
OutputStream class is an abstract class. It is the super
class of all classes representing an output stream of
bytes.
methods of OutputStream
OutputStream class Hierarchy
FileInputStream
FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data such as
image data, audio, video etc.
Its constructors
FileInputStream(String filepath)
FileInputStream(File fileObj)
Example
FileInputStream f0 = new FileInputStream("abc.txt")
File f = new File(“abc.txt");
FileInputStream f1 = new FileInputStream(f);
Example
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream(“input.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileOutputStream
Java FileOutputStream is an output stream used for
writing data to a file.
Its constructors
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("output.txt");
String s="Welcome to CMRCET.";
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);
}
}
}
File Operations Reading, Writing and Closing
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();
}
}
}
}
Reader class
Reader is an abstract class for reading character
streams.
The methods that a subclass must implement are
1.read(char[], int, int)
2.close().
Reader class Hierarchy
Writer class
It is an abstract class for writing to character streams.
The methods that a subclass must implement are
write(char[], int, int)
flush()
close()
Writer class Hierarchy
FileReader Class
FileReader class is used to read data from the file.
It returns data in byte format like FileInputStream class
Its constructors
FileReader(String filePath)
FileReader(File fileObj)
Example
import java.io.FileReader;
public class FileReaderExample
{
public static void main(String args[])throws Exceptio
n{
FileReader fr=new FileReader("test.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
FileWriter class
FileWriter class is used to write character-
oriented data to a file.
Its constructors
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
Methods of FileWriter class
1. void write(String text):It is used to write the string
into FileWriter.
2. void write(char c):It is used to write the char into
FileWriter.
3. void write(char[] c):It is used to write char array
into FileWriter.
4. void flush():It is used to flushes the data of
FileWriter.
5. void close():It is used to close the FileWriter.
Example
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter(“out.txt");
fw.write("Welcome to CMRCET");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
ArrayList Class
1.The underlined data structure is Resizable Array or
Grow able Array.
2.Duplicates are allowed.
3.Insertion order is preserved.
4.Heterogeneous objects are allowed.
5.Null insertion is possible.
ArrayList Constructors
1.ArrayList al = new ArrayList()
Creates an empty Array list object with default
capacity 10.
Once ArrayList reaches its max capacity a new Array
List will be created with
new capacity=(currentcapacity*3/2)+1.
2. ArrayList al = new ArrayList(int initialCapacity);
3. ArrayList al=new ArrayList(Collection c)
Example
Import java.util.*;
Class ArryListDemo
{
Pubilc static void main(String arg[])
{
ArrayList l=new ArrayList();
l.add(“a”);
l.add(10);
l.add(“a”);
l.add(null);
Sysytem.out.println(l);
l.remove(2);
System.out.println(l);
l.add(“2”,”m”);
l.add(“n”);
System.out.println(l);
}
}
Usually we can use collections to hold and transfer
Objects from on place to other place, to provide
support for this requirement every Collection
already implements Serializable and Cloneable
interfaces.
ArrayList class implements RandomAccess interface
so that we can access any Random element with
the same speed.
Hence if our frequent operation is retrieval operation
then ArrayList is the best choice.
ArrayList is the worst choice if our frequent operation
is insertion or deletion in the middle(Because
several shift operation are required).
Vector class
1. The underlying Data structure for the vcetor is
resizable array or growable arrray.
2. Duplicates are allowed.
3. Insertion order is preserved.
4. Heterogeneous objects are allowed.
5. Null insertion is possible.
6. Vector class implements Serializable, Cloneable
and RandomAccess Interfaces.
7. Most of the methods presnt in vector are
synchronized. Hence vector object is Thread–safe.
8. Best choice if the frequent operation is retrieval.
Vector specific methods
For adding objects
Add(Object o); [from Collection -List(l)]
Add(int index, Object o); [from List]
addElement(Object o) [from Vector]
For removing Objects
remove(Object o) [from Collection]
removeElement(Object o) [from Vector]
remove(int index) [from List]
removeElementAt(int index) [from Vector]
Clear() [from Collection]
removeElementAt()[from Vector]
For Accessing Elements
Object get(int index) [from Collection]
Object elementAt(int index) [from Vector]
Object firstElement() [from Vector]
Object lastElement() [from Vector]
Other Methods
int size();// currently how many objects are
there
int capacity();// total how many objects we
can accommodate.
Enumeration elements();//to get elements
one by one .
Vector class constructors
1.Vector v= new Vector();
- Create an empty vector object with default capacity
10,once vector reaches its max capacity a new vector
object will be created with new capacity=2* current
capacity.
2. Vector v= new Vector (int initialCapacity)
-creates an empty vector object with specified initial
capacity.
3.Vector v=new Vector(int initial Capacity, int
incremental Capacity)
4.Vector v=new Vector(Collection c);
- Creates an equivalent vector Object for the given
Collection
Example
Import java.util.*;
Class VectorDemo
{
public static void main(String args[])
{
Vector v=new Vector();
System.out.println(v.capacity());
for(int i=0;i<10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement(“A”);
System.out.println(v.capacity());
System.out.println(v);
}
}
Hashtable
1. The underlying data structure for Hashtable is Hashtable
only.
2. Insertion order is not persevered and it is based on hash
code of keys.
3. Duplicate keys are not allowed but values can be duplicated.
4. Heterogeneous objects are allowed for both keys and
values.
5. Null is not allowed for both key and value, other wise we
will get runtime exception saying null pointer exception
6. It implements Serializable and Cloneable interfaces but not
RandomAccess.
7. Every method present in hash table is synchronized and
hence hash table object is Thread-safe.
8. Hash table is best choice if our frequent operation is search
operation.
Constructors
1.Hashtable h=new Hashtable();
- default capacity is 11. and default fillRatio 0.75
2. Hashtable h=new Hashtable(int initial capacity);
3. Hashtable h=new Hashtable(int initial capacity, float
fillRatio)
4. Hashtable h=new Hashtable(map m);
fillRatio
The decision of "When to increase the number of
buckets" is decided by fillRatio (Load Factor).
If fillRatio<(m/n) then Hash table size will be doubled.
Where m=number of entries in a Hashtable
n=Total size of hashtable.
Example
Import java.util.*;
Class HashTableDemo
{
public static void main(String args[])
{
Hashtable h=new Hashtable(); //Hashtable h=new Hashtable(25);
h.put(new Temp(5), “A”);
h.put(new Temp(2), “B”);
h.put(new Temp(6), “C”);
h.put(new Temp(15), “D”);
h.put(new Temp(23), “E”);
h.put(new Temp(16), “F”);
System.out.println(h);
}
}
Class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
Public int hashCode()
{
return i;// return i%9
}
public String toString()
{
return i+””;
}
}
Display order
From Top to bottom
And with in the Bucket the values are taken from right to left
Out put:
{6=C,16=F,5=A,15=D,2=B,23=E}
If Hash code changes
Out put:
{16=F,15=D,6=C,23=E,5=A,2=B}
10
9
8
7
6 6=C
5 5=A,
16=F
4 15=D
3
2 2=B
1 23=E
0
10
9
8
7 16=F
6 6=C,
15=D
5 5=A,
23=E
4
3
2 2=B
1
0
StringTokenizer class
StringTokenizer class in Java is used to break a string
into tokens.
Example
Constructors:
StringTokenizer(String str) :
str is string to be tokenized. Considers default delimiters like
new line, space, tab, carriage return and form feed.
StringTokenizer(String str, String delim) :
delim is set of delimiters that are used to tokenize the given
string.
StringTokenizer(String str, String delim, boolean flag):
The first two parameters have same meaning. The flag
serves following purpose. If the flag is false, delimiter
characters serve to separate tokens. For example, if string
is "hello geeks" and delimiter is " ", then tokens are
"hello" and “VCE". If the flag is true, delimiter characters
are considered to be tokens. For example, if string is
"hello VCE" and delimiter is " ", then tokens are "hello", "
" and “VCE".
Methods
boolean hasMoreTokens():checks if there is more
tokens available.
String nextToken():returns the next token from the
StringTokenizer object.
String nextToken(String delim):returns the next
token based on the delimeter.
boolean hasMoreElements(): same as
hasMoreTokens() method.
Object nextElement(): same as nextToken() but its
return type is Object.
int countTokens():returns the total number of tokens.
Example
import java.util.*;
public class NewClass
{
public static void main(String args[])
{
System.out.println("Using Constructor 1 - ");
StringTokenizer st1 = new StringTokenizer("Hello vce How are you", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");
StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("Using Constructor 3 - ");
StringTokenizer st3 =new StringTokenizer("JAVA : Code : String", " :", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
Date class
• The java.util.Date class represents date and
time in java. It provides constructors and
methods to deal with date and time in java.
• The java.util.Date class implements
Serializable, Cloneable and
Comparable<Date> interface. It is inherited by
java.sql.Date, java.sql.Time and
java.sql.Timestamp interfaces.
Constructors
1.Date():Creates a date object representing
current date and time.
2.Date(long milliseconds):Creates a date object
for the given milliseconds since January 1,
1970, 00:00:00 GMT.
Methods
1)boolean after(Date date): tests if current date is after the given
date.
2)boolean before(Date date):tests if current date is before the given
date.
3)Object clone():returns the clone object of current date.
4)int compareTo(Date date):compares current date with given date.
5)boolean equals(Date date):compares current date with given date
for equality.
6)static Date from(Instant instant):returns an instance of Date
object from Instant date.
7)long getTime():returns the time represented by this date object.
8)int hashCode():returns the hash code value for this date object.
9)void setTime(long time):changes the current date and time to
given time.
10)Instant toInstant():converts current date into Instant object.
11)String toString():converts this date into Instant object.
Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2 );
}
}
Out put
Current date is Sat Oct 07 04:14:42 IST 2017
Date represented is Wed Jan 28 02:50:23 IST 1970

More Related Content

PDF
Java Day-6
PPTX
Input/Output Exploring java.io
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PPTX
IOStream.pptx
PPTX
Java I/O
PDF
Programming language JAVA Input output opearations
PPTX
Input & output
PPTX
Input output files in java
Java Day-6
Input/Output Exploring java.io
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
IOStream.pptx
Java I/O
Programming language JAVA Input output opearations
Input & output
Input output files in java

Similar to file handling in object oriented programming through java (20)

PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PPTX
File Input and output.pptx
PPT
Chapter 12 - File Input and Output
PPT
Java căn bản - Chapter12
PPT
9. Input Output in java
PDF
Java IO Stream, the introduction to Streams
PPT
Java Basics
PPT
Java Input Output and File Handling
PPS
Files & IO in Java
PDF
Java IO
PDF
CSE3146-ADV JAVA M2.pdf
DOCX
FileHandling.docx
PPTX
File Handling.pptx
PPTX
Java class 5
PPT
Java stream
PPTX
IO Programming.pptx all informatiyon ppt
PDF
File Handling in Java.pdf
chapter 2(IO and stream)/chapter 2, IO and stream
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
File Input and output.pptx
Chapter 12 - File Input and Output
Java căn bản - Chapter12
9. Input Output in java
Java IO Stream, the introduction to Streams
Java Basics
Java Input Output and File Handling
Files & IO in Java
Java IO
CSE3146-ADV JAVA M2.pdf
FileHandling.docx
File Handling.pptx
Java class 5
Java stream
IO Programming.pptx all informatiyon ppt
File Handling in Java.pdf
Ad

More from Parameshwar Maddela (11)

PPTX
EventHandling in object oriented programming
PPTX
Exception‐Handling in object oriented programming
PPTX
working with interfaces in java programming
PPTX
introduction to object orinted programming through java
PPT
multhi threading concept in oops through java
PDF
Object oriented programming -QuestionBank
PPTX
22H51A6755.pptx
PPTX
swings.pptx
PDF
03_Objects and Classes in java.pdf
PDF
02_Data Types in java.pdf
PPT
Intro tooop
EventHandling in object oriented programming
Exception‐Handling in object oriented programming
working with interfaces in java programming
introduction to object orinted programming through java
multhi threading concept in oops through java
Object oriented programming -QuestionBank
22H51A6755.pptx
swings.pptx
03_Objects and Classes in java.pdf
02_Data Types in java.pdf
Intro tooop
Ad

Recently uploaded (20)

PDF
Module 3: Health Systems Tutorial Slides S2 2025
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
English Language Teaching from Post-.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
High Ground Student Revision Booklet Preview
Module 3: Health Systems Tutorial Slides S2 2025
The Final Stretch: How to Release a Game and Not Die in the Process.
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Open Quiz Monsoon Mind Game Final Set.pptx
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Software Engineering BSC DS UNIT 1 .pptx
NOI Hackathon - Summer Edition - GreenThumber.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
English Language Teaching from Post-.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Introduction and Scope of Bichemistry.pptx
How to Manage Starshipit in Odoo 18 - Odoo Slides
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Insiders guide to clinical Medicine.pdf
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
O7-L3 Supply Chain Operations - ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
High Ground Student Revision Booklet Preview

file handling in object oriented programming through java

  • 1. Stream Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. Java defines two types of streams 1.Byte Streams 2.Character Streams
  • 2. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used to read and write binary data. Character streams provide a convenient means for handling input and output of characters. Character streams use Unicode.
  • 3. Stream Classes Stream-based I/O is built upon four abstract classes. They are 1.InputStream: 2.OutputStream: 3.Reader: 4.Writer. InputStream and OutputStream are designed for byte streams. Reader and Writer are designed for character streams.
  • 4. InputStream class InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes. methods of InputStream
  • 6. OutputStream class OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. methods of OutputStream
  • 8. FileInputStream FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data such as image data, audio, video etc. Its constructors FileInputStream(String filepath) FileInputStream(File fileObj) Example FileInputStream f0 = new FileInputStream("abc.txt") File f = new File(“abc.txt"); FileInputStream f1 = new FileInputStream(f);
  • 9. Example import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]) { try { FileInputStream fin=new FileInputStream(“input.txt"); int i=0; while((i=fin.read())!=-1) { System.out.print((char)i); } fin.close(); } catch(Exception e) { System.out.println(e); } } }
  • 10. FileOutputStream Java FileOutputStream is an output stream used for writing data to a file. Its constructors FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append)
  • 11. Example import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]) { try { FileOutputStream fout=new FileOutputStream("output.txt"); String s="Welcome to CMRCET."; 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); } } }
  • 12. File Operations Reading, Writing and Closing 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(); } } } }
  • 13. Reader class Reader is an abstract class for reading character streams. The methods that a subclass must implement are 1.read(char[], int, int) 2.close().
  • 15. Writer class It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int) flush() close()
  • 17. FileReader Class FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class Its constructors FileReader(String filePath) FileReader(File fileObj)
  • 18. Example import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exceptio n{ FileReader fr=new FileReader("test.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } }
  • 19. FileWriter class FileWriter class is used to write character- oriented data to a file. Its constructors FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append)
  • 20. Methods of FileWriter class 1. void write(String text):It is used to write the string into FileWriter. 2. void write(char c):It is used to write the char into FileWriter. 3. void write(char[] c):It is used to write char array into FileWriter. 4. void flush():It is used to flushes the data of FileWriter. 5. void close():It is used to close the FileWriter.
  • 21. Example import java.io.FileWriter; public class FileWriterExample { public static void main(String args[]) { try { FileWriter fw=new FileWriter(“out.txt"); fw.write("Welcome to CMRCET"); fw.close(); } catch(Exception e) { System.out.println(e); } System.out.println("Success..."); } }
  • 22. ArrayList Class 1.The underlined data structure is Resizable Array or Grow able Array. 2.Duplicates are allowed. 3.Insertion order is preserved. 4.Heterogeneous objects are allowed. 5.Null insertion is possible.
  • 23. ArrayList Constructors 1.ArrayList al = new ArrayList() Creates an empty Array list object with default capacity 10. Once ArrayList reaches its max capacity a new Array List will be created with new capacity=(currentcapacity*3/2)+1.
  • 24. 2. ArrayList al = new ArrayList(int initialCapacity); 3. ArrayList al=new ArrayList(Collection c)
  • 25. Example Import java.util.*; Class ArryListDemo { Pubilc static void main(String arg[]) { ArrayList l=new ArrayList(); l.add(“a”); l.add(10); l.add(“a”); l.add(null); Sysytem.out.println(l); l.remove(2); System.out.println(l); l.add(“2”,”m”); l.add(“n”); System.out.println(l); } }
  • 26. Usually we can use collections to hold and transfer Objects from on place to other place, to provide support for this requirement every Collection already implements Serializable and Cloneable interfaces. ArrayList class implements RandomAccess interface so that we can access any Random element with the same speed. Hence if our frequent operation is retrieval operation then ArrayList is the best choice. ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle(Because several shift operation are required).
  • 27. Vector class 1. The underlying Data structure for the vcetor is resizable array or growable arrray. 2. Duplicates are allowed. 3. Insertion order is preserved. 4. Heterogeneous objects are allowed. 5. Null insertion is possible. 6. Vector class implements Serializable, Cloneable and RandomAccess Interfaces. 7. Most of the methods presnt in vector are synchronized. Hence vector object is Thread–safe. 8. Best choice if the frequent operation is retrieval.
  • 28. Vector specific methods For adding objects Add(Object o); [from Collection -List(l)] Add(int index, Object o); [from List] addElement(Object o) [from Vector] For removing Objects remove(Object o) [from Collection] removeElement(Object o) [from Vector] remove(int index) [from List] removeElementAt(int index) [from Vector] Clear() [from Collection] removeElementAt()[from Vector]
  • 29. For Accessing Elements Object get(int index) [from Collection] Object elementAt(int index) [from Vector] Object firstElement() [from Vector] Object lastElement() [from Vector] Other Methods int size();// currently how many objects are there int capacity();// total how many objects we can accommodate. Enumeration elements();//to get elements one by one .
  • 30. Vector class constructors 1.Vector v= new Vector(); - Create an empty vector object with default capacity 10,once vector reaches its max capacity a new vector object will be created with new capacity=2* current capacity. 2. Vector v= new Vector (int initialCapacity) -creates an empty vector object with specified initial capacity. 3.Vector v=new Vector(int initial Capacity, int incremental Capacity) 4.Vector v=new Vector(Collection c); - Creates an equivalent vector Object for the given Collection
  • 31. Example Import java.util.*; Class VectorDemo { public static void main(String args[]) { Vector v=new Vector(); System.out.println(v.capacity()); for(int i=0;i<10;i++) { v.addElement(i); } System.out.println(v.capacity()); v.addElement(“A”); System.out.println(v.capacity()); System.out.println(v); } }
  • 32. Hashtable 1. The underlying data structure for Hashtable is Hashtable only. 2. Insertion order is not persevered and it is based on hash code of keys. 3. Duplicate keys are not allowed but values can be duplicated. 4. Heterogeneous objects are allowed for both keys and values. 5. Null is not allowed for both key and value, other wise we will get runtime exception saying null pointer exception 6. It implements Serializable and Cloneable interfaces but not RandomAccess. 7. Every method present in hash table is synchronized and hence hash table object is Thread-safe. 8. Hash table is best choice if our frequent operation is search operation.
  • 33. Constructors 1.Hashtable h=new Hashtable(); - default capacity is 11. and default fillRatio 0.75 2. Hashtable h=new Hashtable(int initial capacity); 3. Hashtable h=new Hashtable(int initial capacity, float fillRatio) 4. Hashtable h=new Hashtable(map m); fillRatio The decision of "When to increase the number of buckets" is decided by fillRatio (Load Factor). If fillRatio<(m/n) then Hash table size will be doubled. Where m=number of entries in a Hashtable n=Total size of hashtable.
  • 34. Example Import java.util.*; Class HashTableDemo { public static void main(String args[]) { Hashtable h=new Hashtable(); //Hashtable h=new Hashtable(25); h.put(new Temp(5), “A”); h.put(new Temp(2), “B”); h.put(new Temp(6), “C”); h.put(new Temp(15), “D”); h.put(new Temp(23), “E”); h.put(new Temp(16), “F”); System.out.println(h); } }
  • 35. Class Temp { int i; Temp(int i) { this.i=i; } Public int hashCode() { return i;// return i%9 } public String toString() { return i+””; } }
  • 36. Display order From Top to bottom And with in the Bucket the values are taken from right to left Out put: {6=C,16=F,5=A,15=D,2=B,23=E} If Hash code changes Out put: {16=F,15=D,6=C,23=E,5=A,2=B} 10 9 8 7 6 6=C 5 5=A, 16=F 4 15=D 3 2 2=B 1 23=E 0 10 9 8 7 16=F 6 6=C, 15=D 5 5=A, 23=E 4 3 2 2=B 1 0
  • 37. StringTokenizer class StringTokenizer class in Java is used to break a string into tokens. Example
  • 38. Constructors: StringTokenizer(String str) : str is string to be tokenized. Considers default delimiters like new line, space, tab, carriage return and form feed. StringTokenizer(String str, String delim) : delim is set of delimiters that are used to tokenize the given string. StringTokenizer(String str, String delim, boolean flag): The first two parameters have same meaning. The flag serves following purpose. If the flag is false, delimiter characters serve to separate tokens. For example, if string is "hello geeks" and delimiter is " ", then tokens are "hello" and “VCE". If the flag is true, delimiter characters are considered to be tokens. For example, if string is "hello VCE" and delimiter is " ", then tokens are "hello", " " and “VCE".
  • 39. Methods boolean hasMoreTokens():checks if there is more tokens available. String nextToken():returns the next token from the StringTokenizer object. String nextToken(String delim):returns the next token based on the delimeter. boolean hasMoreElements(): same as hasMoreTokens() method. Object nextElement(): same as nextToken() but its return type is Object. int countTokens():returns the total number of tokens.
  • 40. Example import java.util.*; public class NewClass { public static void main(String args[]) { System.out.println("Using Constructor 1 - "); StringTokenizer st1 = new StringTokenizer("Hello vce How are you", " "); while (st1.hasMoreTokens()) System.out.println(st1.nextToken()); System.out.println("Using Constructor 2 - "); StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :"); while (st2.hasMoreTokens()) System.out.println(st2.nextToken()); System.out.println("Using Constructor 3 - "); StringTokenizer st3 =new StringTokenizer("JAVA : Code : String", " :", true); while (st3.hasMoreTokens()) System.out.println(st3.nextToken()); } }
  • 41. Date class • The java.util.Date class represents date and time in java. It provides constructors and methods to deal with date and time in java. • The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
  • 42. Constructors 1.Date():Creates a date object representing current date and time. 2.Date(long milliseconds):Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
  • 43. Methods 1)boolean after(Date date): tests if current date is after the given date. 2)boolean before(Date date):tests if current date is before the given date. 3)Object clone():returns the clone object of current date. 4)int compareTo(Date date):compares current date with given date. 5)boolean equals(Date date):compares current date with given date for equality. 6)static Date from(Instant instant):returns an instance of Date object from Instant date. 7)long getTime():returns the time represented by this date object. 8)int hashCode():returns the hash code value for this date object. 9)void setTime(long time):changes the current date and time to given time. 10)Instant toInstant():converts current date into Instant object. 11)String toString():converts this date into Instant object.
  • 44. Example import java.util.*; public class Main { public static void main(String[] args) { Date d1 = new Date(); System.out.println("Current date is " + d1); Date d2 = new Date(2323223232L); System.out.println("Date represented is "+ d2 ); } } Out put Current date is Sat Oct 07 04:14:42 IST 2017 Date represented is Wed Jan 28 02:50:23 IST 1970