Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

Unit-III

1
Packages
• So far, we have seen reusing the classes ( via
inheritance ) within the program.

• What if we want to reuse your classes in other


programs without physically copying them ?

• In Java, this is achieved by using packages.

• Package is a group of classes.

2
Creating and importing an user defined package

1. Pick a name for your package

Ex : 1. mypackage
2. mypackage.util

– java recommends lower case letters to the


package names

3
2. Choose a directory in your hard drive as the
root directory of your package.
– You need a place on your hard disk to store your
packages.
– For example, create a directory such as c:\mylib
– This folder becomes the root directory for your
packages.

4
3.Create subdirectories within the root directory
for your package name.

For example, for the package named mypackage.util, create


a directory named mypackage in the c:\mylib. Then, in the
mypackage directory, create a directory named util.

5
4. Add the root directory for your package to
the classpath environment variable.

 Do not disturb any paths already listed in the classpath

– For example, suppose your classpsath is already set to


this:
C:\Program Files\Java\jdk1.5.0_05\lib;

– Then, you modify it to look like this:


C:\Program Files\Java\jdk1.5.0_05\lib;c:\mylib;

6
5. Add a package statement at the beginning of each
source file.

• All classes declared within that file belong to the specified


package.

• For example: package mypackage.util;

• The package statement must be the first statement in the file.

7
6. Save the files for any classes you want to be
in a particular package in the corresponding
package directory.

-- For example, save the files for a class that belongs to

the mypackage.util package in


c:\mylib\mypackage\util

8
Ex:
package mypackage.util;
public class Sum
{
public int sumInt(int a[])
{

int s=0;

for(int i=0;i<a.length;i++)
{
s = s+a[i];
}

return s;
}
}
9
Contd..
import mypackage.util.*;
class PackageDemo
{
public static void main( String args[])
{
int x[] = {1,2,3,4,5};
Sum s = new Sum();
System.out.println(s.sumInt(x));
}
}

Note: This file can be compiled and executed from any


place

10
• In general, a Java source file can contain any (or all)
of the following four internal parts:

– A single package statement (optional).


– Any number of import statements (optional).
– A single public class declaration (required).
– Any number of classes private to the package
(optional).

11
Java Built-In Packages
• There are six built-in packages :

– java.lang
• Contains classes for Strings, Math functions, Threads, and Exception
– java.util
• Contains classes such as Scanner, Vector,date, Calendar etc.
– java.io
• Stream classes for I/O
– java.awt
• Classes for implementing GUI – Windows, Buttons, Menus etc.
– java.net
• Classes for Network programming
– Java.sql
• Classes for Database accessing.
– java.applet
• Classes for creating and implementing applets

12
Accessing Classes from Packages
• There are two ways of accessing the classes
from packages:

1. Using fully qualified class name


• java.lang.Math.sqrt(x);

2. Import package and use class name directly


• import java.lang.Math;
• Math.sqrt(x);

13
• Selected class or all classes in packages can be
imported:

– import package.ClassName;
– import package.*;

14
Scopes defined by a class
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.

15
To summarize

Class member access

16
Contd..
• We can simplify access protection as follows:
– Anything declared public can be accessed from
anywhere.
– Anything declared private can be accessed within the
same class only.
– default is visible to the same class, subclasses and non-
subclasses in the same package.
– protected is visible to the same class, subclasses, non-
subclasses in the same package and subclasses in different
packages.

17
Class / Interface access modifiers

• A class / Interface has two access levels


– default
– public
• When a class is declared as public, it is accessible by any
other code.
• If a class has default access, then it can only be accessed by
other code within the same package.

18
I/O Programming

19
Introduction
• So far we have used variables and arrays for storing data
inside a program. This approach poses the following
limitations:

– The data is lost when the program terminates.


– It is difficult to handle large volumes of data.

• We can overcome this problem by storing data on secondary


storage devices such as hard disks.

