0% found this document useful (0 votes)
54 views70 pages

OOP Through Java: Unit - Iii

- Packages allow for organization and reuse of classes across programs. Java provides built-in packages that group related classes together, such as java.lang for core classes and java.io for input/output. Users can also define their own packages. - Streams facilitate input/output of data and come in two varieties - input streams that receive data and output streams that send data. Common stream classes include FileInputStream, FileOutputStream, BufferedReader, and BufferedWriter. Buffered streams improve efficiency by buffering data temporarily before writing. - The System class provides standard input/output streams for keyboard (System.in) and monitor (System.out). Programs can read user input from the keyboard

Uploaded by

Akram Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views70 pages

OOP Through Java: Unit - Iii

- Packages allow for organization and reuse of classes across programs. Java provides built-in packages that group related classes together, such as java.lang for core classes and java.io for input/output. Users can also define their own packages. - Streams facilitate input/output of data and come in two varieties - input streams that receive data and output streams that send data. Common stream classes include FileInputStream, FileOutputStream, BufferedReader, and BufferedWriter. Buffered streams improve efficiency by buffering data temporarily before writing. - The System class provides standard input/output streams for keyboard (System.in) and monitor (System.out). Programs can read user input from the keyboard

Uploaded by

Akram Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 70

OOP Through Java UNIT - III

Packages : Putting classes together

 The main feature of object oriented program is reusability.

 Reusability can be achieved by inheritance and interfaces.

 But, this is limited to reusing the classes with in the


program.

 To reuse the classes from other programs without


physically coping can be done with packages.

 Package is a group of related classes and interfaces of a


directory.
Packages - Benefits
 Grouping variety of classes and / or interfaces together.
 The grouping is usually done according to functionality
Benefits

 Classes of other programs can be easily reused.


 Hiding the classes according to the requirement
 Separates design from code.
 First, we design classes and decide their relationships, and then
we can implement the code required for methods.
 Implementation of the method can be done without
effecting the rest of the design.
Types of packages
 Two types
 Built-in Packages
 User define packages

 Java API provides a large number of classes grouped into


different packages according to functionality.

 Total No. of packages in Java 6.0: 203 (3793 classes)


 Total No. of packages in Java 7.0: 209 (4024 classes)
Java API Packages

java

util io awt net applet


lang
Contents of built-in packages

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.

5. java.net: contains networking classes for communicating with


local computers as well as with internet servers. Client-server
programming can be done by using this package.

6. java.applet : classes for creating and implementing applets.


Applets are the programs which comes from the server into a
client and get executed on the client machine on a network.
Naming conventions

 Can be named using standard naming rules.


 Packages begins with lower case letters.
 Class names begins with upper case letters.
 Ex: double y = java.lang.Math.sqrt(x);
User-defined packages
 Packages created by users are called as user-defined
packages.
 User-defined packages can also imported into other
classes and used exactly in the same way as built-in
packages.
 To create a package, syntax is:
 package packagename;
 To create a sub package (or multilevel packages) within a
package:
 Package packagename.subpackagename;
Program to create a package with addition
class
package pack; // pack is package name
public class Addition
{
private double d1,d2 // instance variables
public Addition(double a, double b)
{
d1=a;
d2=b;
}
public void sum()
{
System.out.println(“Sum=“+(d1+d2));
}
}
Compilation of package program
javac –d . Addition.java

 The -d option tells the java compiler to create a separate


sub directory and place the class file in it.

 The . (dot) indicates that the package should be created


with the name as pack in the current directory.

 To use this package with Addition class we need to write


another program.
Program to import a user defined
package and its classes into a program
import pack.Addition;
class Usepackage
{
public static void main(String args[])
{
Addition obj = new Addition(20,14.5);
obj.sum( );
}
}
class members access specifiers

There are five categories of visibility for class members.

 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

 Current working directory as its starting point. Thus if the


package is available in current directory or its sub
directory , it will be found.

 Secondly: we should specify the directory path by setting


the CLASSPATH
 The CLASSPATH is an environment variable that tells java
compiler where to look for the class files to import.
Summarization of Access Specifiers

Class member access


