Collections in Java, Java I/O Stream,File Class in java, String and StringBuffer Class,DataInputStream , FileInputStream and FileOutputStream Class,FileReader & FileWriter

Java Collection

 

Collection: A collection is an object that represents a group of objects. A collection sometimes         called a container is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. It contains the following:


collections in java, Interfaces Arraylist vector,HashMap, Hash Table ,Liked List






Interfaces

Interface Name

Description

Collection

This enables you to work with groups of objects; it is at the top of the collection’s hierarchy.

List

This extends Collection and an instance of List stores an ordered collection of elements.

Set

This extends Collection to handle sets, which must contain unique elements.

SortedSet

This extends Set to handle sorted sets.

Map

This maps unique keys to values.

SortedMap

This extends Map so that the keys are maintained in an ascending order.

 

Collection Interface methods

 

Method

Description

boolean add(Object obj)

Adds obj to the invoking collection.

boolean addAll(Collection c)

Adds all the elements of c to the invoking collection.

void clear( )

Removes all elements from the invoking collection.

boolean contains(Object obj)

Returns true if obj is an element of the invoking collection.

boolean containsAll(Collection c)

Returns true if the invoking collection contains all elements of c.

boolean equals(Object obj)

Returns true if the invoking collection and obj are equal.

int hashCode( )

Returns the hash code for the invoking collection.


boolean isEmpty( )

Returns true if the invoking collection is empty.

Iterator iterator( )

Returns an iterator for the invoking collection.

boolean remove(Object obj)

Removes one instance of obj from the invoking collection. Returns true if the element was removed.

boolean removeAll(Collection c)

Removes all elements of c from the invoking collection.

boolean retainAll(Collection c)

Removes all elements from the invoking collection except those in c.

int size( )

Returns the number of elements held in the invoking collection.

Object[ ] toArray( )

Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements.

Object[ ] toArray(Object array[ ])

Returns an array containing only those collection elements whose type matches that of array.


List Interface

Stores sequence of elements may contain duplicate elements. It allows to store heterogeneous data.

 

Method

Description

void add(int index, Object obj)

Inserts obj into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up.

boolean addAll(int index, Collection c)

Inserts all elements of c into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up.

Object get(int index)

Returns the object stored at the specified index within the invoking collection.

int indexOf(Object obj)

Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list,-1 is returned.


int lastIndexOf(Object obj)

Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, -1 is returned.

ListIterator listIterator( )

Returns an iterator to the start of the invoking list.

ListIterator listIterator(int index)

Returns an iterator to the invoking list that begins at the specified index.

Object remove(int index)

Removes the element at position index from the invoking list and returns the deleted element.

Object set(int index, Object obj)

Assigns obj to the location specified by index within the invoking list.

List subList(int start, int end)

Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.

 

Set Interface and SortedSet Interface

Set Interface and SortedSet Interface is a collection that contains no duplicate elements. It contains the methods of the Collection interface(add (), clear(),contains() etc). A SortedSet is a Set that maintains its elements in ascending order. It allows to store homogeneous data. It adds the following methods:

 

Methods

Description

Comparator comparator( )

Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned.

Object first( )

Returns the first element in the invoking sorted set.

SortedSet headSet(Object end)

Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set.

Object last( )

Returns the last element in the invoking sorted set.

SortedSet subSet(Object start, Object end)

Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object.

SortedSet tailSet(Object start)

Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object.


 

Map Interface

A Map represents an object that maps keys to values. Keys have to be unique.

 

Method

Description

void clear( )

Removes all key/value pairs from the invoking map.

boolean containsKey(Object k)

Returns true if the invoking map contains k as a key.

boolean containsValue(Object v)

Returns true if the map contains v as a value.

Set entrySet( )

Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.

boolean equals(Object obj)

Returns true if obj is a Map and contains the same entries.

Object get(Object k)

Returns the value associated with the key k.

int hashCode( )

Returns the hash code for the invoking map.

boolean isEmpty( )

