Java Note 4

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 67

Collections in Java

1. Java Collection Framework

2. Hierarchy of Collection Framework

3. Collection interface

4. Iterator interface

Collections in java is a framework that provides an architecture to store and manipulate


the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection in java


Collection represents a single unit of objects i.e. a group.

What is framework in java

o provides readymade architecture.

o represents set of classes and interface.

o is optional.

What is Collection framework


Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

1. Interfaces and its implementations i.e. classes

2. Algorithm

Do You Know ?
o What are the two ways to iterate the elements of a collection ?

o What is the difference between ArrayList and LinkedList classes in collection


framework?

o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection
framework?

o What is the difference between HashMap and Hashtable class?

o What is the difference between Iterator and Enumeration interface in collection


framework?

o How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces?

o What does the hashcode() method ?

o What is the difference between java collection and java collections ?

Hierarchy of Collection Framework


Let us see the hierarchy of collection framework.The java.util package contains all the
classes and interfaces for Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(Object is used to insert an element in this collection.


element)

2 public boolean is used to insert the specified collection


addAll(Collection c) elements in the invoking collection.
3 public boolean remove(Object is used to delete an element from this
element) collection.

4 public boolean is used to delete all the elements of specified


removeAll(Collection c) collection from the invoking collection.

5 public boolean is used to delete all the elements of invoking


retainAll(Collection c) collection except the specified collection.

6 public int size() return the total number of elements in the


collection.

7 public void clear() removes the total no of element from the


collection.

8 public boolean contains(Object is used to search an element.


element)

9 public boolean is used to search the specified collection in this


containsAll(Collection c) collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object matches two collection.


element)

14 public int hashCode() returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.


2. public object next() it returns the element and moves the cursor pointer to the
next element.

3. public void remove() it removes the last elements returned by the iterator. It is
rarely used.

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.

Before generics, we can store any type of objects in collection i.e. non-generic. Now
generics, forces the java programmer to store specific type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesnt allow to
store other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

1. List list = new ArrayList();


2. list.add("hello");
3. String s = (String) list.get(0);//typecasting

After Generics, we don't need to typecast the object.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not occur at


runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. list.add(32);//Compile Time Error

Syntax to use generic collection


1. ClassOrInterface<Type>

Example to use Generics in java

1. ArrayList<String>

Full Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now

Output:element is: jai


rahul
jai

Example of Java Generics using Map


Now we are going to use map elements using generics. Here, we need to pass key and
value. Let us understand it by a simple example:

1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Test it Now

Output:1 vijay
2 ankit
4 umesh

Generic class
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.

Lets see the simple example to create and use the generic class.

Creating generic class:

1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The
type you specify for the class, will be used to store and retrieve the data.
Using generic class:

Lets see the code to use the generic class.

1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2

Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:

1. T - Type

2. E - Element

3. K - Key

4. N - Number

5. V - Value

Generic Method
Like generic class, we can create generic method that can accept any type of argument.

Lets see a simple example of java generic method to print array elements. We are using
here E to denote the element.

1. public class TestGenerics4{


2.
3. public static < E > void printArray(E[] elements) {
4. for ( E element : elements){
5. System.out.println(element );
6. }
7. System.out.println();
8. }
9. public static void main( String args[] ) {
10. Integer[] intArray = { 10, 20, 30, 40, 50 };
11. Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
12.
13. System.out.println( "Printing Integer Array" );
14. printArray( intArray );
15.
16. System.out.println( "Printing Character Array" );
17. printArray( charArray );
18. }
19. }
Test it Now

Output:Printing Integer Array


10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T

Wildcard in Java Generics


The ? (question mark) symbol represents wildcard element. It means any type. If we write
<? extends Number>, it means any child class of Number e.g. Integer, Float, double etc.
Now we can call the method of Number class through any child class object.

Let's understand it by the example given below:

1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11.
12.
13. class GenericTest{
14. //creating a method that accepts only child class of Shape
15. public static void drawShapes(List<? extends Shape> lists){
16. for(Shape s:lists){
17. s.draw();//calling method of Shape class by child class instance
18. }
19. }
20. public static void main(String args[]){
21. List<Rectangle> list1=new ArrayList<Rectangle>();
22. list1.add(new Rectangle());
23.
24. List<Circle> list2=new ArrayList<Circle>();
25. list2.add(new Circle());
26. list2.add(new Circle());
27.
28. drawShapes(list1);
29. drawShapes(list2);
30. }}
drawing rectangle
drawing circle
drawing circle

Java ArrayList class


Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.

o Java ArrayList class maintains insertion order.

o Java ArrayList class is non synchronized.

o Java ArrayList allows random access because array works at the index basis.

o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be


occurred if any element is removed from the array list.

Hierarchy of ArrayList class


As shown in above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.

ArrayList class declaration


Let's see the declaration for java.util.ArrayList class.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess
, Cloneable, Serializable

Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the colle

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList

Method Description

void add(int index, Object It is used to insert the specified element at the specified position index i
element)

boolean addAll(Collection c) It is used to append all of the elements in the specified collection to t
this list, in the order that they are returned by the specified collection's

void clear() It is used to remove all of the elements from this list.

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
element, or -1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this
correct order.

Object[] toArray(Object[] It is used to return an array containing all of the elements in this
a) correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean addAll(int index, It is used to insert all of the elements in the specified collection int
Collection c) starting at the specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
element, or -1 if the List does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the lis
size.

Java Non-generic Vs Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.

Let's see the old non-generic example of creating java collection.

1. ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile
time error.

For more information of java generics, click here Java Generics Tutorial.

Java ArrayList Example

1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Test it Now
Ravi
Vijay
Ravi
Ajay

Two ways to iterate the elements of collection in java


There are two ways to traverse collection elements:

1. By Iterator interface.

2. By for-each loop.

In the above example, we have seen traversing ArrayList by Iterator. Let's see the example
to traverse ArrayList elements using for-each loop.

Iterating Collection through for-each loop

1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
Test it Now
Ravi
Vijay
Ravi
Ajay

User-defined class objects in Java ArrayList


Let's see an example where we are storing Student class object in array list.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method

1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Sonoo");
10. al2.add("Hanumat");
11. al.addAll(al2);//adding second list in first list
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat

Example of removeAll() method

1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.removeAll(al2);
12. System.out.println("iterating the elements after removing the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17.
18. }
19. }
Test it Now
iterating the elements after removing the elements of al2...
Vijay
Ajay

Example of retainAll() method

1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }
Test it Now
iterating the elements after retaining the elements of al2...
Ravi
Java ArrayList Example: Book
Let's see an ArrayList example where we are adding books to list and printing all the books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill
",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now
Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector

1) ArrayList is not Vector is synchronized.


synchronized.

2) ArrayList increments 50% of Vector increments 100% means doubles the


current array size if number of array size if total number of element exceeds than
element exceeds from its its capacity.
capacity.

3) ArrayList is not a Vector is a legacy class.


legacy class, it is introduced in
JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized i.e. in


non-synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until
current thread releases the lock of object.

5) ArrayList Vector uses Enumeration interface to traverse


uses Iterator interface to the elements. But it can use Iterator also.
traverse the elements.

Legacy Classes
Early version of java did not include the Collection framework. It only defined several classes
and interface that provide method for storing objects. When Collection framework were added in
J2SE 1.2, the original classes were reengineered to support the collection interface. These classes
are also known as Legacy classes. All legacy claases and interface were redesign by JDK 5 to
support Generics.
The following are the legacy classes defined by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector

There is only one legacy interface called Enumeration


NOTE: All the legacy classes are syncronized

Enumeration interface

1. Enumeration interface defines method to enumerate through collection of object.


2. This interface is suspended by Iterator interface.
3. However some legacy classes such as Vector and Properties defines several method in
which Enumeration interface is used.
4. It specifies the following two methods

boolean hasMoreElements()

Object nextElement()

Vector class

1. Vector is similar to ArrayList which represents a dynamic array.


2. The only difference between Vector and ArrayList is that Vector is synchronised while
Array is not.
3. Vector class has following four constructor
4. Vector()