15
Streams
• Streams facilitate transporting data from one place to
another.
•Different streams are required to send or receive data
through different sources.
• To receive the data from keyboard, we need a stream and
to send data to a file we need another stream.
• It can be categorized as Input streams and output streams.
Input streams reads data or receive data
Output streams sends or write data.
These streams are represented by classes in IO
package
Streams
 Keyboard is represented by a field in System class. When we
write System.in, we are representing a standard input device, i.e.
keyboard. By default System class is found in java.lang package
and has three fields:

 System.in: represents InputStream object, represents standard


input device i.e. keyboard

 System.out: This represent PrintStream object, represents


standard output device, monitor .

 System.error: Represents System.out and used to display error


messages.
Data Input streams
 DataInputStream dis = new
DataInputStream(System.in);
 In this statement, we are attaching keyboard to
DataInputStream object. The keyboard is represented
by System.in
 System is a class and in is a field.
 It has three fields.
 System.in represents InputStream object.
 System.out represents PrintStream object.
 System.err represents PrintStream oject.
Streams Classification
 Classified into byte streams and text streams
 Byte streams present data in the form of bytes.
 Text streams represent data as characters of each 2 bytes.
 For ex: FileInputStream
 FileOutputStream
 BufferedInputStream
 BufferedOutputStream

 If a class name ends with Reader or Writer then it


takes as text stream.
 FileReader
 FileWriter
 BufferedReader
 BufferedWriter
Program for creating a text file using FileOutputStream
Or
Program to read data from keyboard and write to text file
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”);
System.out.println(“Enter text(@at end):”);
char ch;
while ((ch = (char)dis.read())!=‘@’);
fout.write(ch);
fout.close
}
}
Explanation
 To read the data from the keyboard, attach this to stream :
 DataInputStream in = new DataInputStream(System.in);
 Now, to store the data into a file attach a output stream.
So use FileOutputStream, which sends data to file.
 fout represents object.
 ch=(char)dis.read(); read one char into ch
 fout.write(ch) write ch into file.
Improving Efficiency Using Buffered
Output Stream
 Efficiency can be improved by using BufferedOutputStream
 It provides a buffer (temporary block of memory) which is
first filled with characters and then all the characters from
the buffer can be at once written into file.
 BufferedOutputStream can be used along with
FileOutputStream to write data into a file.
BufferedOutputStream
write buffer

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
{

BuffereedReader br = new BufferedReader(new InputStreamReader(System.in);


FileInputStream fin = new FileInputStream(“myfile.txt”);
System.out.println(“Enter file name”);
String fname = br.readLine();
FileInputStream fin = null;
try {
fin = new FileInputStream(fname);
}
catch(FileNotFoundException fe) {
System.out.println(“File not found”);
}

BufferedInputStream bin = new BufferedInputStream(fin);


int ch;
while ((ch = bin.read())!=-1);
System.out.print((char)ch);
bin.close();
}
}
Collections
 An Array is indexed collection of fixed no. of
homogeneous data elements.
 To use Arrays we should know the size compulsorily.
 Student s = new Student[100];
 s[0]= new Student[ ];
 s[1] = new Student[ ];
 S[2] = new Customer[ ]; // error and not possible;
 We can resolve this problem by using object arrays:
 Object[ ] a = new Object [100];
Collections in Java
 A collection object or a container object is an object
which can store a group of other objects.
 A collection object has a class called as collection class
or container class.
 These are available in java.util package.
 Collections are growable in nature. As per the
requirement we can increase or decrease the size.
 Collections can hold both homogeneous &
Heterogeneous data
 In the collection frame work JVM does not store the
copies of other objects. It simply stores the references of
other objects into a collection object.
Array Vs Collections
Array Collections
1) Arrays are fixed in size Collections are growable in nature
2) Memory point of view arrays Collections are recommended when
concept is not recommended you don’t know the exact size

3) Performance is better Performance is low


4) Arrays can hold only 4) Can hold heterogeneous data
homogeneous data

5) No underlying data structure 5) Data Structure is available. So


for arrays. Readymade methods are available

6) Arrays can hold both 6) Collections can hold only