Returns true if the invoking map is empty.

Set keySet( )

Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.

Object put(Object k, Object v)

Puts an entry in the invoking map, overwriting any previous value associated with the key.

void putAll(Map m)

Puts all the entries from m into this map.

Object remove(Object k)

Removes the entry whose key equals k.

int size( )

Returns the number of key/value pairs in the map.

Collection values( )

Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.


List Implementation

There are two general-purpose List implementations — ArrayList and LinkedList.

1.     ArrayList: Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

 

2.     LinkedList: The LinkedList class implements the List interface. All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

3.     Vector: Implements Dynamic array. It is similar to ArrayList, but with two differences −

1.       Vector is synchronized.

2.       Vector contains many legacy methods that are not part of the collections framework.

Vector Constructors:

·       Vector() : Default Vector with initial size zero.

·       Vector(int size):Vector with initial capacity as size.

·       Vector(int size, int increment): Constructs a vector whose initial capacity is specified by size and whose increment is specified by incr.

·       Vector(Collection c):Construct a vector that contains the elements of collection c.

 

Set Implementation

There are three general-purpose Set implementations — HashSet, TreeSet and LinkedHashSet.

1.  TreeSet: The elements are internally stored in a search tree. It is useful when you need to extract elements from a collection in a sorted manner.

 

2.  HashSet: It creates a collection the uses a hash table for storage. The advantage of HashSet is that it performs basic operations (add, remove, contains and size) in constant time and is faster than TreeSet

 

3.  LinkedHashSet: The only difference is that the LinkedHashSet maintains the order of the items added to the Set, The elements are stored in a doubly linked list.

 

Map Implemetation

There are three general-purpose Map implementations HaspMap, LinkedHashMap, TreeMap

1.     HashMap: The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

 

2.     LinkedHashMap: This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.


3.     TreeMap: The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.

 

Iterator

The Iterator interface provides methods using which we can traverse any collection. This interface is implemented by all collection classes.

 

Methods by Iterator

Method

Description

boolean hasNext( )

Returns true if there are more elements. Otherwise, returns false.

Object next( )

Returns the next element. Throws NoSuchElementException if there is not a next element.

void remove( )

Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

 

The Methods Declared by ListIterator

 

Methods

Description

boolean hasNext( )

Returns true if there is a next element. Otherwise, returns false.

boolean hasPrevious( )

Returns true if there is a previous element. Otherwise, returns false.

Object next( )

Returns the next element. A NoSuchElementException is thrown if there is not a next element.

int nextIndex( )

Returns the index of the next element. If there is not a next element, returns the size of the list.

Object previous( )

Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

int previousIndex( )

Returns the index of the previous element. If there is not a previous element, returns -1.

void remove( )

Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.


void set(Object obj)

Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

 

 

Java I/O

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

Stream

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

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1)    System.out: standard output stream

2)    System.in: standard input stream

3)    System.err: standard error stream

 

String class

In Java, string is basically an object that represents sequence of char values. An array

of characters works same as Java string. This class present in the package java.lang which contains two string classes:


a)         String class

b)         StringBuffer class

 

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

Method

Description

char charAt(int index)

It returns char value for the particular index

int length()

It returns string length

static String format(String format, Object... args)

It returns a formatted string.

static String format(Locale l, String format,

Object... args)

It returns formatted string with given locale.

String substring(int beginIndex)

It returns substring for given begin index.

String substring(int beginIndex, int endIndex)

It returns substring for given begin index and end

index.

boolean contains(CharSequence s)

It returns true or false after matching the sequence of

char value.

static String join(CharSequence delimiter,

CharSequence... elements)

It returns a joined string.

static String join(CharSequence delimiter,

Iterable<? extends CharSequence> elements)

It returns a joined string.

boolean equals(Object another)

It checks the equality of string with the given object.

boolean isEmpty()

It checks if string is empty.

String concat(String str)

It concatenates the specified string.

String replace(char old, char new)

It replaces all occurrences of the specified char value.