5.

6. Vector(int size)

7.
8. Vector(int size, int incr)

9.

10. Vector(Collection< ? extends E> c)

Vector defines several legacy method. Lets see some important legacy method define
by Vector class.

Method Description

addElement() add element to the Vector

elementAt() return the element at specified index

elements return an enumeration of element in vector

firstElement() return first element in the Vector

lastElement() return last element in the Vector

removeAllElement() remove all element of the Vector

Example of Vector
import java.util.*;

public class Test

public static void main(String[] args)

Vector ve = new Vector();

ve.add(10);

ve.add(20);

ve.add(30);

ve.add(40);
ve.add(50);

ve.add(60);

Enumeration en = ve.elements();

while(en.hasMoreElements())

System.out.println(en.nextElement());

Output :
10

20

30

40

50

60

Hashtable class

1. Like HashMap, Hashtable also stores key/value pair in hashtable. However


neither keys nor values can be null.
2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
3. Hashtable has following four constructor
4. Hashtable()

5. Hashtable(int size)

6. Hashtable(int size, float fillratio)

7. Hashtable(Map< ? extends K, ? extends V> m)

Example of Hashtable
import java.util.*;

class HashTableDemo

public static void main(String args[])

Hashtable< String,Integer> ht = new Hashtable< String,Integer>();

ht.put("a",new Integer(100));

ht.put("b",new Integer(200));

ht.put("c",new Integer(300));

ht.put("d",new Integer(400));

Set st = ht.entrySet();

Iterator itr=st.iterator();

while(itr.hasNext())

Map.Entry m=(Map.Entry)itr.next();

System.out.println(itr.getKey()+" "+itr.getValue());

Output:
a 100

b 200

c 300

d 400

Difference between HashMap and Hashtable

Hashtable HashMap

Hashtable class is synchronized. HastMap is not synchronize.

Because of Thread-safe, Hashtable is slower than HashMap works faster.


HashMap

Neither key nor values can be null Both key and values can be null

Order of table remain constant over time. does not guarantee that order of map remain
constant over time.

Properties class

1. Properties class extends Hashtable class.


2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor
4. Properties()

5. Properties(Properties default)

6. One advantage of Properties over Hashtable is that we can specify a default property that
will be useful when no value is associated with a certain key.

Example of Properties class


import java.util.*;

public class Test

public static void main(String[] args)

Properties pr = new Properties();

pr.put("Java", "James Ghosling");

pr.put("C++", "Bjarne Stroustrup");

pr.put("C", "Dennis Ritchie");

pr.put("C#", "Microsoft Inc.");


Set< ?> creator = pr.keySet();

for(Object ob: creator)

System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );

Output :
Java was created by James Ghosling

C++ was created by Bjarne Stroustrup

C was created by Dennis Ritchie

C# was created by Microsoft Inc

ava Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

The important points about Java Hashtable class are:

o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key.

o It contains only unique elements.

o It may have not have any null key or value.

o It is synchronized.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneabl


e, Serializable
Hashtable class Parameters
Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.

o V: It is the type of mapped values.

Constructors of Java Hashtable class

Constructor Description

Hashtable() It is the default constructor of hash table it instantiates the Hashtabl


class.

Hashtable(int size) It is used to accept an integer parameter and creates a hash table that ha
an initial size specified by integer value size.

Hashtable(int size, float It is used to create a hash table that has an initial size specified by size and
fillRatio) a fill ratio specified by fillRatio.

Methods of Java Hashtable class

Method Description

void clear() It is used to reset the hash table.

boolean contains(Object This method return true if some value equal to the value exist within
value) the hash table, else return false.

boolean containsValue(Object This method return true if some value equal to the value exist
value) within the hash table, else return false.

boolean containsKey(Object This method return true if some key equal to the key exists within
key) the hash table, else return false.

boolean isEmpty() This method return true if the hash table is empty; returns false if i
contains at least one key.

void rehash() It is used to increase the size of the hash table and rehashes all of it
keys.

Object get(Object key) This method return the object that contains the value associated with
the key.
Object remove(Object key) It is used to remove the key and its value. This method return the
value associated with the key.

