Java Package Management and I/O Basics
Java Package Management and I/O Basics
Defining Package
Creating and Accessing a Package
Types of packages
Understanding CLASSPATH
importing packages
Packages
Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
You can define classes inside a package that are not accessible by code outside that
package.
You can also define class members that are only exposed to other members of the
same package.
Pre-defined packages
1. [Link] 11. [Link]
2. [Link] 12. [Link]
3. [Link] 13. [Link]
4. [Link] [Link]
5. [Link] [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
Defining a Packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.
To do so, simply separate each package name from the one above it by use of a
period.
A package hierarchy must be reflected in the file system of your Java development
system.
Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
For example, consider the following package specification.
package MyPack;
In order for a program to find MyPack, one of two things must be true.
Either the program is executed from a directory immediately above MyPack, or
CLASSPATH must be set to include the path to MyPack.
// A simple package //[Link]
package MyPack; class AccountBalance {
class Balance { public static void main(String args[]) {
Balance current[] = new Balance[3];
String name; current[0] = new Balance("K. J. Fielding", 123.23);
double bal; current[1] = new Balance("Will Tell", 157.02);
Balance(String n, double b){ current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
name = n; current[i].show();
bal = b; }
} }
void show() {
if(bal<0)
[Link]("--> "); //To compile
javac [Link]
[Link](name + ": $" + bal);
} //To run
} java [Link]
A class has only two possible access levels: default and public.
Class Member Access
//[Link]
package pack1;
public class VarProtection {
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public VarProtection() {
[Link]("Individual class constructor");
[Link]("default value is: " + n);
[Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
} To Compile:
} d:\>javac –d . [Link]
//SameSub .java:
package pack1;
class SameSub extends VarProtection{
SameSub(){
[Link]("subclass constructor");
[Link]("default value is: " + n);
// [Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
}
}
To Compile:
d:\>javac –d . [Link]
// [Link]
package pack1;
class SameDiff{
SameDiff(){
VarProtection v1 = new VarProtection();
[Link]("Delegationclass constructor");
[Link]("default value is: " +v1. n);
// [Link]("private value is: " +v1. pri);
[Link]("protected value is: " +v1. pro);
[Link]("public value is: " + [Link]);
}
}
To Compile:
d:\>javac –d . [Link]
//[Link]
package pack2;
import pack1.*;
class OtherSub extends VarProtection{
OtherSub(){
[Link]("Different Package subclass constructor");
//[Link]("default value is: " + n);
// [Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
}
}
To Compile:
d:\>javac –d . [Link]
// [Link]
package pack2;
import pack1.*;
class OtherDiff{
OtherDiff(){
VarProtection v2=new VarProtection();
[Link]("Different Package non-subclass constructor");
// [Link]("default value is: " +v2. n);
// [Link]("private value is: " + [Link]);
// [Link]("protected value is: " + [Link]);
[Link]("public value is: " + [Link]);
}
}
To Compile:
d:\>javac –d . [Link]
// Demo package p1. To Compile:
d:\>javac –d . [Link]
package pack1;
To Run:
Import pack1.*; d:\>java [Link]
class MainTest{
public static void main(String args[]){
VarProtection v=new VarProtection();
SameDiff s2=new SameDiff();
SameSub s1=new SameSub();
}
package pack2;
}
import pack1.*;
class OtherMainTest{
public static void main(String args[]){
OtherSub os=new OtherSub();
To Compile: OtherDiff od=new OtherDiff();
d:\>javac –d . [Link] }
To Run:
d:\>java [Link] }
Importing user-defined Packages
There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.
Java includes the import statement to bring certain classes, or entire packages,
into visibility.
Once imported, a class can be referred to directly, using only its name.
Finally, you specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.
The basic language functions are stored in a package inside of the java package
called [Link].
Normally, you have to import every package or class that you want to use, but
[Link] is implicitly imported by the compiler for all programs.
This is equivalent to the following line being at the top of all of your programs:
import [Link].*;
When a package is imported, only those items within the package declared as public will
be available to non-subclasses in the importing code. For example, if you want the
Balance class of the package MyPack shown earlier to be available as a stand-alone
class for general use outside of MyPack, then you will need to declare it as public and
put it into its own file, as shown here:
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
[Link](); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then
try compiling TestBalance. As explained, errors will result.
Introduction to I/O Programming:
Introduction to I/O Programming:
➢DataInputStream
➢DataOutputStream
➢FileInputStream
➢FileOutputStream
➢BufferedReader
Introduction
➢Input refers to reading data from some external source into a
running program.
➢Output refers to writing data from a running program to some
external destination.
➢A file is a collection of data stored on a disk or CD or some
other storage medium.
➢Files and their data persist beyond the duration of the program.
➢It is necessary to link the input stream object to the source and
the output stream object to the destination.
➢ The output stream takes the data from the variable and writes
to the destination.
1. FileInputStream(String filepath)
2. FileInputStream(File fileObj)
• Here, filepath is the path of the file, and fileObj is a File object
that describes the file.
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.
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)
Method Description
void write(int b) Writes a single byte to an output stream.
• Methods
– writeBoolean(boolean v)
– writeByte(int b)
– writeShort(int s)
– writeChar(int c)
– writeInt(int i)
– writeLong(long l)
– writeFloat(float f)
– writeDouble(double d)
DataInputStream
• 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.
• Constructor
– DataInputStream(InputStream in)
• Methods
– boolean readBoolean(boolean v)
– byte readByte(int b)
– short readShort(int s)
– char readChar(int c)
– int readInt(int i)
– long readLong(long l)
– float readFloat(float f)
– double readDouble(double d)
Example
DataInputStream dis= new DataInputStream(
import [Link].*; new FileInputStream(“[Link]") ) ;
public class DataOutStreamDataInputStream
{ int a= [Link]();
public static void main(String[] args) throws float b = [Link]();
IOException long c = [Link]();
{ [Link]();
DataOutputStream dos= new
DataOutputStream( new
[Link](“a = " + a);
FileOutputStream("[Link]") );
[Link](“b = " + b);
[Link](“c = " + c);
[Link](123);
}
[Link](123.45F);
}
[Link](789);
[Link]();
FileReader
– FileReader(String filePath)
– FileReader(File fileObj)
Example
import [Link].*;
public class FileReaderExample
{
public static void main(String[] args) throws Exception
{
FileReader fis = new FileReader ("[Link]");
int c;
while ((c = [Link]()) != -1)
{
[Link]( (char)c );
}
[Link]();
}
}
BufferedReader class
• Java BufferedReader class is used to read the text from a character-based
input stream. It can be used to read data line by line by readLine() method. It
makes the performance fast.
int c;
while ((c = [Link]()) != -1)
{
[Link]( (char)c );
}
[Link](); } }
Example 2:
import [Link].*;
class BufferedReaderEx
{
public static void main(String args[]) throws IOException
{
InputStreamReader is=new InputStreamReader([Link]);//reading data
from console.
BufferedReader br=new BufferedReader(is);
String str=[Link]();
[Link]("Welcome to "+str);
}
}
output:
>java BufferedReaderEx
this is cseaiml
Welcome to this is cseaiml
Problems in Storing objects into an Array.
We can store a group of similar datatype objects into an array
and retrieve them again easily but there are some
disadvantages in this mechanism;
1. We cannot store different class objects into the same array.
Because an array can store only homogenous data elements.
2. Adding objects at the end of an array is easy, But, inserting
and deleting the elements in the middle of the array is
difficult.
3. Retrieving the elements from an array is easy but after
retrieving the elements, if we want to process them, then there
are no methods available to carryout this.
Due to this problems, programmer want a better mechanism to
store group of objects, the alternative is collection framework.
Collections Framework
• Interfaces .
Collection with
Dequeue operations for Double
SortedSet ended queue.
Stores a sequence of elements and
allows duplicate elements.
Set<T> HashSet<T>
LinkedHashSet<T>
List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>
Queue<T>
Interface Type
LinkedList<T>
Map<K,V> HashMap<K,V>
Hashtable<K,V>
47
Sets:
A set represents a group of elements arranged just like an array.
The set will grow dynamically when the elements are stored
into it. A set will not allow duplicate elements or values.
Lists:
Lists are like sets. They store group of elements. But Lists allow
duplicate values to be stored.
Queues:
A Queue arrangement of elements in FIFO order.
Maps:
Maps store elements in the form of key and value pairs. If the key
is provided then its corresponding value can be obtained. The
key should have unique values.
48
<<interface>>
<<interface>>
Queue<E>> Deque<E>
Interfaces and +add(E):boolean +add(E):boolean
their methods +remove(Object):boolean
+contains(Object):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int +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
List<E>t<E> +getLast():E
<c<<interface>>
+add(E):boolean +removeFirst():E
Collection<E>on<E> +removeLast():E():E
+remove(Object):boolean
+add(E):boolean +get(int):E
+remove(Object):boolean +indexOf(Object):int
+contains(Object):boolean +contains(Object):boolean <<interface>>
+size():int +size():int
etc… SortedSet<E> >>
etc…etc…
+add(E):boolean
+remove(Object):boolean
<<interface>> +contains(Object):boolean
Set<E> +size():int
+first():E
+add(E):boolean
+last():E
+remove(Object):boolean
+contains(Object):boolean +subSet(Object,Object) :
+size():int SortedSet
etc… etc…etc…
The Collection Interface
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.
53
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.
SortedSet Interface
➢ SortedSet is the alternate of Set interface that provides a total
ordering on its elements.
➢ The elements of the SortedSet are arranged in the increasing
(ascending) order.
➢ The SortedSet provides the additional methods that inhibit the
natural ordering of the elements.
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.
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.
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.
61
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]
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. The second constructor
builds a TreeSet that is initialized with the elements of the
collection c.
➢ It does not allow to store duplicate elements.
68
Ex :
import [Link].*;
class TreeSetExample{
public static void main(String args[])
{
TreeSet<String> ts=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");
[Link](ts);
[Link]([Link]());
[Link]([Link]());
}
}
69
Algorithms
• The collections framework defines several algorithms
that can be applied to collections.
70
Method Description
static int binarySearch(List list, Searches for value in list. The list must be
Object value) 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
71
static void swap(List list, int idx1, int Exchanges the elements in list at
idx2) the indices specified by idx1 and
idx2.
static void shuffle(List list) Shuffles (i.e., randomizes) the
elements in list.
72
Example: (binary search)
import [Link].*;
class AlgorithmsDemo1
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");
[Link](al);
[Link]( "List After Sorting\n"+al);
[Link]( "Enter Element to be searched ");
Scanner s=new Scanner([Link]);
String element=[Link]();
int loc=[Link](al,element);
if(loc>=0)
[Link]("Element found, index="+loc );
else
[Link]("Element not found" );
}
} 73
Example: ( Sorting )
import [Link].*;
class AlgorithmsDemo2
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");
}
}
74
Example: (max, min and reverse)
import [Link].*;
public class MaxMinRev {
public static void main(String args[]) {
ArrayList<Integer> al=new ArrayList<Integer>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link](al);