OOP Through Java: Unit - Iii
OOP Through Java: Unit - Iii
java
1. java.lang
language support classes. These are the classes that java
compiler itself uses and they are automatically imported.
Includes the classes for primitive types, strings,
stringbuffer, mathematical methods, threads and
exceptions.
2. java.util
Stands for utility. Contains utility classes like vectors, hash
tables, random number, date, stack, linked list etc.. These
classes are called collections.
3. java.io
input, output support classes. Contains streams. Streams
are useful to store the data in the form of files and to
perform input and output related tasks.
Contents of built-in packages
4. java.awt : abstract window tool kit. This package helps to
develop GUI based applications with graphics, colors,
paintings and images etc.. Also provides actions for windows
components.
Same class
Subclasses in the same package.
Non-subclasses in the same package.
Subclasses in different packages.
Non-subclasses in different packages.
13
Finding packages in CLASSPATH
To execute packages java run time system first looks in
FileOutputStream
myfile.txt
Program to Create a text file using
BufferedOutputStream
import java.io.*;
class CreateFile {
public static void main(String args[ ]) throws IOException {
DataInputStream in = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream(“myfile.txt”, true);
BufferedOutputStream bout = new
BufferedOutputStream(fout,1024);
System.out.println(“Enter text(@at end):”);
char ch;
while ((ch = (char)dis.read())!=‘@’);
bout.write(ch);
bout.close
}
}
Program to read data from myfile using
FileInputStream and display it on monitor
import java.io.*;
class ReadFile {
public static void main(String args[ ]) throws IOException
{
FileInputStream fin = new FileInputStream(“myfile.txt”);
System.out.println(“File contents”);
int ch;
while ((ch = fin.read())!=-1);
System.out.print((char)ch);
fin.close
}
}
Create file using FileWriter
Can create a file using FileWriter by writing characters
into it.
Java program to create a text file using FileWriter
import java.io.*;
class CreateFile{
public static void main(String args[]) throws IOException {
String s1 = “This is about java” +”\n I am a learner of java”;
FileWriter fw = new FileWriter(“text”);
for(int i=0; i<str.length(); i++)
fw.write(str.charAt(i));
fw.close();
}
}
file
import java.io.*;
class ReadFile {
public static void main(String args[ ]) throws IOException
{
Collection Vs Collections:
Collection is an interface
Collections is an utility class, present in java.util package and
contains several utility methods.
key interfaces of Collection framework
9 interfaces are available under collection framework.
1. collection (Interface):
This is the root interface of collection frame work
this defines the most common methods which are
applicable for any collection object.
class Vectordemo {
public static void main(String args[]) {
Vector v = new Vector();
System.out.println(v.capacity());
for(int i=1;i<=10;i++) {
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}
}
Stack
Last In First Out
This is the child class of Vector class and contains only
one constructor
Stack s = new Stack();
Methods:
Object push (Object o) : To insert an object into the stack
Object pop() : To remove and returns top of stack
Object peek(): To return top of the stack
Boolean empty(): returns when the stack is empty.
int search (Object o): returns the offset from top of the
stack if the stack is available. Otherwise returns -1
Cursors
Useful to retrieve objects one by one from collections.
3 types of cursors:
Enumeration (available in 1.0Version)
Iterator
ListIterator
Enumeration(1.0 ver):
public Enumeration elements( );
Enumeration e = V.elements(); V is vector object
Enumeration interface defines the following 2 methods:
public boolean hasMoreElements();
public Object nextElement();
Enumerations are useful for only ReadAccess.
Enumeration Demo
import java.util.*;
class EnumerationDemo {
public static void main(String[] args) {
Vector v=new Vector();
for(int i=0;i<=10;i++) {
v.addElement(i); }
System.out.println(v); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements()) {
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i); } //0 2 4 6 8 10
System.out.print(v); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
}
Iterator
To overcome the disadvantages of Enumeration, the Iterator
was introduced.
Useful for any collection object
It is a universal cursor
Useful for both read and write operations
Iterator itr = C.iterator(); // c is any collection object.
3 methods are there:
public boolean hasNext();
public Object next();
public void remove();
Iterators are for forward direction only.
Example for iterator
import java.util.*;
class IteratorDemo {
public static void main(String[] args) {
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++) {
a.add(i); }
System.out.println(a);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator itr=a.iterator();
while(itr.hasNext()) {
Integer i=(Integer)itr.next();
if(i%2==0)
System.out.println(i);//0, 2, 4, 6, 8, 10
else
itr.remove(); }
System.out.println(a);//[0, 2, 4, 6, 8, 10] }
}
List Iterator
Child interface of iterator
During iteration, the elements can be visited in forward or
backward directions
ListIterator litr = l.listIterator();
Methods: 1. Public boolean hasNext();
2. public object next(); Forward
3. public int nextIndex();
HashSet SortedSet
LinkedHashSet NavigableSet
TreeSet
HashSet & Linked HashSet
The underlying data structure is Hashtable
Insertion order is not preserved and is based on hash code
of objects.
Duplicate objects are not allowed.
Syntax: HashSet h=new HashSet();
LinkedHashSet: LinkedHashSet is the child class of
HashSet.
The underlying Data Structure is a combination of
Hashtable & Linked List
Insertion order is preserved.
Available from 1.4 Version onwards.
SortedSet
Set child Interface
To represent a group of individual objects according to some
sorting order it is better to use SortedSet
Methods: Object first()
Object last()
SortedSet headSet(Object obj)
SortedSet TailSet(Object obj)
SortedSet SubSet(Object obj1, Object obj2);
Comparator Comparator()
Example for SortedSet
In the list [100,101,103,104,107,109]
first() 100
Last() 109
headSet(104) [100,101,103]
tailSet(104) [ 104,107,108]
SubSet(101,107) [101,103,104]
Comparator() null.
TreeSet
Underlying data structure is balanced tree.
Duplicate objects are not allowed.
Insertion order is not preserved and it is based on some sorting
order of objects.
Heterogeneous objects are not allowed. If trying, it will return
ClassCast Exception
Null insertion is possible(only once).
Syntax: TreeSet t = new TreeSet(); Creates an empty TreeSet
object and elements are inserted according to natural / default
sorting order.
TreeSet t = new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be
inserted according to customized sorting order specified by
Comparator object.
Example program
import java.util.*;
class TreeSetdemo {
public static void main(String args[]) {
TreeSet t = new TreeSet();
t.add("A");
t.add("a");
t.add("2");
t.add("s");
System.out.println("A".compareTo("a"));
}
}
Comparable Vs. Comparator
Comparable means natural sorting order
Comparator means customized sorting order
Comparator Interface:
public int compare(Object obj1, Object obj2);
returns –ve if and only if obj1 has to come before obj2
returns +ve if and only if obj1 has to come after obj2
returns 0 if only if obj1 and obj2 are equal.
When we are implementing Comparator interface we
should provide implementation only for compare()
method.
order
import java.util.*;
class TreeSetdemo {
public static void main(String args[]) {
TreeSet t = new TreeSet(new MyComparator());
t.add(10);
t.add(2);
t.add(22);
t.add(4);
System.out.println(t); } }
class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return+1;
else if(i1>i2)
return -1;
else
return 0;
} }
Map
To represent a group of objects key-value pair maps are
useful.
Both key & values are objects.
Duplicate keys are not allowed, But values can be
duplicated.
Each key-value pair is called entry.
There is no relation between Collection & Map
Collection meant for a group of individual objects, where as
Map meant for a group of key-value pairs.
Map
HashTable
HashMap Weak HashMap Sorted Map
Identity HashMap