int size() This method return the number of entries in the hash table.

Java Hashtable Example

1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
8. hm.put(101,"Vijay");
9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Test it Now

Output:

103 Rahul
102 Ravi
101 Vijay
100 Amit

Java Hashtable Example: remove()

1. import java.util.*;
2. public class HashtableExample {
3. public static void main(String args[]) {
4. // create and populate hash table
5. Hashtable<Integer, String> map = new Hashtable<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }

Output:

Values before remove: {103=Operating System, 102=Let us C, 101=Data


Communication and Networking}
Values after remove: {103=Operating System, 101=Data Communication and
Networking}

Java Hashtable Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashtableExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new Hashtable<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill
",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26. //Traversing map
27. for(Map.Entry<Integer, Book> entry:map.entrySet()){
28. int key=entry.getKey();
29. Book b=entry.getValue();
30. System.out.println(key+" Details:");
31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

32. }
33. }
34. }

Output:

3 Details:
103 Operating System Galvin Wiley 6
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8

STACk
Stack is a subclass of Vector that implements a standard last-in, first-out
stack.

Stack only defines the default constructor, which creates an empty stack.
Stack includes all the methods defined by Vector, and adds several of its
own.

Stack( )

Apart from the methods inherited from its parent class Vector, Stack
defines the following methods

Sr.No. Method & Description


boolean empty()
1
Tests if this stack is empty. Returns true if the stack is
empty, and returns false if the stack contains elements.

Object peek( )

2
Returns the element on the top of the stack, but does not
remove it.

Object pop( )

3
Returns the element on the top of the stack, removing it
in the process.

Object push(Object element)

4
Pushes the element onto the stack. Element is also
returned.

int search(Object element)

5
Searches for element in the stack. If found, its offset from
the top of the stack is returned. Otherwise, .1 is returned.

Example
The following program illustrates several of the methods supported by this
collection

import java.util.*;
public class StackDemo {

static void showpush(Stack st, int a) {


st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {


System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
}catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

This will produce the following result

Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack

ENUMERATion
The Enumeration interface defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. Although not


deprecated, Enumeration is considered obsolete for new code. However, it
is used by several methods defined by the legacy classes such as Vector
and Properties, is used by several other API classes, and is currently in
widespread use in application code.

The methods declared by Enumeration are summarized in the following


table

Sr.No. Method & Description

boolean hasMoreElements( )

1 When implemented, it must return true while there are


still more elements to extract, and false when all the
elements have been enumerated.

Object nextElement( )

2
This returns the next object in the enumeration as a
generic Object reference.

Example
Following is an example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {


Enumeration days;
Vector dayNames = new Vector();

dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();

while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}

This will produce the following result

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
ITERATOR

Often, you will want to cycle through the elements in a collection. For
example, you might want to display each element. The easiest way to do
this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing


elements. ListIterator extends Iterator to allow bidirectional traversal of a
list, and the modification of elements.

Before you can access a collection through an iterator, you must obtain one.
Each of the collection classes provides an iterator( ) method that returns an
iterator to the start of the collection. By using this iterator object, you can
access each element in the collection, one element at a time.

In general, to use an iterator to cycle through the contents of a collection,


follow these steps

Obtain an iterator to the start of the collection by calling the collection's iterator(
) method.

Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.

Within the loop, obtain each element by calling next( ).

For collections that implement List, you can also obtain an iterator by
calling ListIterator.

The Methods Declared by Iterator


Sr.No. Method & Description

boolean hasNext( )
1
Returns true if there are more elements. Otherwise,
returns false.
Object next( )

2
Returns the next element. Throws
NoSuchElementException if there is not a next element.

void remove( )

3 Removes the current element. Throws


IllegalStateException if an attempt is made to call
remove( ) that is not preceded by a call to next( ).

The Methods Declared by ListIterator


Sr.No. Method & Description

void add(Object obj)


1
Inserts obj into the list in front of the element that will be
returned by the next call to next( ).

boolean hasNext( )

2
Returns true if there is a next element. Otherwise, returns
false.

boolean hasPrevious( )

3
Returns true if there is a previous element. Otherwise,
returns false.

Object next( )

4
Returns the next element. A NoSuchElementException is
thrown if there is not a next element.
int nextIndex( )

5
Returns the index of the next element. If there is not a
next element, returns the size of the list.

Object previous( )

6
Returns the previous element. A NoSuchElementException
is thrown if there is not a previous element.

int previousIndex( )

7
Returns the index of the previous element. If there is not
a previous element, returns -1.

void remove( )

8 Removes the current element from the list. An


IllegalStateException is thrown if remove( ) is called
before next( ) or previous( ) is invoked.

void set(Object obj)

9
Assigns obj to the current element. This is the element
last returned by a call to either next( ) or previous( ).

Example
Here is an example demonstrating both Iterator and ListIterator. It uses an
ArrayList object, but the general principles apply to any type of collection.

Of course, ListIterator is available only to those collections that implement


the List interface.

import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

// Use iterator to display contents of al


System.out.print("Original contents of al: ");
Iterator itr = al.iterator();

while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Modify objects being iterated


ListIterator litr = al.listIterator();

while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Now, display the list backwards


System.out.print("Modified list backwards: ");

while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}

