Professional Documents
Culture Documents
JavaUnit 3
JavaUnit 3
1
Packages
• So far, we have seen reusing the classes ( via
inheritance ) within the program.
2
Creating and importing an user defined package
Ex : 1. mypackage
2. mypackage.util
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.
5
4. Add the root directory for your package to
the classpath environment variable.
6
5. Add a package statement at the beginning of each
source file.
7
6. Save the files for any classes you want to be
in a particular package in the corresponding
package directory.
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));
}
}
10
• In general, a Java source file can contain any (or all)
of the following four internal parts:
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:
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
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
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:
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
22
Streams
• Java uses the concept of Streams
to represent the ordered sequence
of data.
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.
25
Streams
Byte Streams Character streams
26
Class Description
FileInputStream Provides methods for reading bytes from a file
27
FileInputStream
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.
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)
30
Methods in FileOutputStream
Method Description
void write(int b) Writes a single byte to an output
stream.
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();
int a= dis.readInt();
float b = dis.readFloat();
long c = dis.readLong();
dis.close();
– 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.
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.
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.
boolean isEmpty() Returns true if the collection is empty. Otherwise, returns false.
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
Method Description
Object first( ) Returns the first element in the invoking sorted set.
Object last( ) Returns the last element in the invoking sorted set.
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.
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.
54
The Collection Classes
Collection classes are classes that implement
collection interfaces .
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.
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
64
static void swap(List list, int idx1, int idx2) Exchanges the elements in list at the
indices specified by idx1 and idx2.
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");
}
}
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);
Collections.reverse(al);