primitives and objects objects.
Collection, Collections, Collection framework
 A group of individual objects as a single entity is called as
collection.
 Collection framework is a set of several classes & Interfaces
that represents a group of objects as a single entity

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

2. List (interface): to insert the duplicate values and


to preserve the insertion order, then we have to
use list.
3. Set: duplicates are not allowed and insertion order
is not preserved.
key interfaces of Collection framework
4. SortedSet: to represent a group of objects according to
some sorting order, then SortedSet is useful.
5. NavigatableSet: Useful for navigation purposes.
Introduced in 1.6 version
6. Queue: to represent a group of individual objects
prior to processing then queues are useful
7. Map: To represent a group of objects as a key-value
pair then map is useful. Key & Value are objects.
Duplicate keys are not allowed. But duplicate
values are allowed.
key interfaces of Collection framework
 8.SortedMap:To represent objects as key-value pairs
in some sorting order then sortedmap is useful. This
is child interface of Map.

 9.Navigatable Map: child of sortedMap & contains


several methods for navigation purposes.
Implementation of collection classes
 All the collection classes are implementation classes of
different interfaces as shown below:
Interface Type Implementation Classes

Set <T> HashSet<T>


LinkedHashSet <T>
List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>
Queue<T> LinkedList<T>
Map<K,V> HashMap<K,V>
Hashtable<K,V>
List of methods in Collection Interface
 1. boolean add(Object o)
 2. boolean addAll(Collection c)
 3. boolean remove(Object o)
 4. boolean removeAll(Collection c)
 5. boolean retainAll(Collection c)
 To remove all objects only
 6. void clear()
 7. boolean isEmpty()
 8. int size()
 9. boolean contains(Object o)
 10. boolean containsAll(Collection c)
 11. Object[] toArray()
 12. Iterator iterator()
List (Interface)
 List is the child Interface of collection.
 To represent a group of individual objects where
duplicates are allowed & insertion order is Preserved as
Index , then use collection.
 It contains 4 classes.
1) ArrayList (C)
2) LinkedList (C )
3) VectorList( C )
4) Stack(C)
ArrayList
 Heterogeneous objects are allowed
 Null insertion is possible
 ArrayList Al = new ArrayList();
Program using ArrayList
import java.util.*;
class AlistEx {
public static void main(String args[]) {
ArrayList al=new ArrayList();
al.add(“sasidhar”);
al.add(111);
al.add(9.2);
System.out.println(al);
al.remove(2);
al.add(1,”K”);
al.add(null);
al.add(“uppal”);
}
}
Linked List
 Underlying Data Structure is Doubly linked list
 Suitable for insertion or deletion in the middle.
 LinkedList l = new LinkedList();
 Creates an empty linkedlist object.
 Methods:
 We can use LinkedList to implement Stacks and Queue. To
support this linkedlist class defines the following methods.
 void addFirst(Object o);
 void addLast(Object o);
 Object removeFirst();
 Object removeLast();
 Object getFirst();
 Object getLast();
LinkedList Demo Program
import java.util.*;
class LinkedlistDemo {
public static void main(String args[]) {
LinkedList l=new LinkedList();
l.add(“sasidhar”);
l.add(111);
l.add(9.2);
l.add(null);
l.add(“Bhaskar”);
l.set(0,”Professor”);
l.add(0,”Anil”);
l.removeLat();
l.addFirst(“Ch”);
System.out.println(l);
}
}
Vector
 The Underlying data structure is Resizable array or
growable Array.
 Insertion order is preserved.
 Duplicate objects are allowed.
 Null insertion is possible
 Useful to retrieve the elements frequently.
 Vector v = new Vector();
 Methods to add objects:
 add(Object o)
 add(int index, Object o);
 addElement(Object o);
Vector
 To remove elements or objects
 remove(Object o)
 removeElement(Object o)
 remove(int index)
 removeElementAt(int index)
 clear()
 removeAllElements()
 To retrieve elements
 get(int index)
 elementAt(int index)
 firstElement();
 lastElement();
Other methods
 int Size();
 int Capacity();
 Enumeration elements();