String replace(CharSequence old,

CharSequence new)

It replaces all occurrences of the specified

CharSequence.

static String equalsIgnoreCase(String another)

It compares another string. It doesn't check case.

String[] split(String regex)

It returns a split string matching regex.

String[] split(String regex, int limit)

It returns a split string matching regex and limit.

String intern()

It returns an interned string.

int indexOf(int ch)

It returns the specified char value index.

int indexOf(int ch, int fromIndex)

It returns the specified char value index starting with

given index.

int indexOf(String substring)

It returns the specified substring index.

int indexOf(String substring, int fromIndex)

It returns the specified substring index starting with

given index.

String toLowerCase()

It returns a string in lowercase.

String toLowerCase(Locale l)

It returns a string in lowercase using specified locale.

String toUpperCase()

It returns a string in uppercase.

String toUpperCase(Locale l)

It returns a string in uppercase using specified locale.

String trim()

It removes beginning and ending spaces of this string.

static String valueOf(int value)

It converts given type into string. It is an overloaded

method.


 

StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as String class except it is mutable i.e. it can be changed.

 

Constructor

Description

StringBuffer()

It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str)

It creates a String buffer with the specified string..

StringBuffer(int capacity)

It creates an empty String buffer with the specified capacity as length.

 

StringBuffer Methods

Method

Description

StringBuffer append(String str)

appends the specified string to this character sequence.

int capacity()

returns the current capacity.

char charAt(int index)

This method returns the char value in this sequence at

the specified index.

StringBuffer delete(int start, int

end)

This method removes the characters in a substring of

this sequence.

StringBuffer deleteCharAt(int

index)

This method removes the char at the specified position

in this sequence

void ensureCapacity(int

minimumCapacity)

This method ensures that the capacity is at least equal

to the specified minimum.

void getChars(int srcBegin, int

srcEnd, char[] dst, int dstBegin)

This method characters are copied from this sequence

into the destination character array dst.

int indexOf(String str)

This method returns the index within this string of the

first occurrence of the specified substring.

int indexOf(String str, int fromIndex)

This method returns the index within this string of the

first occurrence of the specified substring, starting at the specified index.

StringBuffer insert(int offset, int i)

This method inserts the string representation of the

second int argument into this sequence.

int lastIndexOf(String str)

This method returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)

This method returns the index within this string of the last occurrence of the specified substring.

int length()

This method returns the length (character count).

StringBuffer replace(int start, int end, String str)

This method replaces the characters in a substring of this sequence with characters in the specified String.

StringBuffer reverse()

This method causes this character sequence to be

replaced by the reverse of the sequence.

void setCharAt(int index, char ch)

The character at the specified index is set to ch.


void setLength(int newLength)

This method sets the length of the character sequence.

String substring(int start)

This method returns a new String that contains a subsequence of characters currently contained in this

character sequence

String substring(int start, int end)

This method returns a new String that contains a subsequence of characters currently contained in this

sequence.

void trimToSize()

This method attempts to reduce storage used for the character sequence.

 

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

 

Constructor

Description

File(File parent, String child)

It creates a new File instance from a parent abstract pathname and a

child pathname string.

File(String pathname)

It creates a new File instance by converting the given pathname

string into an abstract pathname.

File(String parent, String child)

It creates a new File instance from a parent pathname string and a child pathname string.

File(URI uri)

It creates a new File instance by converting the given file: URI into

an abstract pathname.

 

File class methods

Method

Description

boolean canWrite()

It tests whether the application can modify the file denoted by this abstract

pathname.String[]

boolean canExecute()

It tests whether the application can execute the file denoted by this abstract

pathname.

boolean canRead()

It tests whether the application can read the file denoted by this abstract

pathname.

boolean isAbsolute()

It tests whether this abstract pathname is absolute.

boolean isDirectory()

It tests whether the file denoted by this abstract pathname is a directory.

boolean isFile()

It tests whether the file denoted by this abstract pathname is a normal file.

