You are on page 1of 147

PROGRAMMING IN JAVA – U19ITT42

Course Outcomes
 CO1: Explain the basic concepts of Object Oriented
programming used in java. (K1)
 CO2: Demonstrate the use of inheritance, interface and
package in relevant applications. (K3)
 CO3: Build java applications using exception handling,
thread and generic programming. (K3)
 CO4: Build java distributed applications using Collections
and IO streams. (K3)
 CO5: Exemplify simple graphical user interfaces using
GUI components. (K2)

2
Syllabus
 UNIT I- INTRODUCTION TO JAVAPROGRAMMING
 The History and Evolution of Java - Byte code - Java buzzwords - Data types – Variables – Arrays –
operators - Control statements - Type conversion and casting. Concepts of classes and objects: Basic
Concepts of OOPs – Constructors - Static keyword - Final with data - Access control - This key word -
Garbage collection - Nested classes and inner classes - String class.
 UNIT II- INHERITANCE, PACKAGES AND INTERFACES
 Inheritance: Basic concepts - Forms of inheritance - Super key word – Method overriding - Abstract
classes- Dynamic method dispatch - The Object class. Packages: Defining, Creating and Accessing -
Importing packages. Interfaces: Defining – Implementing – Applying - Variables and extending interfaces
 UNIT III- EXCEPTIONHANDLING,MULTITHREADING
 Concepts of Exception handling - Types of exceptions - Creating own exception - Concepts of
Multithreading - Creating multiple threads – Synchronization - Inter thread communication -
Enumeration - Autoboxing - Generics.
 UNIT IV –COLLECTIONS,I/OSTREAMS
 Collections: List –Vector – Stack - Queue – Deque –Set - SortedSet. Input / Output Basics – Streams –
Byte streams and Character streams – Reading and Writing Console – Reading and Writing Files.
 UNIT V – EVENT DRIVEN PROGRAMMINGAND JDBC
 Events - Delegation event model - Event handling - Adapter classes. AWT: Concepts of components - Font
class - Color class and Graphics - Introduction to Swing – Layout management - Swing Components -
Java Database Connectivity - Programming Example.

3
Text Books and References
 Text Books:
 Herbert Schildt, Java: The Complete Reference 11th Edition, TMH
Publishing Company Ltd, 2018.
 Reference Books:
 Cay S. Horstmann, Gary cornell, Core Java Volume – I Fundamentals, 9th Edition, Prentice
Hall,2013.
 H.M.Dietel and P.J.Dietel, Java How to Program, 11th Edition, Pearson Education/
PHI,2017.
 Cay.S.Horstmann and Gary Cornell, Core Java, Vol 2, Advanced Features, 8th Edition,
Pearson Education, 2008.
 Websites:
 http://www.ibm.com/developerworks/java/
 http://docs.oracle.com/javase/tutorial/rmi/.
 IBM’s tutorials on Swings, AWT controls and JDBC.
 https://www.edureka.co/blog
 https://www.geeksforgeeks.org

4
UNIT IV

 UNIT IV –COLLECTIONS,I/OSTREAMS
 Collections: List –Vector – Stack - Queue – Deque –Set -
SortedSet.
 Input / Output Basics – Streams – Byte streams and Character
streams – Reading and Writing Console – Reading and Writing
Files.

5
Collections in Java
 The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
 Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
 Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
 What is Collection in Java
 A Collection represents a single unit of objects, i.e., a group.
 What is a framework in Java
 It provides readymade architecture.
 It represents a set of classes and interfaces.
 It is optional.
 What is Collection framework
 The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
 Interfaces and its implementations, i.e., classes
 Algorithm
6
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the
Collection framework.

7
Methods of Collection interface
 There are many methods declared in the Collection interface. They
are as follows:
No Method Description

1 public boolean add(E e) It is used to insert an element in this


collection.

2 public boolean It is used to insert the specified collection


addAll(Collection<? extends elements in the invoking collection.
E> c)
3 public boolean remove(Object It is used to delete an element from the
element) collection.

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


removeAll(Collection<?> c) specified collection from the invoking
collection.

5 default boolean It is used to delete all the elements of the


removeIf(Predicate<? super collection that satisfy the specified
E> filter) predicate.

8
6 public boolean retainAll(Collection<? It is used to delete all the elements of
> c) invoking collection except the specified
collection.

7 public int size() It returns the total number of elements


in the collection.

8 public void clear() It removes the total number of


elements from the collection.

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


element)

10 public boolean It is used to search the specified


containsAll(Collection<?> c) collection in the collection.

11 public Iterator iterator() It returns an iterator.


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

9
13 public <T> T[] toArray(T[] a) It converts collection into array.
Here, the runtime type of the
returned array is that of the
specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel
Stream with the collection as its
source.
16 default Stream<E> stream() It returns a sequential Stream with
the collection as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the
specified elements in the
collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of
the collection.

10
Iterator interface
 Iterator interface provides the facility of iterating the elements in a
forward direction only.
 Methods of Iterator interface
 There are only three methods in the Iterator interface. They are:
No Method Description

1 public boolean hasNext() It returns true if the iterator has more


elements otherwise it returns false.
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 less used.

11
Iterable Interface
 The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.
 It contains only one abstract method. i.e.,
 Iterator<T> iterator()  
 It returns the iterator over the elements of type T.

Collection Interface
 The Collection interface is the interface which is implemented by all the
classes in the collection framework. It declares the methods that every
collection will have. In other words, we can say that the Collection
interface builds the foundation on which the collection framework
depends.
 Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented
by all the subclasses of Collection interface.

12
List Interface
 List interface is the child interface of Collection interface. It inhibits a
list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.
 List interface is implemented by the classes ArrayList, LinkedList,
Vector, and Stack.
 To instantiate the List interface, we must use :
 List <data-type> list1= new ArrayList();  
 List <data-type> list2 = new LinkedList();  
 List <data-type> list3 = new Vector();  
 List <data-type> list4 = new Stack();  
 There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.

13
The classes that implement the List interface are given
below.
 ArrayList
 The ArrayList class implements the List interface. It uses a dynamic array to
store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored in
the ArrayList class can be randomly accessed. Consider the following example.
 import java.util.*;  
 class TestJavaCollection1
 {  
 public static void main(String args[]){  
 ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
 list.add("Ravi");//Adding object in arraylist  
 list.add("Vijay");  
 list.add("Ravi");  
 list.add("Ajay");  

14
 //Traversing list through Iterator  
 Iterator itr=list.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 }  
 }  

 Output:
 Ravi
 Vijay
 Ravi
 Ajay

15
LinkedList
 LinkedList implements the Collection interface. It uses a doubly linked list
internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.

 Consider the following example.


 import java.util.*;  
 public class TestJavaCollection2{  
 public static void main(String args[]){  
 LinkedList<String> al=new LinkedList<String>();  
 al.add("Ravi");  
 al.add("Vijay");  
 al.add("Ravi");  
 al.add("Ajay");  

16
 Iterator<String> itr=al.iterator();
 while(itr.hasNext()){
 System.out.println(itr.next());
 }
 }
 }

 Output:
 Ravi
 Vijay
 Ravi
 Ajay
17
Vector
 Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods
that are not the part of Collection framework.
 Consider the following example.
 import java.util.*;  
 public class TestJavaCollection3{  
 public static void main(String args[]){  
 Vector<String> v=new Vector<String>();  
 v.add("Ayush");  
 v.add("Amit");  
 v.add("Ashish");  
 v.add("Garima");  

18
 Iterator<String> itr=v.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 }  
 }
   
 Output:
 Ayush
 Amit
 Ashish
 Garima
19
Stack
 The stack is the subclass of Vector. It implements the last-in-first-out data
structure, i.e., Stack. The stack contains all of the methods of Vector class
and also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.
 Consider the following example.
 import java.util.*;  
 public class TestJavaCollection4{  
 public static void main(String args[]){  
 Stack<String> stack = new Stack<String>();  
 stack.push("Ayush");  
 stack.push("Garvit");  
 stack.push("Amit");  
 stack.push("Ashish");  
 stack.push("Garima");  
 stack.pop();  
20
 Iterator<String> itr=stack.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 }  
 } 
  
 Output:
 Ayush
 Garvit
 Amit
 Ashish
21
Queue Interface
 Queue interface maintains the first-in-first-out order. It can