20
C Input/Output Revision
FILE *fp;

fp = fopen(“In.file”, “rw”);
fscanf(fp, ……);
fpintf(fp, …..);
fread(………, fp);
fwrite(……….., fp);

21
I/O and Data Movement

• The flow of data into a program


(input) may come from different
devices such as keyboard, mouse,
memory, disk, network, or another
program.

• The flow of data out of a program


(output) may go to the screen,
printer, memory, disk, network,
another program.

22
Streams
• Java uses the concept of Streams
to represent the ordered sequence
of data.

• A Stream is a path along which


data flows (like a river or pipe
along which water flows).

23
• A stream, in java, is an object that reads data from a
source(keyboard, mouse, memory, disk, network, or another
program.) or writes data to a source (screen, printer,
memory, disk, network, another program).
Java Stream Classes
• Input/Output related stream classes are defined in
java.io package.

• Java i/o classes are categorised into two types:


– Byte streams
– Character Streams

25
Streams
Byte Streams Character streams

Operated on 8 bit (1 Operates on 16-bit (2


byte) data. byte) unicode
characters.
Input streams/Output Readers/ Writers
streams

26
Class Description
FileInputStream Provides methods for reading bytes from a file

FileOutputStream Provides methods for writing bytes to a file

DataInputStream Provides methods for reading Java's primitive data types

DataOutputStream Provides methods for writing Java's primitive data types

FileReader Provides methods for reading characters from a file

BufferedReader Provides buffering for character input streams

27
FileInputStream

• The FileInputStream class creates a Stream that can be used to


read bytes from a file.
• Its two most common constructors are shown below:

FileInputStream(String filepath)
FileInputStream(File fileObj)

• Here, filepath is the path of the file, and fileObj is a File object
that describes the file.

28
Methods in FileInputStream
Method Description
int read( ) Returns an integer representation of the next
available byte of input. –1 is returned when the
end of the file is encountered.

int available( ) Returns the number of bytes of input currently


available for reading.

void close( ) Closes the input source. Further read attempts will
generate an IOException.

long skip(long numBytes) Ignores (that is, skips) numBytes bytes of input,
returning the number of bytes actually ignored.

29
FileOutputStream
• FileOutputStream creates a Stream that can be used to write
bytes to a file.
• Its commonly used constructors are shown below:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)

• Here, filePath is the of a file, and fileObj is a File object that


describes the file. If append is true, the file is opened in
append mode.

30
Methods in FileOutputStream
Method Description
void write(int b) Writes a single byte to an output
stream.

void close( ) Closes the output stream. Further


write attempts will generate an IOException.

31
Ex
import java.io.*;
public class FileInputOutputExample
{
public static void main(String[] args) throws Exception
{
FileInputStream is = new FileInputStream("in.txt");
FileOutputStream os = new FileOutputStream("out.txt");
int c;
while ((c = is.read()) != -1)
{
System.out.print((char) c);
os.write(c);
}
is.close();
os.close();
}
}
32
DataOutputStream
• DataOutputStream takes an OutputStream ( Ex. FileOutputStream ) and uses this
to do higher-level i/o, such as writeInt, writeDouble, etc
• Constructor
– DataOutputStream(OutputStream out)

• Methods
– public void writeBoolean(boolean v) throws IOException
– public void writeByte(int b) throws IOException
– public void writeShort(int s) throws IOException
– public void writeChar(int c) throws IOException
– public void writeInt(int i) throws IOException
– public void writeLong(long l) throws IOException
– public void writeFloat(float f) throws IOException
– public void writeDouble(double d) throws IOException

33
DataInputStream
• DataInputStream takes an InputStream ( Ex. FileInputStream ) and uses this to do
higher-level i/o, such as readInt, readDouble, etc
• Constructor
– DataInputStream(InputStream in)