This will produce the following result

Output
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

StringTokenizer in Java
1. StringTokenizer

2. Methods of StringTokenizer

3. Example of StringTokenizer

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class


There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string,


String delim, boolean delimeter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens. If it
is false, delimiter characters serve to separate tokens.

Methods of StringTokenizer class


The 6 useful methods of StringTokenizer class are as follows:

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer


object.

String nextToken(String returns the next token based on the delimeter.


delim)

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class


Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer


class
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Output:Next token is : my

Java Scanner class


There are various ways to read input from the keyboard, the java.util.Scanner class is one
of them.

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and primitive types using regular
expression.

Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class


There is a list of commonly used Scanner class methods:
Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the
value as a string.

public byte nextByte() it scans the next token as a byte.

public short it scans the next token as a short value.


nextShort()

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double it scans the next token as a double value.


nextDouble()

Java Scanner Example to get input from console


Let's see the simple example of the Java Scanner class which reads the int, string and
double value as an input:

1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }
download this scanner example

Output:

Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter


Let's see the example of Scanner class with delimiter. The \s represents whitespace.

1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}

Output:

10
tea
20
coffee
files
The java.io package contains nearly every class you might ever need to
perform input and output (I/O) in Java. All these streams represent an
input source and an output destination. The stream in the java.io package
supports many data such as primitives, object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of
Streams

InPutStream The InputStream is used to read data from a source.

OutPutStream The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and
networks but this tutorial covers very basic functionality related to streams
and I/O. We will see the most commonly used examples one by one

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an
input file into an output file

Example

import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Now let's have a file input.txt with the following content

This is test for copy file.

As a next step, compile the above program and execute it, which will result
in creating output.txt file with the same content as we have in input.txt. So
let's put the above code in CopyFile.java file and do the following

$javac CopyFile.java
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two
classes to copy an input file (having unicode characters) into an output file

Example

import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Now let's have a file input.txt with the following content

This is test for copy file.

As a next step, compile the above program and execute it, which will result
in creating output.txt file with the same content as we have in input.txt. So
let's put the above code in CopyFile.java file and do the following

$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where the
user's program can take input from a keyboard and then produce an output
on the computer screen. If you are aware of C or C++ programming
languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard
streams

Standard Input This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.

Standard Output This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.

Standard Error This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.

Following is a simple program, which creates InputStreamReader to read


standard input stream until the user types a "q"

Example

import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}

Let's keep the above code in ReadConsole.java file and try to compile and
execute it as shown in the following program. This program continues to
read and output the same character until we press 'q'

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data.
The InputStream is used to read data from a source and
the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream,


which would be discussed in this tutorial.

FileInputStream
This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.

Following constructor takes a file name as a string to create an input stream


object to read the file

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to


read the file. First we create a file object using File() method as follows

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper
methods which can be used to read to stream or to do other operations on
the stream.

Sr.No. Method & Description