be defined as an ordered list that is used to hold the
elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.
 Queue interface can be instantiated as:
 Queue<String> q1 = new PriorityQueue();  
 Queue<String> q2 = new ArrayDeque();  
 There are various classes that implement the Queue
interface, some of them are given below.

22
PriorityQueue
 The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow
null values to be stored in the queue. Consider the following example.
 import java.util.*;  
 public class TestJavaCollection5{  
 public static void main(String args[]){  
 PriorityQueue<String> queue=new PriorityQueue<String>();  
 queue.add("Amit Sharma");  
 queue.add("Vijay Raj");  
 queue.add("JaiShankar");  
 queue.add("Raj");  
 System.out.println("head:"+queue.element());  
 System.out.println("head:"+queue.peek());  
 System.out.println("iterating the queue elements:");  
23
 Iterator itr=queue.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 queue.remove();  
 queue.poll();  
 System.out.println("after removing two elements:");  
Output:
 Iterator<String> itr2=queue.iterator();   head:Amit Sharma head:Amit Sharma
 while(itr2.hasNext()){   iterating the queue elements:
Amit Sharma
 System.out.println(itr2.next());   Raj JaiShankar
 }   Vijay Raj
after removing two elements:
 }   Raj
Vijay Raj
 }  
24
Deque Interface
 Deque interface extends the Queue interface. In Deque, we can
remove and add the elements from both the side. Deque stands for a
double-ended queue which enables us to perform the operations at
both the ends.
 Deque can be instantiated as:
 Deque d = new ArrayDeque();  

25
ArrayDeque
 ArrayDeque class implements the Deque interface. It facilitates us to use the
Deque. Unlike queue, we can add or delete the elements from both the ends.
 ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.
 Consider the following example.
 import java.util.*;  
 public class TestJavaCollection6{  
 public static void main(String[] args) {  
 //Creating Deque and adding elements  
 Deque<String> deque = new ArrayDeque<String>();  
 deque.add("Gautam");  
 deque.add("Karan");  
 deque.add("Ajay");  

26
 //Traversing elements  
 for (String str : deque) {  
 System.out.println(str);  
 }  
 }  
 }  

 Output:
 Gautam
 Karan
 Ajay

27
Set Interface
 Set Interface in Java is present in java.util package. It extends the
Collection interface. It represents the unordered set of elements which
doesn't allow us to store the duplicate items. We can store at most one
null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.

 Set can be instantiated as:


 Set<data-type> s1 = new HashSet<data-type>();  
 Set<data-type> s2 = new LinkedHashSet<data-type>();  
 Set<data-type> s3 = new TreeSet<data-type>();  

28
HashSet
 HashSet class implements Set Interface. It represents the collection that
uses a hash table for storage. Hashing is used to store the elements in the
HashSet. It contains unique items.
 Consider the following example.
 import java.util.*;  
 public class TestJavaCollection7{  
 public static void main(String args[]){  
 //Creating HashSet and adding elements  
 HashSet<String> set=new HashSet<String>();  
 set.add("Ravi");  
 set.add("Vijay");  
 set.add("Ravi");  
 set.add("Ajay");  
29
 //Traversing elements  
 Iterator<String> itr=set.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 }  
 }  

 Output:
 Vijay
 Ravi
 Ajay

30
LinkedHashSet
 LinkedHashSet class represents the LinkedList implementation of Set
Interface. It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements. It maintains the
insertion order and permits null elements.
 Consider the following example.
 import java.util.*;  
 public class TestJavaCollection8{  
 public static void main(String args[]){  
 LinkedHashSet<String> set=new LinkedHashSet<String>();  
 set.add("Ravi");  
 set.add("Vijay");  
 set.add("Ravi");  
 set.add("Ajay");  
31
 Iterator<String> itr=set.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 }  
 } 
  
 Output:
 Ravi
 Vijay
 Ajay

32
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 can be instantiated as:
 SortedSet<data-type> set = new TreeSet();  

33
TreeSet
 Java TreeSet class implements the Set interface that uses a tree for storage.
Like HashSet, TreeSet also contains unique elements. However, the access
and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in
ascending order.
 Consider the following example:
 import java.util.*;
 public class TestJavaCollection9{
 public static void main(String args[]){
 //Creating and adding elements
 TreeSet<String> set=new TreeSet<String>();
 set.add("Ravi");
 set.add("Vijay");
 set.add("Ravi");
 set.add("Ajay");

34
 //traversing elements
 Iterator<String> itr=set.iterator();
 while(itr.hasNext()){
 System.out.println(itr.next());
 }
 }
 }

 Output:
 Ajay
 Ravi
 Vijay
35
Java ArrayList
 Java ArrayList class uses a dynamic array for storing the elements.
It is like an array, but there is no size limit.
 We can add or remove elements anytime. So, it is much more flexible
than the traditional array.
 It is found in the java.util package.
 The ArrayList in Java can have the duplicate elements also.
 It implements the List interface so we can use all the methods of List
interface here.
 The ArrayList maintains the insertion order internally.
 It inherits the AbstractList class and implements List interface.

36
The important points about Java ArrayList class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the
index basis.
 In ArrayList, manipulation is little bit slower than the LinkedList in
Java because a lot of shifting needs to occur if any element is
removed from the array list.

37
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 a collection. Now it is type safe so typecasting is not
required at runtime.
 Let's see the old non-generic example of creating java collection.
 ArrayList list=new ArrayList();//creating old non-generic arraylist  
 Let's see the new generic example of creating java collection.
 ArrayList<String> list=new ArrayList<String>();//
creating new generic arraylist  
 In a generic collection, we specify the type in angular braces. Now
ArrayList is forced to have the only specified type of objects in it. If
you try to add another type of object, it gives compile time error.

38
 Example of Array List
 //The get() method returns the element at the specified index,
 //whereas the set() method changes the element.
 import java.util.*;
 public class ArrayListExample4
 {
 public static void main(String args[])
 {
 ArrayList<String> al=new ArrayList<String>();
 al.add("Mango");
 al.add("Apple");
 al.add("Banana");
 al.add("Grapes");
 //accessing the element
 System.out.println("Returning element: "+al.get(1));
 //changing the element
 al.set(1,"Dates");
 //Traversing list
 for(String fruit:al)
 System.out.println(fruit);
 }
 }
39
 Example 2
 /* Ways to iterate the elements of the collection in Java
 There are various ways to traverse the collection elements:
 By Iterator interface, By for-each loop. By ListIterator interface. By for loop.
 By forEach() method.
 By forEachRemaining() method.*/
 import java.util.*;
 class ArrayList4{
 public static void main(String args[]){
 ArrayList<String> list=new ArrayList<String>();//Creating arraylist
 list.add("Ravi");//Adding object in arraylist
 list.add("Vijay");
 list.add("Ravi");
 list.add("Ajay");
 System.out.println("Traversing list through List Iterator:");
 //Here, element iterates in reverse order
 ListIterator<String> list1=list.listIterator(list.size());
 while(list1.hasPrevious())
 {
 String str=list1.previous();
 System.out.println(str);
 }
40
 System.out.println("Traversing list through for loop:");
 for(int i=0;i<list.size();i++)
 {
 System.out.println(list.get(i));
 }
 System.out.println("Traversing list through forEach() method:");
 //The forEach() method is a new feature, introduced in Java 8.
 list.forEach(a->{ //Here, we are using lambda expression
 System.out.println(a);
 });
 System.out.println("Traversing list through forEachRemaining() method:");
 Iterator<String> itr=list.iterator();
 itr.forEachRemaining(a-> //Here, we are using lambda expression
 {
 System.out.println(a);
 });
 }
 }

41
 Example 3
 import java.util.*;
 class SortArrayList
 {
 public static void main(String args[])
 {
 //Creating a list of fruits
 List<String> list1=new ArrayList<String>();
 list1.add("Mango");
 list1.add("Apple");
 list1.add("Banana");
 list1.add("Grapes");
 //Sorting the list
 Collections.sort(list1);
 //Traversing list through the for-each loop
 for(String fruit:list1)
 System.out.println(fruit);

42
 System.out.println("Sorting numbers...");
 //Creating a list of numbers
 List<Integer> list2=new ArrayList<Integer>();
 list2.add(21);
 list2.add(11);
 list2.add(51);
 list2.add(1);
 //Sorting the list
 Collections.sort(list2);
 //Traversing list through the for-each loop
 for(Integer number:list2)
 System.out.println(number);
 }
 }

43
Java Vector
 Vector is like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no