• Methods
– public boolean readBoolean(boolean v) throws IOException
– public byte readByte(int b) throws IOException
– public short readShort(int s) throws IOException
– public char readChar(int c) throws IOException
– public int readInt(int i) throws IOException
– public long readLong(long l) throws IOException
– public float readFloat(float f) throws IOException
– public double readDouble(double d) throws IOException

34
Ex
import java.io.*;
public class DataOutStream_And_DataInputStream_Example
{ public static void main(String[] args) throws IOException
{
DataOutputStream dos= new DataOutputStream( new FileOutputStream("data.txt") );

dos.writeInt(123);
dos.writeFloat(123.45F);
dos.writeLong(789);
dos.close();

DataInputStream dis= new DataInputStream( new FileInputStream(“data.txt") ) ;

int a= dis.readInt();
float b = dis.readFloat();
long c = dis.readLong();
dis.close();

System.out.println(“a = " + a);


System.out.println(“b = " + b);
System.out.println(“c = " + c);
}
}
35
FileReader
• The FileReader class creates a Reader that can be used to
read characters from a file.
• Its two most commonly used constructors are shown
below:

– FileReader(String filePath)
– FileReader(File fileObj)

36
Ex
import java.io.*;
public class FileReaderExample
{
public static void main(String[] args) throws Exception
{
FileReader fis = new FileReader ("in.txt");

int c;
while ((c = is.read()) != -1)
{
System.out.print( (char)c );

}
fis.close();

}
}
37
BufferedReader
• It is a character based input stream class.
• It reads more characters than initially needed and store
them in a buffer.
• So when the buffered reader's read() method is called,
the data is read from the buffer rather than from the file.
• When the buffer is empty, the buffered stream refills the
buffer.
• It improves the performance of I/O
• One long disk access takes less time than many smaller
ones.
• It reads large amount of data at a time into the buffer.
38
• BufferedReader Constructors
• It has two constructors
– BufferedReader( Reader inputstream )
– BufferedReader( Reader inputstream , int bufSize )

39
Ex: BufferedReader with a FileReader
import java.io.*;
public class BufferedReaderExample
{
public static void main(String[] args) throws Exception
{
FileReader fis = new FileReader ("in.txt");
BufferedReader br=new BufferedReader(fis);

int c;
while ((c = br.read()) != -1)
{
System.out.print( (char)c );

}
fis.close();
40
Collections Framework
Collections Framework is a hierarchy of interfaces
and classes that provide mechanism for managing
groups of objects.

A collection is an object that can hold references to


other objects.

The classes and interfaces of the collections


framework are in  java.util package.
Collections frame work contains the
following
• Interfaces .
• Implementations -These are the classes.
• Algorithms -These are the methods that perform
useful computations, such as searching and sorting, on
objects that implement collection interfaces.
Interfaces

Collection that Root interface for functions common


cannot contain to all types of collections
duplicates.
Collection Collection with functions for FIFO
and priority queues.

Set List Queue

Collection with
Deque operations for Double
SortedSet ended queue.
Stores a sequence of elements and
allows duplicate elements.
Special Set that maintains
the ordering of elements.
<<interface>>
<<interface>>
Interfaces Queue<E> Deque<E>
and their +add(E):boolean
+remove(Object):boolean
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
methods +size():int
+contains(Object):boolean
+size():int
+element():E
+element():E +remove():E
+remove():E +peek():E
+peek():E +poll():E
+poll():E +addFirst(Object): void
+addLast(Object):void
<<interface>> +getFirst(): E
<<interface>> List<E> +getLast():E
Collection<E> +add(E):boolean +removeFirst():E
+remove(Object):boolean +removeLast():E
+add(E):boolean +get(int):E
+remove(Object):boolean +indexOf(Object):int
+contains(Object):boolean +contains(Object):boolean
+size():int +size():int
etc… etc… <<interface>>
SortedSet<E>
+add(E):boolean
<<interface>>
+remove(Object):boolean
Set<E> +contains(Object):boolean
+add(E):boolean +size():int
+remove(Object):boolean +first():E
+contains(Object):boolean +last():E
+size():int +subSet(Object,Object) :
etc… SortedSet
etc…
The Collection Interface
 The Collection interface is the foundation upon which the
collections framework is built.

 Collection is a generic interface that has this declaration:


interface Collection<E>

 Here E specifies the type of objects that the collection will


hold.
The methods defined by Collection

Method Description
boolean add(E obj ) Returns true if obj was added at end of the collection. Returns false
if obj is already a member of the collection. Collection does not
allow duplicates.

boolean remove(Object obj) Removes obj from the collection . Returns true if the element was
removed. Otherwise returns false.

void clear( ) Removes all elements from the collection.

boolean isEmpty() Returns true if the collection is empty. Otherwise, returns false.

int size() Returns the number of elements held in the collection


The List Interface
 The List interface extends Collection and stores a sequence of
elements.
 Elements can be inserted or accessed by their position in the
list, using a zero-based index.
 A list may contain duplicate elements.
 List is a generic interface that has this declaration:
 Interface List<E>
The methods defined by List
Method Description
void add(E obj ) Inserts obj at the end of the list.

void add(int index, E obj) Inserts obj at the specified index . Any preexisting elements at or
beyond the point of insertion are shifted towards right.
E get(int index) Returns the object stored at the specified index.

int indexOf(Object obj) Returns the index of the first 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 obj in the invoking list. If obj is not an
element of the list, –1 is returned .
E remove(int index) Removes the element at position index t and returns the deleted
element. The indexes of subsequent elements are decremented by one.
The Set Interface

 The Set extends Collection and does not allow duplicate


elements.

 Therefore, the add( ) method returns false if an attempt is


made to add duplicate elements to a set.

 It does not define any additional methods of its own.


The SortedSet Interface

Method Description
Object first( ) Returns the first element in the invoking sorted set.

Object last( ) Returns the last element in the invoking sorted set.

SortedSet subSet(Object Returns a SortedSet that includes those elements


start, Object end) between start and end–1.
The queue interface
 The queue interface extends Collection and declares
the behavior of a queue, which is often first-in, first-
out list.
 Queue is a generic interface that has this declaration
interface Queue<E>
Methods defined by a queue
Method description
E element() Returns the element at the head of the queue. The element is
not removed. It throws NoSuchElementException if the
queue is empty.
E remove() Removes the element at the head of the queue and returns that
element. It throws NoSuchElementException if the queue is
empty.
E peek() Returns the element at the head of the queue. The element is
not removed. It returns null if the queue is empty.

E poll() Removes the element at the head of the queue and returns that
element. It returns null if the queue is empty.
The deque interface
 It was added by Java SE 6.
 It extends queue and declares the behavior of a
double ended queue.
 Double ended queue can function as first-in, first-out
queues or as last-in, first-out stacks.
Methods defined by deque
Method description
void addFisrt(E obj) Adds obj to the head of the queue.

void addLast(E obj) Adds obj to the tail of the queue.

E getFirst() Returns the first element in the queue. The element is not
removed.
E getLast() Returns the last element in the queue. The element is not
removed.
E removeFirst() Returns and removes the first element.

E removeLast() Returns and removes the last element.

54
The Collection Classes
 Collection classes are classes that implement
collection interfaces .

 Some of the classes provide full implementations that


can be used to maintain group of objects.

 Others are abstract classes.


The ArrayList Class

 The ArrayList class implements the List interface.


 ArraylList is a generic class that has this declaration:
class ArrayList<E>
 Here E specifies type of objects that the list will hold.
 ArrayList supports dynamic arrays that can grow as needed.
 In java, standard arrays are of fixed length.
 ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
 The first constructor builds an empty list. The second
constructor builds a list that is initialized with the elements of
the collection c.
Ex:-
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A"); Output:
al.add("E"); Initial size of al: 0
Size of al after additions: 7
al.add("B"); Contents of al: [C, A2, A, E, B, D, F]
al.add("D"); Size of al after deletions: 5
al.add("F"); Contents of al: [C, A2, E, B, D]
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
} 57
The LinkedList Class
 The LinkedList class implements the List , Deque, and
Queue interfaces.
 LinkedList Class is a generic class that has this
declaration:
class LinkedList<E>
 It provides a linked-list data structure. It has the two
constructors, shown here:
LinkedList( )
LinkedList(Collection c)
 The first constructor builds an empty linked list. The second
constructor builds a linked list that is initialized with the
elements of the collection c.
Ex:-
// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList<String> llist = new LinkedList<String>();
llist.add("F");
llist.add("B");
llist.add("D");
llist.add("E");
llist.add("C");
llist.addLast("Z");
llist.addFirst("A");
llist.add(1, "A2");
System.out.println("Original contents of llist: " + llist);
// remove elements from the linked list
llist.remove("F");
llist.remove(2);
System.out.println("Contents of llist after deletion: " + llist);
59
// remove first and last elements
llist.removeFirst();
llist.removeLast();
System.out.println("llist after deleting first and last: "+ llist);
}
}

Output:
Original contents of llist: [A, A2, F, B, D, E, C, Z]
Contents of llist after deletion: [A, A2, D, E, C, Z]
llist after deleting first and last: [A2, D, E, C]

60
The TreeSet Class
 TreeSet provides an implementation of the SortedSet
interface. Objects are stored in sorted, ascending
order
 The following constructors are defined:
TreeSet( )
TreeSet(Collection c)
 The first constructor builds an empty linked list. The
second constructor builds a linked list that is
initialized with the elements of the collection c.

61
Ex :
import java.util.*;
class TreeSetExample{
public static void main(String args[])
{
TreeSet<String> ts=new TreeSet<String>();
ts.add("Ravi");
ts.add("Vijay");
ts.add("Ajay");
ts.add("Pavan");
System.out.println(ts);
System.out.println(ts.first());
System.out.println(ts.last());
}
}

62
Algorithms
• The collections framework defines several algorithms
that can be applied to collections.

• These algorithms are defined as static methods


within the Collections class.

63
Method Description
static int binarySearch(List list, Object value) Searches for value in list. The list
must be sorted. Returns the
position of value in list,or−1 if
Value is not found

static void sort(List list) Sorts the elements of list as


determined by their natural
Ordering
static Object max(Collection c) Returns the maximum element
in c. The collection need
not be sorted
static Object min(Collection c) Returns the minimum element
in c. The collection need
not be sorted

64
static void swap(List list, int idx1, int idx2) Exchanges the elements in list at the
indices specified by idx1 and idx2.

static void shuffle(List list) Shuffles (i.e., randomizes) the


elements in list.

65
Example: (binary search)
import java.util.*;
class AlgorithmsDemo1
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Pavan");
Collections.sort(al);
System.out.println( "List After Sorting\n"+al);
System.out.println( "Enter Element to be searched ");
Scanner s=new Scanner(System.in);
String element=s.next();
int loc=Collections.binarySearch(al,element);
if(loc>0)
System.out.println("Element found, index="+loc );
else
System.out.println("Element not found" );

}
}
66
Example: ( Sorting )
import java.util.*;
class AlgorithmsDemo2
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Pavan");

System.out.println( "List Before Sorting\n"+al);


Collections.sort( al);
System.out.println( "List After Sorting\n"+al);

}
}

67
Example: (max, min and reverse)
import java.util.*;
public class MaxMinRev {
public static void main(String args[]) {
ArrayList<Integer> al=new ArrayList<Integer>();

al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);

System.out.println("List values: "+al);


System.out.println("Minimum is :"+Collections.min(al));
System.out.println(“Maximum is :"+Collections.max(al));

Collections.reverse(al);

System.out.println("List values after reverse: "+al);


}
}
68

You might also like