public void close() throws IOException{}

1 This method closes the file output stream. Releases any


system resources associated with the file. Throws an
IOException.

protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures


2
that the close method of this file output stream is called
when there are no more references to this stream. Throws
an IOException.

public int read(int r)throws IOException{}

3 This method reads the specified byte of data from the


InputStream. Returns an int. Returns the next byte of
data and -1 will be returned if it's the end of the file.

public int read(byte[] r) throws IOException{}

4 This method reads r.length bytes from the input stream


into an array. Returns the total number of bytes read. If it
is the end of the file, -1 will be returned.

public int available() throws IOException{}


5

Gives the number of bytes that can be read from this file
input stream. Returns an int.

There are other important input streams available, for more detail you can
refer to the following links

ByteArrayInputStream

DataInputStream

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream


object.

Following constructor takes a file name as a string to create an input stream


object to write the file

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object


to write the file. First, we create a file object using File() method as follows

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper
methods, which can be used to write to stream or to do other operations on
the stream.

Sr.No. Method & Description

public void close() throws IOException{}


1
This method closes the file output stream. Releases any
system resources associated with the file. Throws an
IOException.

protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures


2
that the close method of this file output stream is called
when there are no more references to this stream. Throws
an IOException.

public void write(int w)throws IOException{}

3
This methods writes the specified byte to the output
stream.

public void write(byte[] w)

4
Writes w.length bytes from the mentioned byte array to
the OutputStream.

There are other important output streams available, for more detail you can
refer to the following links

ByteArrayOutputStream

DataOutputStream

Example

Following is the example to demonstrate InputStream and OutputStream

import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i = 0; i < size; i++) {


System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e) {
System.out.print("Exception");
}
}
}

The above code would create file test.txt and would write given numbers in
binary format. Same would be the output on the stdout screen.

File Navigation and I/O


There are several other classes that we would be going through to get to
know the basics of File Navigation and I/O.

File Class

FileReader Class

FileWriter Class
Directories in Java
A directory is a File which can contain a list of other files and directories.
You use File object to create directories, to list down files available in a
directory. For complete detail, check a list of all the methods which you can
call on File object and what are related to directories.

Creating Directories
There are two useful File utility methods, which can be used to create
directories

The mkdir( ) method creates a directory, returning true on success and false on
failure. Failure indicates that the path specified in the File object already exists,
or that the directory cannot be created because the entire path does not exist
yet.

The mkdirs() method creates both a directory and all the parents of the
directory.

Following example creates "/tmp/user/java/bin" directory

Example

import java.io.File;
public class CreateDir {

public static void main(String args[]) {


String dirname = "/tmp/user/java/bin";
File d = new File(dirname);

// Create directory now.


d.mkdirs();
}
}

Compile and execute the above code to create "/tmp/user/java/bin".


Note Java automatically takes care of path separators on UNIX and
Windows as per conventions. If you use a forward slash (/) on a Windows
version of Java, the path will still resolve correctly.

Listing Directories
You can use list( ) method provided by File object to list down all the files
and directories available in a directory as follows

Example