size limit. It is a part of Java Collection framework since Java 1.2.
 It is found in the java.util package and implements the List interface,
so we can use all the methods of List interface here.
 It is similar to the ArrayList, but with two differences-
 Vector is synchronized.
 Java Vector contains many legacy methods that are not the part of a collections
framework.

44
Java Vector Methods
SN Method Description
1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the
end of this Vector.

3) addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.


7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specified
collection.
9) copyInto() It is used to copy the components of the vector into the specified array.

10) elementAt() It is used to get the component at the specified index.

45
11) elements() It returns an enumeration of the components of a vector.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use,
if necessary. It ensures that the vector can hold at least the
number of components specified by the minimum capacity
argument.
13) equals() It is used to compare the specified object with the vector for
equality.
14) firstElement() It is used to get the first component of the vector.
15) forEach() It is used to perform the given action for each element of the
Iterable until all elements have been processed or the action
throws an exception.
16) get() It is used to get an element at the specified position in the
vector.
17) hashCode() It is used to get the hash code value of a vector.
18) indexOf() It is used to get the index of the first occurrence of the specified
element in the vector. It returns -1 if the vector does not
contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the
given vector at the specified index.
20) isEmpty() It is used to check if this vector has no components.

46
21) iterator() It is used to get an iterator over the elements in the list in
proper sequence.
22) lastElement() It is used to get the last component of the vector.
23) lastIndexOf() It is used to get the index of the last occurrence of the
specified element in the vector. It returns -1 if the vector
does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in
proper sequence.
25) remove() It is used to remove the specified element from the vector.
If the vector does not contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are
present in the specified collection.
27) removeAllElements() It is used to remove all elements from the vector and set
the size of the vector to zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of
the argument from the vector.
29) removeElementAt() It is used to delete the component at the specified index.
30) removeIf() It is used to remove all of the elements of the collection that
satisfy the given predicate.
31) removeRange() It is used to delete all of the elements from the vector
whose index is between fromIndex, inclusive and toIndex,
exclusive.
32) replaceAll() It is used to replace each element of the list with the result
of applying the operator to that element.
47
33) retainAll() It is used to retain only that element in the vector which is
contained in the specified collection.
34) set() It is used to replace the element at the specified position in the
vector with the specified element.
35) setElementAt() It is used to set the component at the specified index of the vector
to the specified object.
36) setSize() It is used to set the size of the given vector.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the
specified Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the
elements in the list.
40) subList() It is used to get a view of the portion of the list between
fromIndex, inclusive, and toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this
vector in correct order.
42) toString() It is used to get a string representation of the vector.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current
size.

48
 Example
 import java.util.*;
 public class VectorExample1
 {
 public static void main(String args[])
 {
 //Create an empty vector with initial capacity 4
 Vector<String> vec = new Vector<String>(4);
 //Adding elements to a vector
 vec.add("Tiger");
 vec.add("Lion");
 vec.add("Dog");
 vec.add("Elephant");
 //Check size and capacity
 System.out.println("Size is: "+vec.size());
 System.out.println("Default capacity is: "+vec.capacity());
 //Display Vector elements
 System.out.println("Vector element is: "+vec);
 vec.addElement("Rat");
 vec.addElement("Cat");
 vec.addElement("Deer");
 //Again check size and capacity after two insertions
 System.out.println("Size after addition: "+vec.size());
 System.out.println("Capacity after addition is: "+vec.capacity());
 //Display Vector elements again
 System.out.println("Elements are: "+vec);
49
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);

50
 //Display the vector elements
 System.out.println("Values in vector: " +in);
 //use remove() method to delete the first occurence of an element
 System.out.println("Remove first occourence of element 200:
"+in.remove((Integer)200));
 //Display the vector elements afre remove() method
 System.out.println("Values in vector: " +in);
 //Remove the element at index 4
 System.out.println("Remove element at index 4: " +in.remove(4));
 System.out.println("New Value list in vector: " +in);
 //Remove an element
 in.removeElementAt(5);
 //Checking vector and displays the element
 System.out.println("Vector element after removal: " +in);
 //Get the hashcode for this vector
 System.out.println("Hash code of this vector = "+in.hashCode());
 //Get the element at specified index
 System.out.println("Element at index 1 is = "+in.get(1));
 }
}
51
Java Stack
 The stack is a linear data structure that is used to store the collection of objects. It
is based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
 In this section, we will discuss the Java Stack class,
its methods, and implement the stack data structure in a Java program. But before
moving to the Java Stack class have a quick view of how the stack works.
 The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work on
stack.

52
 Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

 Let's remove (pop) 18, 45, and 11 from the stack.

53
 Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.

 When we push an element into the stack the top is increased by 1. In the following figure,
 Push 12, top=0
 Push 6, top=1
 Push 9, top=2

 When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.

 The following table shows the different values of the top.

54
Methods of the Stack Class
 We can perform push, pop, peek and search operation on the stack.
The Java Stack class provides mainly five methods to perform these
operations. Along with this, it also provides all the methods of the 
Java Vector class.
Method Modifier and Method Description
Type
empty() boolean The method checks the stack is empty or not.
push(E item) E The method pushes (insert) an element onto the top
of the stack.
pop() E The method removes an element from the top of the
stack and returns the same element as the value of
that function.
peek() E The method looks at the top element of the stack
without removing it.
search(Object o) int The method searches the specified object and returns
the position of the object.

55
Example of Stack
 import java.util.*;
 class Stackeg
 {
 public static void main(String args[])
 {
 //creating an instance of Stack class
 Stack<Integer> stk= new Stack<>();
 // checking stack is empty or not
 boolean result = stk.empty();
 System.out.println("Is the stack empty? " + result);
 // pushing elements into stack
 stk.push(78);
 stk.push(113);
 stk.push(90);
 stk.push(120);
 //prints elements of the stack
 System.out.println("Elements in Stack: " + stk);

56
 result = stk.empty();
 System.out.println("Is the stack empty? " + result);
 stk.pop();
 System.out.println("Elements in Stack: " + stk);
 // Access element from the top of the stack
 Integer num = stk.peek();
 //prints stack
 System.out.println("Element at top: " + num);
 int location = stk.search(113);
 System.out.println("Location of 113: " + location);
 // Find the size of the Stack
 int x=stk.size();
 System.out.println("The stack size is: "+x);
 }
 }

57
Java Queue Interface
 Java Queue interface orders the element in FIFO(First In First Out)
manner. In FIFO, first element is removed first and last element is
removed at last.
 Methods of Java Queue Interface
Method Description
boolean add(object) It is used to insert the specified element into this queue and
return true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this
queue.
Object peek() It is used to retrieves, but does not remove, the head of this
queue, or returns null if this queue is empty.

58
PriorityQueue class
 The PriorityQueue class provides the facility of using queue. But it
does not orders the elements in FIFO manner. It inherits
AbstractQueue class.
 PriorityQueue class declaration
 Let's see the declaration for java.util.PriorityQueue class.
 public class PriorityQueue<E> extends AbstractQueue<E> impleme
nts Serializable  

59
Java PriorityQueue Example
 import java.util.*;  
 class TestCollection12{  
 public static void main(String args[]){  
 PriorityQueue<String> queue=new PriorityQueue<String>  
 queue.add("Amit");  
 queue.add("Vijay");  
 queue.add("Karan");  
 queue.add("Jai");  
 queue.add("Rahul");  
 System.out.println("head:"+queue.element());  
 System.out.println("head:"+queue.peek());  
 System.out.println("iterating the queue elements:");  
60
 Iterator itr=queue.iterator();  
 while(itr.hasNext()){  
 System.out.println(itr.next());  
 }  
 queue.remove();  
 queue.poll();  
 System.out.println("after removing two elements:");  
Output:head:Amit
 Iterator<String> itr2=queue.iterator();   head:Amit
iterating the queue elements: Amit
 while(itr2.hasNext()){   Jai Karan
 System.out.println(itr2.next());   Vijay
Rahul
 }   after removing two elements: Karan
Rahul
 }   Vijay
 }  
61
Java Deque Interface
 Java Deque Interface is a linear collection that supports element
insertion and removal at both ends. Deque is an acronym for "double
ended queue".
 Methods of Java Deque Interface