Program for Vector
import java.util.*;
class TestVector {
public static void main(String args[]) {
Vector<String> v = new Vector(String);
v.add(“sasidhar”); // method of collection
v.addElement(“Bhaskar”); // method of Vector
Enumeration e = v.elements();
while(e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
Vector Program-II
import java.util.*;

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();

4. public boolean hasPrevious();


5. public object previous(); Backward
6. public int previousIndex();
Set interface
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects
where duplicates are not allow and insertion order
is not preserved then we should go for Set interface.
 Set interface does not contain any new method we
have to use only Collection interface methods.
Set

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

Map Interface Methods:


Object put(Object key, Object value)  adds key-value
pair to the map
Void putAll(Map m) : to add a group of key-value pairs.
Object get(Object key)
Returns the value associated with specified key.
If the key is not available, then we will get null.
Map
 Object remove(Object key)
 boolean containsKey(Object key)
 boolean ContainsValue(Object value)
 int Size();
 boolean isEmpty();
 void clear();
HashMap
 The underlying datastructure is HashTable
 Heterogeneous objects are allowed for both keys & values
 Duplicate keys are not allowed. But the values can be
duplicated.
 Insertion order is not preserved because it is based on
HashCode of keys.
 Null key is allowed for only once.
 Null values are allowed.
 Syntax: HashMap m = new HashMap();
 Create empty hashmap with default capacity and fillratio
Hashmap program demo
import java.util.*; while(it.hasNext()) {
class HashMapdemo { Map.Entry m1 = (Map.Entry) it.next();
public static void main(String System.out.println(m1.getKey() +”
args[]) { ..”+ m1.getValues());
HashMap h = new HashMap(); if(m1.getKey().equals(“srinu”))
h.put("srinu",101); m1.setValue[1000];
}
h.put("raju",102);
System.out.println(m);
h.put("Anil",103);
}
System.out.println(h); }
System.out.println(h.put("srinu",1
03));
Set s = m.keySet();
System.out.println(s);
Collection c = m.values();
System.out.println(c);
Set s1 = m.entrySet();
Iterator it = s1.iterator();
Linked HashMap
 Child class of HashMap
 Underlying data structure is HashTable set and
LinkedList
 Insertion order is preserved.
 Available from 1.4 version onwards.
Sorted Map
 To represent a group of entities according to some
sorting order then Sorted Map is useful.
 Sorting should be done based on the keys but not on
the values.
 Sorted Map Interface is the child interface of Map.
 Contains following methods
 Object firstKey();
 Object lastKey();
 SortedMap headMap(Object Key1);
 SortedMap tailMap(Object key1);
 SortedMap SubMap(Object Key1, Object key2);
 Comparator comparator();
Queue
 It is the child Interface of Collection.
 If we want to represent a group of individual objects prior
to processing then Queue is useful.
 In the 1.5 version of java, linked list implements queue.
 Follows FIFO
 Methods: boolean offer(Object obj)  to add an object
into the queue.
 Object peek( );  to return head element of the queue.
 If Queue is empty then, this method returns null.
 Object element( ); To return head element of the queue.
If queue is empty, then displays exception i.e.
NoSuchElement Exception.
Queue Methods
 Object poll()  to remove & return head element of the
queue. If queue is empty then this method returns null.
 Object remove()  to remove and return head element
of the queue, If queue is empty, then we will get runtime
exception saying no such element exception.
Priority Queue
 A group of objects are hold as per the priority i.e. prior
to processing.
 The priority can be either natural sorting order or
customized sorting order.
 If the sorting is default, then the objects should be
homogeneous and comparable.
 If the sorting is customized, then the object may
heterogeneous.
 Insertion order is not preserved and duplicates are not
allowed.
 Syntax:
PriorityQueue q = new PriorityQueue();
PriorityQueue q = new PriorityQueue(int initialCapacity);
Priority Queue Example
import java.util.*;
class PriorityQueuedemo {
public static void main(String args[]) {
PriorityQueue q = new PriorityQueue();
System.out.println(q.peek());
for(int i =0; i<=10; i++) {
q.offer(i);
}
System.out.println(q);
System.out.println(q.poll());
System.out.println(q);
}
}

You might also like