import java.io.File;
public class ReadDir {

public static void main(String[] args) {


File file = null;
String[] paths;

try {
// create new file object
file = new File("/tmp");

// array of files and directory


paths = file.list();

// for each name in the path array


for(String path:paths) {
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}

This will produce the following result based on the directories and files
available in your /tmp directory

Output

test1.txt
test2.txt
ReadDir.java
ReadDir.class

FILE MANAGEMENT USING FILE CLASS


Java File class represents the files and directory pathnames in an abstract
manner. This class is used for creation of files and directories, file
searching, file deletion, etc.

The File object represents the actual file/directory on the disk. Following is
the list of constructors to create a File object.

Sr.No. Method & Description

File(File parent, String child)


1
This constructor creates a new File instance from a parent
abstract pathname and a child pathname string.

File(String pathname)

2
This constructor creates a new File instance by converting
the given pathname string into an abstract pathname.

File(String parent, String child)

3
This constructor creates a new File instance from a parent
pathname string and a child pathname string.
File(URI uri)

4
This constructor creates a new File instance by converting
the given file: URI into an abstract pathname.

Once you have File object in hand, then there is a list of helper methods
which can be used to manipulate the files.

Sr.No. Method & Description

public String getName()


1
Returns the name of the file or directory denoted by this
abstract pathname.

public String getParent()

2 Returns the pathname string of this abstract pathname's


parent, or null if this pathname does not name a parent
directory.

public File getParentFile()

3 Returns the abstract pathname of this abstract


pathname's parent, or null if this pathname does not
name a parent directory.

public String getPath()


4
Converts this abstract pathname into a pathname string.

public boolean isAbsolute()


5

Tests whether this abstract pathname is absolute. Returns


true if this abstract pathname is absolute, false otherwise.

public String getAbsolutePath()

6
Returns the absolute pathname string of this abstract
pathname.

public boolean canRead()

Tests whether the application can read the file denoted by


7
this abstract pathname. Returns true if and only if the file
specified by this abstract pathname exists and can be
read by the application; false otherwise.

public boolean canWrite()

Tests whether the application can modify to the file


8 denoted by this abstract pathname. Returns true if and
only if the file system actually contains a file denoted by
this abstract pathname and the application is allowed to
write to the file; false otherwise.

public boolean exists()

Tests whether the file or directory denoted by this


9
abstract pathname exists. Returns true if and only if the
file or directory denoted by this abstract pathname exists;
false otherwise.

public boolean isDirectory()

10
Tests whether the file denoted by this abstract pathname
is a directory. Returns true if and only if the file denoted
by this abstract pathname exists and is a directory; false
otherwise.

public boolean isFile()

Tests whether the file denoted by this abstract pathname


is a normal file. A file is normal if it is not a directory and,
11 in addition, satisfies other system-dependent criteria. Any
non-directory file created by a Java application is
guaranteed to be a normal file. Returns true if and only if
the file denoted by this abstract pathname exists and is a
normal file; false otherwise.

public long lastModified()

Returns the time that the file denoted by this abstract


pathname was last modified. Returns a long value
12
representing the time the file was last modified, measured
in milliseconds since the epoch (00:00:00 GMT, January
1, 1970), or 0L if the file does not exist or if an I/O error
occurs.

public long length()

13 Returns the length of the file denoted by this abstract


pathname. The return value is unspecified if this
pathname denotes a directory.

public boolean createNewFile() throws IOException

Atomically creates a new, empty file named by this


14 abstract pathname if and only if a file with this name does
not yet exist. Returns true if the named file does not exist
and was successfully created; false if the named file
already exists.
public boolean delete()

Deletes the file or directory denoted by this abstract


15 pathname. If this pathname denotes a directory, then the
directory must be empty in order to be deleted. Returns
true if and only if the file or directory is successfully
deleted; false otherwise.

public void deleteOnExit()

16 Requests that the file or directory denoted by this abstract


pathname be deleted when the virtual machine
terminates.

public String[] list()

17 Returns an array of strings naming the files and


directories in the directory denoted by this abstract
pathname.

public String[] list(FilenameFilter filter)

18 Returns an array of strings naming the files and


directories in the directory denoted by this abstract
pathname that satisfy the specified filter.

public File[] listFiles()

20
Returns an array of abstract pathnames denoting the files
in the directory denoted by this abstract pathname.

public File[] listFiles(FileFilter filter)


21
Returns an array of abstract pathnames denoting the files
and directories in the directory denoted by this abstract
pathname that satisfy the specified filter.

public boolean mkdir()

22 Creates the directory named by this abstract pathname.


Returns true if and only if the directory was created; false
otherwise.

public boolean mkdirs()

Creates the directory named by this abstract pathname,


23 including any necessary but nonexistent parent
directories. Returns true if and only if the directory was
created, along with all necessary parent directories; false
otherwise.

public boolean renameTo(File dest)

24 Renames the file denoted by this abstract pathname.


Returns true if and only if the renaming succeeded; false
otherwise.

public boolean setLastModified(long time)

25 Sets the last-modified time of the file or directory named


by this abstract pathname. Returns true if and only if the
operation succeeded; false otherwise.

public boolean setReadOnly()

Marks the file or directory named by this abstract


26
pathname so that only read operations are allowed.
Returns true if and only if the operation succeeded; false
otherwise.
public static File createTempFile(String prefix,
String suffix, File directory) throws IOException

27 Creates a new empty file in the specified directory, using


the given prefix and suffix strings to generate its name.
Returns an abstract pathname denoting a newly-created
empty file.

public static File createTempFile(String prefix,


String suffix) throws IOException

Creates an empty file in the default temporary-file


28
directory, using the given prefix and suffix to generate its
name. Invoking this method is equivalent to invoking
createTempFile(prefix, suffix, null). Returns abstract
pathname denoting a newly-created empty file.

public int compareTo(File pathname)

Compares two abstract pathnames lexicographically.


Returns zero if the argument is equal to this abstract
29
pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or
a value greater than zero if this abstract pathname is
lexicographically greater than the argument.

public int compareTo(Object o)

Compares this abstract pathname to another object.


Returns zero if the argument is equal to this abstract
30
pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or
a value greater than zero if this abstract pathname is
lexicographically greater than the argument.
public boolean equals(Object obj)

Tests this abstract pathname for equality with the given


31
object. Returns true if and only if the argument is not null
and is an abstract pathname that denotes the same file or
directory as this abstract pathname.

public String toString()

32
Returns the pathname string of this abstract pathname.
This is just the string returned by the getPath() method.

Example
Following is an example to demonstrate File object

package com.tutorialspoint;
import java.io.File;

public class FileDemo {

public static void main(String[] args) {


File f = null;
String[] strs = {"test1.txt", "test2.txt"};
try {
// for each string in string array
for(String s:strs ) {
// create new file
f = new File(s);

// true if the file is executable


boolean bool = f.canExecute();

// find the absolute path


String a = f.getAbsolutePath();
// prints absolute path
System.out.print(a);

// prints
System.out.println(" is executable: "+ bool);
}
}catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
}
}
}

Consider there is an executable file test1.txt and another file test2.txt is


non executable in the current directory. Let us compile and run the above
program, This will produce the following result

Output
Path of the file/test1.txt is executable: false
Path of the file/test2.txt is executable: false

JDBC
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server.

For example, using JDBC drivers enable you to open database connections
and to interact with it by sending SQL or database commands then
receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with
their behaviours defined and their actual implementaions are done in third-
party drivers. Third party vendors implements the java.sql.Driver interface
in their database driver.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating
systems and hardware platforms in which Java operates. Sun has divided
the implementation types into four categories, Types 1, 2, 3, and 4, which
is explained below

Type 1: JDBC-ODBC Bridge Driver


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed
on each client machine. Using ODBC, requires configuring on your system a
Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases
only supported ODBC access but now this type of driver is recommended
only for experimental use or when no other alternative is available.

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this
kind of driver.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API
calls, which are unique to the database. These drivers are typically provided
by the database vendors and used in the same manner as the JDBC-ODBC
Bridge. The vendor-specific driver must be installed on each client machine.

If we change the Database, we have to change the native API, as it is


specific to a database and they are mostly obsolete now, but you may
realize some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java


In a Type 3 driver, a three-tier approach is used to access databases. The
JDBC clients use standard network sockets to communicate with a
middleware application server. The socket information is then translated by
the middleware application server into the call format required by the
DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed


on the client and a single driver can actually provide access to multiple
databases.
You can think of the application server as a JDBC "proxy," meaning that it
makes calls for the client application. As a result, you need some knowledge
of the application server's configuration in order to effectively use this
driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate


with the database, understanding the nuances will prove helpful.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the
vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by the
vendor itself.

This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4
drivers.

Which Driver should be Used?


If you are accessing one type of database, such as Oracle, Sybase, or IBM,
the preferred driver type is 4.

If your Java application is accessing multiple types of databases at the


same time, type 3 is the preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is


not available yet for your database.

The type 1 driver is not considered a deployment-level driver, and is


typically used for development and testing purposes only.

You might also like