Method Description
boolean add(object) It is used to insert the specified element into this deque
and return true upon success.
boolean offer(object) It is used to insert the specified element into this deque.
Object remove() It is used to retrieves and removes the head of this deque.
Object poll() It is used to retrieves and removes the head of this deque,
or returns null if this deque is empty.
Object element() It is used to retrieves, but does not remove, the head of
this deque.
Object peek() It is used to retrieves, but does not remove, the head of
this deque, or returns null if this deque is empty.

62
ArrayDeque class
 The ArrayDeque class provides the facility of using deque and
resizable-array. It inherits AbstractCollection class and implements
the Deque interface.
The important points about ArrayDeque class are:
 Unlike Queue, we can add or remove elements from both sides.
 Null elements are not allowed in the ArrayDeque.
 ArrayDeque is not thread safe, in the absence of external
synchronization.
 ArrayDeque has no capacity restrictions.
 ArrayDeque is faster than LinkedList and Stack.

63
Java ArrayDeque Example
 import java.util.*;  
 public class DequeExample {  
 public static void main(String[] args) {  
     Deque<String> deque=new ArrayDeque<String>();  
     deque.offer("arvind");  
     deque.offer("vimal");  
     deque.add("mukul");  
     deque.offerFirst("jai");  
     System.out.println("After offerFirst Traversal...");  
     for(String s:deque){  
         System.out.println(s);  
     }  
    
64
  //deque.poll();  
     //deque.pollFirst();//it is same as poll()  
     deque.pollLast();  
     System.out.println("After pollLast() Traversal...");  
     for(String s:deque){  
         System.out.println(s);  
     }   Output:
After offerFirst Traversal...
 }   jai
arvind
 }   vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

65
Java HashSet
 Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
 The important points about Java HashSet class are:
 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only.
 HashSet allows null value.
 HashSet class is non synchronized.
 HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
 HashSet is the best approach for search operations.
 The initial default capacity of HashSet is 16, and the load factor is 0.75.
 Difference between List and Set
 A list can contain duplicate elements whereas Set contains unique elements
only.

66
 Methods of Java HashSet class
 Various methods of Java HashSet class are as follows:
SN Modifier & Type Method Description
1) boolean add(E e) It is used to add the specified element to this set if it is not
already present.
2) void clear() It is used to remove all of the elements from the set.

3) object clone() It is used to return a shallow copy of this HashSet instance:


the elements themselves are not cloned.

4) boolean contains(Object o) It is used to return true if this set contains the specified
element.
5) boolean isEmpty() It is used to return true if this set contains no elements.

6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.

7) boolean remove(Object o) It is used to remove the specified element from this set if it
is present.
8) int size() It is used to return the number of elements in the set.

9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator


over the elements in the set.

67
Java HashSet example 
 import java.util.*;  
 class HashSet3{  
  public static void main(String args[]){  
   HashSet<String> set=new HashSet<String>();  
            set.add("Ravi");  
            set.add("Vijay");  
            set.add("Arun");  
            set.add("Sumit");  
            System.out.println("An initial list of elements: "+set);  
            //Removing specific element from HashSet  
            set.remove("Ravi");  
            System.out.println("After invoking remove(object) method: "+set);  
            HashSet<String> set1=new HashSet<String>();  
            set1.add("Ajay");  
            set1.add("Gaurav");  
            set.addAll(set1);  
            System.out.println("Updated List: "+set);  
         
68
    //Removing all the new elements from HashSet  
            set.removeAll(set1);  
            System.out.println("After invoking removeAll() method: "+set);  
            //Removing elements on the basis of specified condition  
            set.removeIf(str->str.contains("Vijay"));    
            System.out.println("After invoking removeIf() method: "+set);  
            //Removing all the elements available in the set  
            set.clear();  
            System.out.println("After invoking clear() method: "+set);  
  }  
 }   OUTPUT
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

69
Java TreeSet class
 Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet
interface. The objects of the TreeSet class are stored in ascending
order.
 The important points about Java TreeSet class are:
 Java TreeSet class contains unique elements only like HashSet.
 Java TreeSet class access and retrieval times are quiet fast.
 Java TreeSet class doesn't allow null element.
 Java TreeSet class is non synchronized.
 Java TreeSet class maintains ascending order.

70
Methods of Java TreeSet class
Method Description

boolean add(E e) It is used to add the specified element to this set if it is not
already present.
boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified collection
to this set.
E ceiling(E e) It returns the equal or closest greatest element of the
specified element from the set, or null there is no such
element.
Comparator<? super E> comparator() It returns comparator that arranged elements in order.

Iterator descendingIterator() It is used iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.


E floor(E e) It returns the equal or closest least element of the specified
element from the set, or null there is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less than the
specified element.
NavigableSet headSet(E toElement, boolean It returns the group of elements that are less than or equal
inclusive) to(if, inclusive is true) the specified element.

71
E higher(E e) It returns the closest greatest element of the specified
element from the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.

E lower(E e) It returns the closest least element of the specified


element from the set, or null there is no such element.

E pollFirst() It is used to retrieve and remove the lowest(first)


element.
E pollLast() It is used to retrieve and remove the highest(last)
element.
Spliterator spliterator() It is used to create a late-binding and fail-fast
spliterator over the elements.
NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.

72
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or
equal to the specified element.
NavigableSet tailSet(E fromElement, boolean It returns a set of elements that are greater than or
inclusive) equal to (if, inclusive is true) the specified element.

boolean contains(Object o) It returns true if this set contains the specified


element.
boolean isEmpty() It returns true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this
set if it is present.
void clear() It is used to remove all of the elements from this
set.
Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this


sorted set.
E last() It returns the last (highest) element currently in
this sorted set.
int size() It returns the number of elements in this set.

73
 Java TreeSet Example
 import java.util.*;
 class TestCollection11{
 public static void main(String args[]){
 TreeSet<String> al=new TreeSet<String>();
 al.add("Ravi");
 al.add("Vijay");
 al.add("Ravi");
 al.add("Ajay");
 Iterator<String> itr=al.iterator();
 while(itr.hasNext()){
 System.out.println(itr.next());
 }
 TreeSet<Integer> set=new TreeSet<Integer>();
 set.add(24);
 set.add(66);
 set.add(12);
 set.add(15);
 System.out.println("Highest Value: "+set.pollFirst());
 System.out.println("Lowest Value: "+set.pollLast());
 }
74
OUTPUT
 TreeSet<String> set1=new TreeSet<String>(); Ajay
 set1.add("A"); Ravi
Vijay
 set1.add("B"); Highest Value: 12
Lowest Value: 66
 set1.add("C"); Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
 set1.add("D"); Head Set: [A, B, C]
SubSet: [B, C, D, E]
 set1.add("E"); TailSet: [D, E]
 System.out.println("Initial Set: "+set1);
 System.out.println("Reverse Set: "+set1.descendingSet());
 System.out.println("Head Set: "+set1.headSet("C", true));
 System.out.println("SubSet: "+set1.subSet("A", false, "E", true));
 System.out.println("TailSet: "+set1.tailSet("C", false));
 }

75
Input / Output Basics
 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
 We can perform file handling in Java by Java I/O API.
 Stream
 A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
 In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
 1) System.out: standard output stream
 2) System.in: standard input stream
 3) System.err: standard error stream

76
 Let's see the code to print output and an error message to the
console.
 System.out.println("simple message");  
 System.err.println("error message");  
 Let's see the code to get input from console.
 int i=System.in.read();//returns ASCII code of 1st character  
 System.out.println((char)i);//will print the character  

77
OutputStream vs InputStream
 The explanation of OutputStream and InputStream classes are given below:
 OutputStream
 Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
 InputStream
 Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
 Let's understand the working of Java OutputStream and InputStream by the figure given
below.

78
OutputStream class
 OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.
 Useful methods of OutputStream
Method Description

1) public void write(int)throws is used to write a byte to the current output stream.
IOException

2) public void is used to write an array of byte to the current output


write(byte[])throws IOException stream.

3) public void flush()throws flushes the current output stream.


IOException
4) public void close()throws is used to close the current output stream.
IOException

79
 OutputStream Hierarchy

80
InputStream class
 InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
 Useful methods of InputStream

Method Description
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes
that can be read from the current input
stream.

3) public void close()throws IOException is used to close the current input stream.

81
 InputStream Hierarchy

82
Byte array stream and Character array stream

83
Byte array stream Versus Character
array stream

84
Java FileOutputStream Class
 Java FileOutputStream is an output stream used for writing data to a file.
 If you have to write primitive values into a file, use FileOutputStream class. You