String getName()

It returns the name of the file or directory denoted by this abstract

pathname.

String getParent()

It returns the pathname string of this abstract pathname's parent, or null if

this pathname does not name a parent directory.

Path toPath()

It returns a java.nio.file.Path object constructed from the this abstract path.

URI toURI()

It constructs a file: URI that represents this abstract pathname.


File[] listFiles()

It returns an array of abstract pathnames denoting the files in the directory

denoted by this abstract pathname

long getFreeSpace()

It returns the number of unallocated bytes in the partition named by this

abstract path name.

String[] list(FilenameFilter

filter)

It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

boolean mkdir()

It creates the directory named by this abstract pathname.

boolean

createNewFile()

It atomically creates a new, empty file named by this abstract pathname if

and only if a file with this name does not yet exist.

 

Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.

 

            Java FileOutputStream Class

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

If you have to write primitive values into a file, use FileOutputStream class. You can write byte- oriented as well as character-oriented data through FileOutputStream class. But, for character- oriented data, it is preferred to use FileWriter than FileOutputStream.

 

Java FileReader Class

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

It is character-oriented class which is used for file handling in java.

Constructor

Description

FileReader(String

file)

It gets filename in string. It opens the given file in read mode. If file doesn't

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 of FileReader class

Method

Description

int read()

It is used to return a character in ASCII form. It returns -1 at the end of file.

void close()

It is used to close the FileReader class.

Java FileWriter Class

Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.

Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.


Constructor

Description

FileWriter(String file)

Creates a new file. It gets file name in string.

FileWriter(File file)

Creates a new file. It gets file name in File object.

 

      Methods of FileWriter class

Method

Description

void write(String text)

It is used to write the string into FileWriter.

void write(char c)

It is used to write the char into FileWriter.

void write(char[] c)

It is used to write char array into FileWriter.

void flush()

It is used to flushes the data of FileWriter.

void close()

It is used to close the FileWriter.

 

Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.


            Java DataInputStream class Methods

Method

Description

int read(byte[] b)

to read the number of bytes from the input stream.

int read(byte[] b, int off, int len)

to read len bytes of data from the input stream.

int readInt()

to read input bytes and return an int value.

byte readByte()

to read and return the one input byte.

char readChar()

to read two input bytes and returns a char value.

double readDouble()

to read eight input bytes and returns a double value.

boolean readBoolean()

to read one input byte and return true if byte is non zero,

false if byte is zero.

int skipBytes(int x)

to skip over x bytes of data from the input stream.

String readUTF()

to read a string that has been encoded using the UTF-8

format.

void readFully(byte[] b)

to read bytes from the input stream and store them into the

buffer array.

void readFully(byte[] b, int off, int len)

to read len bytes from the input stream.

 

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.


Java DataOutputStream class methods

 

Method

Description

int size()

It is used to return the number of bytes written to the data output

stream.


void write(int b)

It is used to write the specified byte to the underlying output

stream.

void write(byte[] b, int off, int len)

It is used to write len bytes of data to the output stream.

void writeBoolean(boolean v)

It is used to write Boolean to the output stream as a 1-byte

value.

void writeChar(int v)

It is used to write char to the output stream as a 2-byte value.

void writeChars(String s)

It is used to write string to the output stream as a sequence of

characters.

void writeByte(int v)

It is used to write a byte to the output stream as a 1-byte value.

void writeBytes(String s)

It is used to write string to the output stream as a sequence of

bytes.

void writeInt(int v)

It is used to write an int to the output stream

void writeShort(int v)

It is used to write a short to the output stream.

void writeShort(int v)

It is used to write a short to the output stream.

void writeLong(long v)

It is used to write a long to the output stream.

void writeUTF(String str)

It is used to write a string to the output stream using UTF-8

encoding in portable manner.

void flush()

It is used to flushes the data output stream.

 

 


 

 

 

 

 

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

Java Database Connectivity (JDBC) ,Steps to connect to the database in Java