can write byte-oriented as well as character-oriented data through FileOutputStream
class. But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
 FileOutputStream class declaration
 public class FileOutputStream extends OutputStream  
 FileOutputStream class methods
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.


85
Java FileOutputStream Example 1: write byte
 import java.io.FileOutputStream;  
 public class FileOutputStreamExample {  
     public static void main(String args[]){    
            try{    
              FileOutputStream fout=new FileOutputStream("D:\\
testout.txt");    
              fout.write(65);    
              fout.close();    
              System.out.println("success...");    
             }catch(Exception e){System.out.println(e);}    
       }    
 }  
86
Java FileOutputStream example 2: write string
 import java.io.FileOutputStream;  
 public class FileOutputStreamExample {  
     public static void main(String args[])
 {    
            try
 {    
              FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    
              String s="Welcome to javaTpoint.";    
              byte b[]=s.getBytes();//converting string into byte array    
              fout.write(b);    
              fout.close();    
              System.out.println("success...");    
             }catch(Exception e){System.out.println(e);}    
       }    
 }  
87
Java FileInputStream Class
 Java FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
 Java FileInputStream class declaration
 public class FileInputStream extends InputStream  
 Java FileInputStream class methods
Method Description
int available() It is used to return the estimated number of bytes that can be read from the
input stream.
int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int off, int It is used to read up to len bytes of data from the input stream.
len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.

FileChannel getChannel() It is used to return the unique FileChannel object associated with the file
input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.
88
void close() It is used to closes the stream.
Java FileInputStream example 1: read single character
 import java.io.FileInputStream;  
 public class DataStreamExample {  
      public static void main(String args[])
 {    
           try
 {    
  FileInputStream fin=new FileInputStream("D:\\testout.txt");    
  int i=fin.read();     
 System.out.print((char)i);    
               fin.close();    
           }
 catch(Exception e){System.out.println(e);}    
          }    
         }
 Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we
are having following content:

89
Java FileInputStream example 2: read all characters
 import java.io.FileInputStream;  
 public class DataStreamExample {  
      public static void main(String args[]){    
           try{    
             FileInputStream fin=new FileInputStream("D:\\testout.txt");    
             int i=0;    
             while((i=fin.read())!=-1){    
              System.out.print((char)i);    
             }    
             fin.close();    
           }catch(Exception e){System.out.println(e);}    
          }    
         }  
90
Java BufferedOutputStream Class
 Java BufferedOutputStream class is used for buffering an output stream. It
internally uses buffer to store data. It adds more efficiency than to write data
directly into a stream. So, it makes the performance fast.
 For adding the buffer in an OutputStream, use the BufferedOutputStream class.
Let's see the syntax for adding the buffer in an OutputStream:
 OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\
IO Package\\testout.txt"));  
 Java BufferedOutputStream class declaration
 public class BufferedOutputStream extends FilterOutputStream  
 Java BufferedOutputStream class constructors
Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which


is used for writing the data to the specified
output stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which
is used for writing the data to the specified
output stream with a specified buffer size.

91
Java BufferedOutputStream class methods
Method Description
void write(int b) It writes the specified byte to the buffered
output stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-
input stream into a specified byte array,
starting with the given offset
void flush() It flushes the buffered output stream.

92
 Example of BufferedOutputStream class:
 In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
 import java.io.*;  
 public class BufferedOutputStreamExample
 {    
 public static void main(String args[])throws Exception{    
      FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    
      BufferedOutputStream bout=new BufferedOutputStream(fout);    
      String s="Welcome to javaTpoint.";    
      byte b[]=s.getBytes();    
      bout.write(b);    
      bout.flush();    
      bout.close();    
      fout.close();    
      System.out.println("success");    
 }    
 }  
93
Java BufferedInputStream Class
 Java BufferedInputStream class is used to read information from stream. It
internally uses buffer mechanism to make the performance fast.
 The important points about BufferedInputStream are:
 When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
 When a BufferedInputStream is created, an internal buffer array is created.

 Java BufferedInputStream class declaration


 public class BufferedInputStream extends FilterInputStream  
 Java BufferedInputStream class constructors
Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and
saves it argument, the input stream IS,
for later use.
BufferedInputStream(InputStream IS, int It creates the BufferedInputStream with a
size) specified buffer size and saves it
argument, the input stream IS, for later
use.
94
Java BufferedInputStream class
methods
Method Description
int available() It returns an estimate number of bytes that can be read
from the input stream without blocking by the next
invocation method for the input stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream
into a specified byte array, starting with the given offset.

void close() It closes the input stream and releases any of the system
resources associated with the stream.

void reset() It repositions the stream at a position the mark method


was last called on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the
input stream.
long skip(long x) It skips over and discards x bytes of data from the input
stream.
boolean markSupported() It tests for the input stream to support the mark and
reset methods.
95
 Example of Java BufferedInputStream
 import java.io.*;  
 public class BufferedInputStreamExample{    
  public static void main(String args[]){    
   try{    
     FileInputStream fin=new FileInputStream("D:\\testout.txt");    
     BufferedInputStream bin=new BufferedInputStream(fin);    
     int i;    
     while((i=bin.read())!=-1){    
      System.out.print((char)i);    
     }    
     bin.close();    
     fin.close();    
   }catch(Exception e){System.out.println(e);}    
  }    
 }  

96
Java DataOutputStream Class
 Java DataOutputStream class allows an application to write primitive 
Java data types to the output 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.
 Java DataOutputStream class declaration
 public class DataOutputStream extends FilterOutputStream 
implements DataOutput  

97
Java DataOutputStream class methods
Method Description
int size() It is used to return the number of bytes written to the data output
stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.

void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.

void writeChar(int v) It is used to write char to the output stream as a 2-byte value.

void writeChars(String s) It is used to write string to the output stream as a sequence of


characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.

void writeBytes(String s) It is used to write string to the output stream as a sequence of


bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.
98
Example of DataOutputStream class
 import java.io.*;  
 public class OutputExample {  
     public static void main(String[] args) throws IOException {  
         FileOutputStream file = new FileOutputStream(D:\\testout.txt);  
         DataOutputStream data = new DataOutputStream(file);  
         data.writeInt(65);  
         data.flush();  
         data.close();  
         System.out.println("Succcess...");  
     }  
 }  

99
Java DataInputStream Class
 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.
 Java DataInputStream class declaration
 public class DataInputStream extends FilterInputStream implements
 DataInput  

100
Java DataInputStream class Methods
Method Description
int read(byte[] b) It is used to read the number of bytes from the
input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input
stream.
int readInt() It is used to read input bytes and return an int
value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a
double value.
boolean readBoolean() It is used to read one input byte and return true if
byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.
String readUTF() It is used to read a string that has been encoded
using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and
store them into the buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.
101
Example of DataInputStream class
 In this example, we are reading the data from the file testout.txt file.
 import java.io.*;    
 public class DataStreamExample {  
   public static void main(String[] args) throws IOException {  
     InputStream input = new FileInputStream("D:\\testout.txt");  
     DataInputStream inst = new DataInputStream(input);  
     int count = input.available();  
     byte[] ary = new byte[count];  
     inst.read(ary);  
     for (byte bt : ary) {  
       char k = (char) bt;  
       System.out.print(k+"-");  
     }  
   }  
 }  

102
Java FilterOutputStream Class
 Java FilterOutputStream class implements the OutputStream class. It provides
different sub classes such as BufferedOutputStream and DataOutputStream to
provide additional functionality. So it is less used individually.
 Java FilterOutputStream class declaration
 public class FilterOutputStream extends OutputStream  
 Java FilterOutputStream class Methods

Method Description

void write(int b) It is used to write the specified byte to


the output stream.

void write(byte[] ary) It is used to write ary.length byte to the


output stream.

void write(byte[] b, int off, int len) It is used to write len bytes from the
offset off to the output stream.

void flush() It is used to flushes the output stream.

void close() It is used to close the output stream.

103
Example of FilterOutputStream class
 import java.io.*;  
 public class FilterExample {  
     public static void main(String[] args) throws IOException {  
         File data = new File("D:\\testout.txt");  
         FileOutputStream file = new FileOutputStream(data);  
         FilterOutputStream filter = new FilterOutputStream(file);  
         String s="Welcome to javaTpoint.";      
         byte b[]=s.getBytes();      
         filter.write(b);     
         filter.flush();  
         filter.close();  
         file.close();  
         System.out.println("Success...");  
     }  
 }  

104
Java FilterInputStream Class
 Java FilterInputStream class implements the InputStream. It contains
different sub classes as BufferedInputStream, DataInputStream for
providing additional functionality. So it is less used individually.
 Java FilterInputStream class declaration
 public class FilterInputStream extends InputStream  
 Java FilterInputStream class Methods
Method Description
int available() It is used to return an estimate number of bytes that can be read from
the input stream.
int read() It is used to read the next byte of data from the input stream.

int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream.

long skip(long n) It is used to skip over and discards n bytes of data from the input
stream.
boolean markSupported() It is used to test if the input stream support mark and reset method.

void mark(int readlimit) It is used to mark the current position in the input stream.

void reset() It is used to reset the input stream.


void close() It is used to close the input stream.

105
Example of FilterInputStream class
 import java.io.*;  
 public class FilterExample {  
     public static void main(String[] args) throws IOException {  
         File data = new File("D:\\testout.txt");  
         FileInputStream  file = new FileInputStream(data);  
         FilterInputStream filter = new BufferedInputStream(file);  
         int k =0;  
         while((k=filter.read())!=-1){  
             System.out.print((char)k);  
         }  
         file.close();  
         filter.close();  
     }  
 }  

106
Java - ObjectStreamClass
 ObjectStreamClass act as a Serialization descriptor for class. This class contains the
name and serialVersionUID of the class.
 Fields
Modifier and Type Field Description

static ObjectStreamField[] NO_FIELDS serialPersistentFields value indicating no serializable fields


 Methods
Modifier and Type Method Description
Class<?> forClass() It returns the class in the local VM that this
version is mapped to.
ObjectStreamField getField(String name) It gets the field of this class by name.

ObjectStreamField[] getFields() It returns an array of the fields of this serialization


class.
String getName() It returns the name of the class described by this
descriptor.
long getSerialVersionUID() It returns the serialVersionUID for this class.

Static ObjectStreamClass lookup(Class<?> cl) It finds the descriptor for a class that can be
serialized.
Static ObjectStreamClass lookupAny(Class<?> cl) It returns the descriptor for any class, regardless
of whether it implements Serializable.
String toString() It returns a string describing this
107 ObjectStreamClass.
 import java.io.ObjectStreamClass;  
 import java.util.Calendar;  
 public class ObjectStreamClassExample {  
     public static void main(String[] args) {  
   
         // create a new object stream class for Integers  
         ObjectStreamClass osc = ObjectStreamClass.lookup(SmartPhone.class);  
   
         // get the value field from ObjectStreamClass for integers  
         System.out.println("" + osc.getField("price"));  
   
         // create a new object stream class for Calendar  
         ObjectStreamClass osc2 = ObjectStreamClass.lookup(String.class);  
   
         // get the Class instance for osc2  
         System.out.println("" + osc2.getField("hash"));  
   
     }  
 }  

108
Java Console Class
 The Java Console class is be used to get input from console. It provides
methods to read texts and passwords.
 If you read password using Console class, it will not be displayed to the
user.
 The java.io.Console class is attached with system console internally. The
Console class is introduced since 1.5.
 Let's see a simple example to read text from console.
 String text=System.console().readLine();    
 System.out.println("Text is: "+text);    
 Java Console class declaration
 public final class Console extends Object implements Flushable  

109
Java Console class methods
Method Description
Reader reader() It is used to retrieve the reader object
 associated with the console
String readLine() It is used to read a single line of text from the
console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the
single line of text from the console.
char[] readPassword() It is used to read password that is not being
displayed on the console.
char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the
args) password that is not being displayed on the
console.
Console format(String fmt, Object... args) It is used to write a formatted string to the
console output stream.
Console printf(String format, Object... args) It is used to write a string to the console
output stream.
PrintWriter writer() It is used to retrieve the PrintWriter object
associated with the console.
void flush()
110 It is used to flushes the console.
How to get the object of Console
 System class provides a static method console() that returns the singleton instance of
Console class.
 public static Console console(){}   
 Let's see the code to get the instance of Console class.
 Console c=System.console();  
 Java Console Example
 import java.io.Console;  
 class ReadStringTest{    
 public static void main(String args[]){    
 Console c=System.console();    
 System.out.println("Enter your name: ");    
 String n=c.readLine();    
 System.out.println("Welcome "+n);    
 }    
 }  
 Output
 Enter your name: Nakul Jain
 Welcome Nakul Jain
111
 Java Console Example to read password
 import java.io.Console;  
 class ReadPasswordTest
 {    
 public static void main(String args[]){    
 Console c=System.console();    
 System.out.println("Enter password: ");    
 char[] ch=c.readPassword();    
 String pass=String.valueOf(ch);//converting char array into string   
 System.out.println("Password is: "+pass);    
 }    
 }  
 Output
 Enter password: Password is: 123

112
Java Reader
 Java Reader is an abstract class for reading character streams. The only methods
that a subclass must implement are read(char[], int, int) and close(). Most
subclasses, however, will override some of the methods to provide higher
efficiency, additional functionality, or both.
 Fields
Modifier and Type Field Description
protected Object lock The object used to synchronize operations on this stream.

 Constructor
Modifier Constructor Description
protected Reader() It creates a new character-stream reader whose
critical sections will synchronize on the reader
itself.

protected Reader(Object lock) It creates a new character-stream reader whose


critical sections will synchronize on the given
object.

113
Methods
Modifier and Type Method Description
abstract void close() It closes the stream and releases any
system resources associated with it.

void mark(int readAheadLimit) It marks the present position in the


stream.
boolean markSupported() It tells whether this stream supports the
mark() operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.

abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of an
array.
int read(CharBuffer target) It attempts to read characters into the
specified character buffer.

boolean ready() It tells whether this stream is ready to


be read.
void reset() It resets the stream.
long skip(long n) It skips characters.
114
Example
 import java.io.*;  
 public class ReaderExample {  
     public static void main(String[] args) {  
         try {  
             Reader reader = new FileReader("file.txt");  
             int data = reader.read();  
             while (data != -1) {  
                 System.out.print((char) data);  
                 data = reader.read();  
             }  
             reader.close();  
         } catch (Exception ex) {  
             System.out.println(ex.getMessage());  
         }  
     }  
 }  

115
Java Writer
 It is an abstract class for writing to character streams. The methods that a subclass
must implement are write(char[], int, int), flush(), and close(). Most subclasses will
override some of the methods defined here to provide higher efficiency,
functionality or both.
 Fields
Modifier and Type Field Description
protected Object lock The object used to synchronize operations on this stream.

 Constructor
Modifier Constructor Description

protected Writer() It creates a new character-stream writer


whose critical sections will synchronize on
the writer itself.
protected Writer(Object It creates a new character-stream writer
lock) whose critical sections will synchronize on
the given object.

116
Methods
Modifier and Type Method Description
Writer append(char c) It appends the specified character to this
writer.
Writer append(CharSequence csq) It appends the specified character sequence
to this writer

Writer append(CharSequence csq, It appends a subsequence of the specified


int start, int end) character sequence to this writer.

abstract void close() It closes the stream, flushing it first.

abstract void flush() It flushes the stream.


void write(char[] cbuf) It writes an array of characters.
abstract void write(char[] cbuf, int off, int It writes a portion of an array of characters.
len)
void write(int c) It writes a single character.
void write(String str) It writes a string.
void write(String str, int off, int It writes a portion of a string.
len)

117
Java Writer Example
 import java.io.*;  
 public class WriterExample {  
     public static void main(String[] args) {  
         try {  
             Writer w = new FileWriter("output.txt");  
             String content = "I love my country";  
             w.write(content);  
             w.close();  
             System.out.println("Done");  
         } 
 catch (IOException e) {  
             e.printStackTrace();  
         }  
     }  
 }  

118
Java FileWriter Class
 Java FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java.
 Unlike FileOutputStream class, you don't need to convert string into byte array
 because it provides method to write string directly.
 Java FileWriter class declaration
 public class FileWriter extends OutputStreamWriter  
 Constructors of FileWriter class
Constructor Description
FileWriter(String file) Creates a new file. It gets file name in string.
FileWriter(File file) Creates a new file. It gets file name in File object.

 Methods of FileWriter class


Method Description
void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.

119
Java FileWriter Example
 In this example, we are writing the data in the file testout.txt using Java FileWriter
class.
 import java.io.FileWriter;  
 public class FileWriterExample
  {  
     public static void main(String args[])
 {    
          try
 {    
            FileWriter fw=new FileWriter("D:\\testout.txt");    
            fw.write("Welcome to javaTpoint.");    
            fw.close();    
           }catch(Exception e){System.out.println(e);}    
           System.out.println("Success...");    
      }    
 }  
120
Java FileReader Class
 Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.
 It is character-oriented class which is used for file handling in java.
 Java FileReader class declaration
 public class FileReader extends InputStreamReader  
 Constructors of FileReader class
Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read mode.
If file doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read
mode. If file doesn't exist, it throws FileNotFoundException.

 Methods of FileReader class


Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of
file.
void close() It is used to close the FileReader class.

121
Java FileReader Example
 In this example, we are reading the data from the text file testout.txt using Java
FileReader class.
 import java.io.FileReader;  
 public class FileReaderExample 
 {  
     public static void main(String args[])throws Exception
 {    
           FileReader fr=new FileReader("D:\\testout.txt");    
           int i;    
           while((i=fr.read())!=-1)    
           System.out.print((char)i);    
           fr.close();    
     }    
 }    

122
Java BufferedWriter Class
 Java BufferedWriter class is used to provide buffering for Writer instances. It
makes the performance fast. It inherits Writer class. The buffering characters are
used for providing the efficient writing of single arrays, characters, and strings.
 Class declaration
 public class BufferedWriter extends Writer  
 Class constructors
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream that
uses the default size for an output buffer.
BufferedWriter(Writer wrt, int size) It is used to create a buffered character output stream that
uses the specified size for an output buffer.

 Class methods
Method Description
void newLine() It is used to add a new line by writing a line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
void flush() It is used to flushes the input stream.
void close() It is used to closes the input stream

123
Example of Java BufferedWriter
 Let's see the simple example of writing the data to a text file testout.txt using
Java BufferedWriter.
 import java.io.*;  
 public class BufferedWriterExample
  {  
 public static void main(String[] args) throws Exception
  {     
     FileWriter writer = new FileWriter("D:\\testout.txt");  
     BufferedWriter buffer = new BufferedWriter(writer);  
     buffer.write("Welcome to javaTpoint.");  
     buffer.close();  
     System.out.println("Success");  
     }  
 }  
124
Java 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. It inherits Reader class.
 Java BufferedReader class declaration
 public class BufferedReader extends Reader  
 Java BufferedReader class constructors
Constructor Description
BufferedReader(Reader rd) It is used to create a buffered character input stream that uses the
default size for an input buffer.
BufferedReader(Reader rd, int size) It is used to create a buffered character input stream that uses the
specified size for an input buffer.

 Java BufferedReader class methods


Method Description

int read() It is used for reading a single character.


int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an array.
boolean markSupported() It is used to test the input stream support for the mark and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the mark method was last called on this input
stream.
void mark(int readAheadLimit) It is used for marking the present position in a stream.
void close() It closes the input stream and releases any of the system resources associated with the
125 stream.
Java BufferedReader Example
 import java.io.*;  
 public class BufferedReaderExample 
 {  
     public static void main(String args[])throws Exception
 {    
           FileReader fr=new FileReader("D:\\testout.txt");    
           BufferedReader br=new BufferedReader(fr);    
   
           int i;    
           while((i=br.read())!=-1){  
           System.out.print((char)i);  
           }  
           br.close();    
           fr.close();    
     }    
 }    

126
Reading data from console by InputStreamReader and
BufferedReader
 In this example, we are connecting the BufferedReader stream with the 
InputStreamReader stream for reading the line by line data from the keyboard.
 import java.io.*;  
 public class BufferedReaderExample{    
 public static void main(String args[])throws Exception{             
     InputStreamReader r=new InputStreamReader(System.in);    
     BufferedReader br=new BufferedReader(r);            
     System.out.println("Enter your name");    
     String name=br.readLine();    
     System.out.println("Welcome "+name);    
 }    
 }  

127
Another example of reading data from console until
user writes stop
 In this example, we are reading and printing the data until the user prints stop.
 import java.io.*;  
 public class BufferedReaderExample{    
 public static void main(String args[])throws Exception{             
      InputStreamReader r=new InputStreamReader(System.in);    
      BufferedReader br=new BufferedReader(r);           
      String name="";    
      while(!name.equals("stop")){    
       System.out.println("Enter data: ");    
       name=br.readLine();    
       System.out.println("data is: "+name);    
      }              
     br.close();    
     r.close();    
     }    
     }  

128
Java CharArrayReader Class
 The CharArrayReader is composed of two words: CharArray and Reader. The
CharArrayReader class is used to read character array as a reader (stream). It
inherits Reader class.
 Java CharArrayReader class declaration
 public class CharArrayReader extends Reader  
 Java CharArrayReader class methods
Method Description
int read() It is used to read a single character
int read(char[] b, int off, int len) It is used to read characters into the portion of an array.
boolean ready() It is used to tell whether the stream is ready to read.
boolean markSupported() It is used to tell whether the stream supports mark()
operation.
long skip(long n) It is used to skip the character in the input stream.
void mark(int readAheadLimit) It is used to mark the present position in the stream.

void reset() It is used to reset the stream to a most recent mark.


void close() It is used to closes the stream.

129
Example of CharArrayReader Class:
 import java.io.CharArrayReader;  
 public class CharArrayExample{  
   public static void main(String[] ag) throws Exception {  
     char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };  
     CharArrayReader reader = new CharArrayReader(ary);  
     int k = 0;  
Output
     // Read until the end of a file   j : 106
     while ((k = reader.read()) != -1) {   a : 97
v : 118
       char ch = (char) k;   a : 97
       System.out.print(ch + " : ");   t : 116
p : 112
       System.out.println(k);  
o : 111
     }   i : 105
   }   n : 110
t : 116
 }  

130
Java CharArrayWriter Class
 The CharArrayWriter class can be used to write common data to multiple files. This
class inherits Writer class. Its buffer automatically grows when data is written in
this stream. Calling the close() method on this object has no effect.
 Java CharArrayWriter class declaration
 public class CharArrayWriter extends Writer  
 Java CharArrayWriter class Methods
Method Description
int size() It is used to return the current size of the buffer.
char[] toCharArray() It is used to return the copy of an input data.
String toString() It is used for converting an input data to a string.
CharArrayWriter append(char c) It is used to append the specified character to the writer.
CharArrayWriter append(CharSequence csq) It is used to append the specified character sequence to the writer.
CharArrayWriter append(CharSequence csq, int It is used to append the subsequence of a specified character to the
start, int end) writer.
void write(int c) It is used to write a character to the buffer.
void write(char[] c, int off, int len) It is used to write a character to the buffer.
void write(String str, int off, int len) It is used to write a portion of string to the buffer.
void writeTo(Writer out) It is used to write the content of buffer to different character stream.
void flush() It is used to flush the stream.
void reset() It is used to reset the buffer.
void close() It is used to close the stream.

131
 Example of CharArrayWriter Class:
 In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
 import java.io.CharArrayWriter;  
 import java.io.FileWriter;  
 public class CharArrayWriterExample {  
 public static void main(String args[])throws Exception{    
           CharArrayWriter out=new CharArrayWriter();    
           out.write("Welcome to javaTpoint");    
           FileWriter f1=new FileWriter("D:\\a.txt");    
           FileWriter f2=new FileWriter("D:\\b.txt");    
           FileWriter f3=new FileWriter("D:\\c.txt");    
           FileWriter f4=new FileWriter("D:\\d.txt");    
           out.writeTo(f1);    
           out.writeTo(f2);    
           out.writeTo(f3);    
           out.writeTo(f4);    
           f1.close();    
           f2.close();    
           f3.close();    
           f4.close();    
           System.out.println("Success...");    
          }    
         }    
132
Java PrintStream Class
 The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush()
method. Moreover, its methods don't throw IOException.
 Class declaration
 public class PrintStream extends FilterOutputStream implements Closeable. Appe
ndable   
 Methods of PrintStream class
Method Description
void print(boolean b) It prints the specified boolean value.
void print(char c) It prints the specified char value.
void print(char[] c) It prints the specified character array values.
void print(int i) It prints the specified int value.
void print(long l) It prints the specified long value.
void print(float f) It prints the specified float value.
void print(double d) It prints the specified double value.
void print(String s) It prints the specified string value.
void print(Object obj) It prints the specified object value.
void println(boolean b) It prints the specified boolean value and terminates the line.

void println(char c) It prints the specified char value and terminates the line.
133
void println(char[] c) It prints the specified character array values and
terminates the line.
void println(int i) It prints the specified int value and terminates the
line.
void println(long l) It prints the specified long value and terminates the
line.
void println(float f) It prints the specified float value and terminates the
line.
void println(double d) It prints the specified double value and terminates
the line.
void println(String s) It prints the specified string value and terminates the
line.
void println(Object obj) It prints the specified object value and terminates
the line.
void println() It terminates the line only.

void printf(Object format, Object... args) It writes the formatted string to the current stream.

void printf(Locale l, Object format, Object... It writes the formatted string to the current stream.
args)
void format(Object format, Object... args) It writes the formatted string to the current stream
using specified format.

void format(Locale l, Object format, Object... It writes the formatted string to the current stream
args) using specified format.

134
 Example of java PrintStream class
 In this example, we are simply printing integer and string value.
 import java.io.FileOutputStream;  
 import java.io.PrintStream;  
 public class PrintStreamTest{    
  public static void main(String args[])throws Exception{    
    FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");    
    PrintStream pout=new PrintStream(fout);    
    pout.println(2016);    
    pout.println("Hello Java");    
    pout.println("Welcome to Java");    
    pout.close();    
    fout.close();    
   System.out.println("Success?");    
  }    
 }    

135
 Example of printf() method using java PrintStream class:
 Let's see the simple example of printing integer value by format specifier using printf() method
of java.io.PrintStream class.
 class JavaFormatter1
 {
   public static void main(String args[])
   {
     int x = 100;
     System.out.printf("Printing simple integer: x = %d\n", x);
     // this will print it upto 2 decimal places
     System.out.printf("Formatted with precison: PI = %.2f\n", Math.PI);
     float n = 5.2f;
     // automatically appends zero to the rightmost part of decimal
     System.out.printf("Formatted to specific width: n = %.4f\n", n);
     n = 2324435.3f
     // here number is formatted from right margin and occupies a
     // width of 20 characters
     System.out.printf("Formatted to right margin: n = %20.4f\n", n);
Output:
   } Printing simple integer: x = 100
 } Formatted with precison: PI = 3.14
Formatted to specific width: n = 5.2000
136 Formatted to right margin: n = 2324435.2500
Java Scanner
 Scanner class in Java is found in the java.util package. Java provides 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 which is whitespace by
default. It provides many methods to read and parse various primitive values.
 The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java,
we can get input from the user in primitive types such as int, long, double, byte, float, short,
etc.
 The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
 The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.

 Java Scanner Class Declaration


 public final class Scanner  
           extends Object  
           implements Iterator<String>   

137
 How to get Java Scanner
 To get the instance of Java Scanner which reads input from the user,
we need to pass the input stream (System.in) in the constructor of
Scanner class. For Example:
 Scanner in = new Scanner(System.in);  
 To get the instance of Java Scanner which parses the strings, we need
to pass the strings in the constructor of Scanner class. For Example:
 Scanner in = new Scanner("Hello Javatpoint");  

138
Java Scanner Class Methods
SN Modifier & Type Method Description
1) void close() It is used to close this scanner.
2) pattern delimiter() It is used to get the Pattern which the Scanner
class is currently using to match delimiters.

3) Stream<MatchResult> findAll() It is used to find a stream of match results


that match the provided pattern string.
4) String findInLine() It is used to find the next occurrence of a
pattern constructed from the specified string,
ignoring delimiters.
5) string findWithinHorizon() It is used to find the next occurrence of a
pattern constructed from the specified string,
ignoring delimiters.
6) boolean hasNext() It returns true if this scanner has another
token in its input.
7) boolean hasNextBigDecimal() It is used to check if the next token in this
scanner's input can be interpreted as a
BigDecimal using the nextBigDecimal() method
or not.
8) boolean hasNextBigInteger() It is used to check if the next token in this
scanner's input can be interpreted as a
BigDecimal using the nextBigDecimal() method
or not.

139
9) boolean hasNextBoolean() It is used to check if the next token in this scanner's input can
be interpreted as a Boolean using the nextBoolean() method
or not.

10) boolean hasNextByte() It is used to check if the next token in this scanner's input can
be interpreted as a Byte using the nextBigDecimal() method
or not.

11) boolean hasNextDouble() It is used to check if the next token in this scanner's input can
be interpreted as a BigDecimal using the nextByte() method
or not.

12) boolean hasNextFloat() It is used to check if the next token in this scanner's input can
be interpreted as a Float using the nextFloat() method or not.

13) boolean hasNextInt() It is used to check if the next token in this scanner's input can
be interpreted as an int using the nextInt() method or not.

14) boolean hasNextLine() It is used to check if there is another line in the input of this
scanner or not.
15) boolean hasNextLong() It is used to check if the next token in this scanner's input can
be interpreted as a Long using the nextLong() method or not.

16) boolean hasNextShort() It is used to check if the next token in this scanner's input can
be interpreted as a Short using the nextShort() method or
not.
17) IOException ioException() It is used to get the IOException last thrown by this Scanner's
readable.
18) Locale locale() It is used to get a Locale of the Scanner class.

140
19) MatchResult match() It is used to get the match result of the last scanning operation
performed by this scanner.

20) String next() It is used to get the next complete token from the scanner
which is in use.

21) BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.

22) BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.

23) boolean nextBoolean() It scans the next token of the input into a boolean value and
returns that value.

24) byte nextByte() It scans the next token of the input as a byte.

25) double nextDouble() It scans the next token of the input as a double.

26) float nextFloat() It scans the next token of the input as a float.

27) int nextInt() It scans the next token of the input as an Int.

28) String nextLine() It is used to get the input string that was skipped of the Scanner
object.

29) long nextLong() It scans the next token of the input as a long.

141
30) short nextShort() It scans the next token of the input as a short.
31) int radix() It is used to get the default radix of the Scanner
use.
32) void remove() It is used when remove operation is not supported
by this implementation of Iterator.
33) Scanner reset() It is used to reset the Scanner which is in use.
34) Scanner skip() It skips input that matches the specified pattern,
ignoring delimiters
35) Stream<String> tokens() It is used to get a stream of delimiter-separated
tokens from the Scanner object which is in use.
36) String toString() It is used to get the string representation of Scanner
using.
37) Scanner useDelimiter() It is used to set the delimiting pattern of the
Scanner which is in use to the specified pattern.

38) Scanner useLocale() It is used to sets this scanner's locale object to the
specified locale.
39) Scanner useRadix() It is used to set the default radix of the Scanner
which is in use to the specified radix.

142
Java - RandomAccessFile
 This class is used for reading and writing to random access file. A random access
file behaves like a large array of bytes. There is a cursor implied to the array called
file pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException is 
thrown. It is a type of IOException.
 Constructor

Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read
from, and optionally to write to, the file
specified by the File argument.

RandomAccessFile(String name, String Creates a random access file stream to read


mode) from, and optionally to write to, a file with
the specified name.

143
Methods
Modifier and Method Method
Type
void close() It closes this random access file stream and releases any system
resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.
void writeDouble(double v) It converts the double argument to a long using the
doubleToLongBits method in class Double, and then writes that long
value to the file as an eight-byte quantity, high byte first.
void writeFloat(float v) It converts the float argument to an int using the floatToIntBits
method in class Float, and then writes that int value to the file as a
four-byte quantity, high byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.

144
Example
 import java.io.IOException;  
 import java.io.RandomAccessFile;  
   
 public class RandomAccessFileExample {  
     static final String FILEPATH ="myFile.TXT";  
     public static void main(String[] args) {  
         try {  
             System.out.println(new String(readFromFile(FILEPATH, 0, 18)));  
             writeToFile(FILEPATH, "I love my country and my people", 31);  
         } catch (IOException e) {  
             e.printStackTrace();  
         }  
     }  
    

145
  private static byte[] readFromFile(String filePath, int position, int size)  
             throws IOException {  
         RandomAccessFile file = new RandomAccessFile(filePath, "r");  
         file.seek(position);  
         byte[] bytes = new byte[size];  
         file.read(bytes);  
         file.close();  
         return bytes;  
     }  
     private static void writeToFile(String filePath, String data, int position)  
             throws IOException {  
         RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
         file.seek(position);  
         file.write(data.getBytes());  
         file.close();  
     }  
 }  

146
END of IV UNIT

147

You might also like