What Is a Collections Framework?
Introduction to CollectionsA?collection?— sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers). If you have used the Java programming language — or just about any other programming language — you are already familiar with collections.What Is a Collections Framework?A?collections framework?is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:Interfaces:?These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.Implementations:?These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.Algorithms:?These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be?polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy. Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. We believe that the Java Collections Framework breaks with this tradition, as you will learn for yourself in this chapter.Benefits of the Java Collections FrameworkThe Java Collections Framework provides the following benefits:Reduces programming effort:?By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.Increases program speed and quality:?This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.Allows interoperability among unrelated APIs:?The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.Reduces effort to learn and to use new APIs:?Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.Reduces effort to design new APIs:?This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.Fosters software reuse:?New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.Hierarchy of Collection FrameworkLet us see the hierarchy of collection framework. The?java.util?package contains all the classes and interfaces for Collection framework.Methods of Collection interfaceThere are many methods declared in the Collection interface. They are as follows:Java ArrayList class:Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface. The important points about Java ArrayList class are: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 Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.Hierarchy of ArrayList classAs shown in above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.ArrayList class declaration:Let's see the declaration for java.util.ArrayList class.public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable Constructors of Java ArrayList:Methods of Java ArrayList:Java Non-generic Vs Generic CollectionJava collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.Let's see the old non-generic example of creating java collection.ArrayList?al=new?ArrayList();//creating?old?non-generic?arraylist??Let's see the new generic example of creating java collection.ArrayList<String>?al=new?ArrayList<String>();//creating?new?generic?arraylist??In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.import java.util.*; class TestCollection1{ 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"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ravi Vijay Ravi AjayTwo ways to iterate the elements of collection in javaThere are two ways to traverse collection elements:By Iterator interface.By for-each loop.In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each loop.Iterating Collection through for-each loopimport java.util.*; class TestCollection2{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); for(String obj:al) System.out.println(obj); } } Output: Ravi Vijay Ravi AjayGenerics in Java:The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.Advantage of Java GenericsThere are mainly 3 advantages of generics. They are as follows:1) Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other objects.2) Type casting is not required: There is no need to typecast the object.Before Generics, we need to type cast. List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);//typecasting After Generics, we don't need to typecast the object. List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); 3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime. List<String> list = new ArrayList<String>(); list.add("hello"); list.add(32);//Compile Time Error Syntax to use generic collectionClassOrInterface<Type>??Example of Generics in JavaHere, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc. import java.util.*; class TestGenerics1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("rahul"); list.add("jai"); //list.add(32);//compile time error String s=list.get(1);//type casting is not required System.out.println("element is: "+s); Iterator<String> itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: element is: jai rahul jai Wildcard in Java GenericsThe ? (question mark) symbol represents wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.Let's understand it by the example given below: import java.util.*; abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle extends Shape{ void draw(){System.out.println("drawing circle");} } class GenericTest{ //creating a method that accepts only child class of Shape public static void drawShapes(List<? extends Shape> lists){ for(Shape s:lists){ s.draw();//calling method of Shape class by child class instance } } public static void main(String args[]){ List<Rectangle> list1=new ArrayList<Rectangle>(); list1.add(new Rectangle()); List<Circle> list2=new ArrayList<Circle>(); list2.add(new Circle()); list2.add(new Circle()); drawShapes(list1); drawShapes(list2); }} Output: drawing rectangle drawing circle drawing circleGenerics in Java:The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.Advantage of Java GenericsThere are mainly 3 advantages of generics. They are as follows:1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.2) Type casting is not required: There is no need to typecast the object.Before Generics, we need to type cast. List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);//typecasting After Generics, we don't need to typecast the object. List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); 3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime. List<String> list = new ArrayList<String>(); list.add("hello"); list.add(32);//Compile Time Error Syntax to use generic collection ClassOrInterface<Type>??Example of Generics in JavaHere, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc. import java.util.*; class TestGenerics1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("rahul"); list.add("jai"); //list.add(32);//compile time error String s=list.get(1);//type casting is not required System.out.println("element is: "+s); Iterator<String> itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Output:element is: jai rahul jai Wildcard in Java GenericsThe ? (question mark) symbol represents wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.Let's understand it by the example given below: import java.util.*; abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle extends Shape{ void draw(){System.out.println("drawing circle");} } class GenericTest{ //creating a method that accepts only child class of Shape public static void drawShapes(List<? extends Shape> lists){ for(Shape s:lists){ s.draw();//calling method of Shape class by child class instance } } public static void main(String args[]){ List<Rectangle> list1=new ArrayList<Rectangle>(); list1.add(new Rectangle()); List<Circle> list2=new ArrayList<Circle>(); list2.add(new Circle()); list2.add(new Circle()); drawShapes(list1); drawShapes(list2); }} Output: drawing rectangledrawing circledrawing circleUser-defined class objects in Java ArrayListLet's see an example where we are storing Student class object in array list. class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } } ……………………. import java.util.*; public class TestCollection3{ public static void main(String args[]){ //Creating user-defined class objects Student s1=new Student(101,"Sonoo",23); Student s2=new Student(102,"Ravi",21); Student s2=new Student(103,"Hanumat",25); //creating arraylist ArrayList<Student> al=new ArrayList<Student>(); al.add(s1);//adding Student class object al.add(s2); al.add(s3); //Getting Iterator Iterator itr=al.iterator(); //traversing elements of ArrayList object while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } } } Output: 101 Sonoo 23 102 Ravi 21 103 Hanumat 25Example of addAll(Collection c) method import java.util.*; class TestCollection4{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Sonoo"); al2.add("Hanumat"); al.addAll(al2);//adding second list in first list Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ravi Vijay Ajay Sonoo HanumatExample of removeAll() methodimport java.util.*; class TestCollection5{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Ravi"); al2.add("Hanumat"); al.removeAll(al2); System.out.println("iterating the elements after removing the elements of al2..."); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: iterating the elements after removing the elements of al2... Vijay AjayExample of retainAll() method import java.util.*; class TestCollection6{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Ravi"); al2.add("Hanumat"); al.retainAll(al2); System.out.println("iterating the elements after retaining the elements of al2..."); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: iterating the elements after retaining the elements of al2... RaviJava ArrayList Example: BookLet's see an ArrayList example where we are adding books to list and printing all the books. import java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class ArrayListExample { public static void main(String[] args) { //Creating list of Books List<Book> list=new ArrayList<Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to list list.add(b1); list.add(b2); list.add(b3); //Traversing list for(Book b:list){ System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } } Output: 101 Let us C Yashwant Kanetkar BPB 8102 Data Communications & Networking Forouzan Mc Graw Hill 4103 Operating System Galvin Wiley 6Difference between ArrayList and VectorArrayList and Vector both implements List interface and maintains insertion order.But there are many differences between ArrayList and Vector classes that are given below.Example of Java VectorLet's see a simple example of java Vector class that uses Enumeration interface.import java.util.*; class TestVector1{ public static void main(String args[]){ Vector<String> v=new Vector<String>();//creating vector v.add("umesh");//method of Collection v.addElement("irfan");//method of Vector v.addElement("kumar"); //traversing elements using Enumeration Enumeration e=v.elements(); while(e.hasMoreElements()){ System.out.println(e.nextElement()); } } } output: umesh irfan kumarJava Hashtable class:Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface. The important points about Java Hashtable class are:A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.It contains only unique elements.It may have not have any null key or value.It is synchronized.Hashtable class declarationLet's see the declaration for java.util.Hashtable class.ublic?class?Hashtable<K,V>?extends?Dictionary<K,V>?implements?Map<K,V>,?Cloneable,?Serializable??Hashtable class ParametersLet's see the Parameters for java.util.Hashtable class.K: It is the type of keys maintained by this map.V: It is the type of mapped values.Constructors of Java Hashtable classMethods of Java Hashtable classJava Hashtable Example import java.util.*; class TestCollection16{ public static void main(String args[]){ Hashtable<Integer,String> hm=new Hashtable<Integer,String>(); hm.put(100,"Amit"); hm.put(102,"Ravi"); hm.put(101,"Vijay"); hm.put(103,"Rahul"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output: 103 Rahul 102 Ravi 101 Vijay 100 AmitJava Hashtable Example: remove() import java.util.*; public class HashtableExample { public static void main(String args[]) { // create and populate hash table Hashtable<Integer, String> map = new Hashtable<Integer, String>(); map.put(102,"Let us C"); map.put(103, "Operating System"); map.put(101, "Data Communication and Networking"); System.out.println("Values before remove: "+ map); // Remove value for key 102 map.remove(102); System.out.println("Values after remove: "+ map); } } Output:Values before remove: {103=Operating System, 102=Let us C, 101=Data Communication and Networking}Values after remove: {103=Operating System, 101=Data Communication and Networking}Java Hashtable Example: Bookimport java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; }} public class HashtableExample { public static void main(String[] args) { //Creating map of Books Map<Integer,Book> map=new Hashtable<Integer,Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to map map.put(1,b1); map.put(2,b2); map.put(3,b3); //Traversing map for(Map.Entry<Integer, Book> entry:map.entrySet()){ int key=entry.getKey(); Book b=entry.getValue(); System.out.println(key+" Details:"); System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } } Output: 3 Details: 103 Operating System Galvin Wiley 6 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4 1 Details: 101 Let us C Yashwant Kanetkar BPB 8The Stack ClassStack is a subclass of Vector that implements a standard last-in, first-out stack.Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.Stack( )Apart from the methods inherited from its parent class Vector, Stack defines the following methods : ExampleThe following program illustrates several of the methods supported by this collection import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); }catch (EmptyStackException e) { System.out.println("empty stack"); } }}This will produce the following resultOutputstack: [ ]push(42)stack: [42]push(66)stack: [42, 66]push(99)stack: [42, 66, 99]pop -> 99stack: [42, 66]pop -> 66stack: [42]pop -> 42stack: [ ]pop -> empty stackEnumeration:Java EnumEnum in java?is a data type that contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.Java Enums can be thought of as classes that have fixed set of constants.Points to remember for Java Enumenum improves type safetyenum can be easily used in switchenum can be traversedenum can have fields, constructors and methodsenum may implement many interfaces but cannot extend any class because it internally extends Enum classExample of java enumclass EnumExample1{ public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s); }} Output: WINTER SPRING SUMMER FALLWhat is the purpose of values() method in enum?The java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum.Internal code generated by the compiler for the above example of enum type:The java compiler internally creates a static and final class that extends the Enum class as shown in the below example:public static final class EnumExample1$Season extends Enum { private EnumExample1$Season(String s, int i) { super(s, i); } public static EnumExample1$Season[] values() { return (EnumExample1$Season[])$VALUES.clone(); } public static EnumExample1$Season valueOf(String s) { return (EnumExample1$Season)Enum.valueOf(EnumExample1$Season, s); } public static final EnumExample1$Season WINTER; public static final EnumExample1$Season SPRING; public static final EnumExample1$Season SUMMER; public static final EnumExample1$Season FALL; private static final EnumExample1$Season $VALUES[]; static { WINTER = new EnumExample1$Season("WINTER", 0); SPRING = new EnumExample1$Season("SPRING", 1); SUMMER = new EnumExample1$Season("SUMMER", 2); FALL = new EnumExample1$Season("FALL", 3); $VALUES = (new EnumExample1$Season[] { WINTER, SPRING, SUMMER, FALL }); } } Defining Java enumThe enum can be defined within or outside the class because it is similar to a class.enum Season { WINTER, SPRING, SUMMER, FALL } class EnumExample2{ public static void main(String[] args) { Season s=Season.WINTER; System.out.println(s); }} Output: WINTERInternal code generated by the compiler for the above example of enum typeThe java compiler internally creates a static and final class that extends the Enum class as shown in the below example:public static final class EnumExample1$Season extends Enum { private EnumExample1$Season(String s, int i) { super(s, i); } public static EnumExample1$Season[] values() { return (EnumExample1$Season[])$VALUES.clone(); } public static EnumExample1$Season valueOf(String s) { return (EnumExample1$Season)Enum.valueOf(EnumExample1$Season, s); } public static final EnumExample1$Season WINTER; public static final EnumExample1$Season SPRING; public static final EnumExample1$Season SUMMER; public static final EnumExample1$Season FALL; private static final EnumExample1$Season $VALUES[]; static { WINTER = new EnumExample1$Season("WINTER", 0); SPRING = new EnumExample1$Season("SPRING", 1); SUMMER = new EnumExample1$Season("SUMMER", 2); FALL = new EnumExample1$Season("FALL", 3); $VALUES = (new EnumExample1$Season[] { WINTER, SPRING, SUMMER, FALL}); } } Initializing specific values to the enum constantsThe enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors and methods.Example of specifying initial value to the enum constantsclass EnumExample4{ enum Season{ WINTER(5), SPRING(10), SUMMER(15), FALL(20); private int value; private Season(int value){ this.value=value; } } public static void main(String args[]){ for (Season s : Season.values()) System.out.println(s+" "+s.value); } } Output: WINTER 5 SPRING 10 SUMMER 15 FALL 20Note: Constructor of enum type is private. If you don't declare private compiler internally creates private constructor.enum Season{ WINTER(10),SUMMER(20); private int value; Season(int value){ this.value=value; } } Java IteratorOften, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.In general, to use an iterator to cycle through the contents of a collection, follow these steps ?Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.Within the loop, obtain each element by calling next( ).For collections that implement List, you can also obtain an iterator by calling ListIterator.The Methods Declared by IteratorThe Methods Declared by ListIterator void add(Object obj)Inserts obj into the list in front of the element that will be returned by the next call to next( ).boolean hasNext( )Returns true if there is a next element. Otherwise, returns false.boolean hasPrevious( )Returns true if there is a previous element. Otherwise, returns false.Object next( )Returns the next element. A NoSuchElementException is thrown if there is not a next element.int nextIndex( )Returns the index of the next element. If there is not a next element, returns the size of the list.Object previous( )Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.int previousIndex( )Returns the index of the previous element. If there is not a previous element, returns -1.void remove( )Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.void set(Object obj)Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).ExampleHere is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.Of course, ListIterator is available only to those collections that implement the List interface.import java.util.*;public class IteratorDemo { public static void main(String args[]) { // Create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // Use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // Modify objects being iterated ListIterator litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + "+"); } System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // Now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + " "); } System.out.println(); }}This will produce the following result:Original contents of al: C A E B D FModified contents of al: C+ A+ E+ B+ D+ F+Modified list backwards: F+ D+ B+ E+ A+ C+Difference between Iterator and Enumeration interfacesremove() method is introduced in iterator. Using this method we can remove element from the underlying collection which we are iterating.Enumeration has two methods and both are available in iterator. Method names for both of them are shortened.ListIterator an even better Iterator for a List containing more utility methods like getting index of elements and adding elements to the base object. Using ListIterator we can iterate in both the directions.StringTokenizerThe?java.util.StringTokenizer?class allows you to break a string into tokens. It is simple way to break string.It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.Constructors of StringTokenizer classThere are 3 constructors defined in the StringTokenizer class.Methods of StringTokenizer classThe 6 useful methods of StringTokenizer class are as follows:Example of StringTokenizer class:Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.import java.util.StringTokenizer; public class Simple{ public static void main(String args[]){ StringTokenizer st = new StringTokenizer("my name is khan"," "); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } Output: my name is khanExample of nextToken(String delim) method of StringTokenizer classimport java.util.*; public class Test { public static void main(String[] args) { StringTokenizer st = new StringTokenizer("my,name,is,khan"); // printing next token System.out.println("Next token is : " + st.nextToken(",")); } } Output:Next token is : myNote: StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).Random ClassThe?java.util.Random?class instance is used to generate a stream of pseudorandom numbers.Following are the important points about Random:The class uses a 48-bit seed, which is modified using a linear congruential formula.The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.Class declaration:Following is the declaration for?java.util.Random?class:public class Random extends Object implements SerializableClass constructorsClass methodsprotected int next(int bits)This method generates the next pseudorandom number.boolean nextBoolean()This method returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. void nextBytes(byte[] bytes)This method generates random bytes and places them into a user-supplied byte array.double nextDouble()This method returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.float nextFloat()This method returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.double nextGaussian()This method returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.int nextInt()This method returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.int nextInt(int n)This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.long nextLong()This method returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.void setSeed(long seed)This method sets the seed of this random number generator using a single long seed.Scanner classThe Scanner class is a class?in java.util, which allows the user to read values of various types. There are far more methods in class?Scanner?than you will need in this course. We only cover a small useful subset, ones that allow us to read in numeric values from either the keyboard or file without having to convert them from strings and determine if there are more values to be read.Class ConstructorsThere are two constructors that are particularly useful: one takes an?InputStream?object as a parameter and the other takes a?FileReader?object as a parameter.?Scanner in = new Scanner(System.in);??// System.in is an InputStreamScanner inFile = new Scanner(new FileReader("myFile"));?If the file ≥myFile≤ is not found, a?FileNotFoundException?is thrown. This is a checked exception, so it must be caught or forwarded by putting the phrase ≥throws FileNotFoundException≤ on the header of the method in which the instantiation occurs and the header of any method that calls the method in which the instantiation occurs.Numeric and String MethodsThe?Scanner?looks for?tokens?in the input. A token is a series of characters that ends with what Java calls?whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the end of the file. Thus, if we read a line that has a series of numbers separated by blanks, the scanner will take each number as a separate token.?Although we have only shown four numeric methods, each numeric data type has a corresponding method that reads values of that type.The numeric values may all be on one line with blanks between each value or may be on separate lines.???Whitespace?characters (blanks or carriage returns) act as separators.??The?next?method returns the next input value as a string, regardless of what is keyed.??For example, given the following code segment and data?int number = in.nextInt();float real = in.nextFloat();long number2 = in.nextLong();double real2 = in.nextDouble();String string = in.next();?44 23222222222222222.33 End?44?would be stored in?number;?23.0?would be stored in?real;?2222222222?would be stored in?number2;?22222.33?would be stored in?real2; and?≥End≤?would be stored in?string.??Notice that method?nextFloat?reads an integer and stores it as a?float?value.??This is legal because an integer value can be stored exactly as a real value; there is no ambiguity.??If we had keyed a decimal point after the?44, the system would have thrown a?InputMismatchException?(a checked exception) regardless of whether or not a non-zero value followed the decimal point. An arbitrary real number cannot be stored exactly as an integer; it is ambiguous.??Remember that anything ambiguous is illegal.nextLine?reads the?rest?of the line and returns it as a string.??The carriage return is consumed but is not appended to the string.??The numeric reads do not consume the whitespace, so if a?nextLine?is issued at after a numeric read and the numeric value is at the end of the line,?nextLine?returns the empty string.??nextLine?never jumps over a carriage return to get the next line of input.??For example, the following code fragment?int number = in.nextInt();String string = in.nextLine();float real = in.nextFloat();String string2 = in.nextLine();?and the data shown above,?string?would contain ≥23≤ and?string2?would contain the empty string.?Here is a program that uses these methods, followed by the output.??Look over the application carefully to be sure you understand how the output was generated.//**********************************************************************// Class NumericInput demonstrates reading numeric values.//**********************************************************************import?java.util.Scanner;import?java.io.*;??????????// Access System.outpublic?class?NumericInput{??public?static?void?main(String[] args)??{????// Declarations????Scanner in =?new?Scanner(System.in);????int?integer;????long?longInteger;????float?realNumber;????double?doubleReal;????String string1;????String string2;??????????// Prompts????System.out.println("Enter an integer, a long integer, "???????????????????????+?"a floating-point ");????System.out.println("number, another floating-point number, "???????????????????????+?"and a string.");????System.out.println("Separate each with a blank or return.");????????// Read in values??????integer = in.nextInt();????longInteger = in.nextLong();????realNumber = in.nextFloat();????doubleReal = in.nextDouble();????string1 = in.nextLine();????System.out.println("Now enter another value.");????string2 = in.next();???????System.out.println("Here is what you entered: ");????System.out.println(integer +?" "?+ longInteger +?" "?+ realNumber +???????????????????????" "?+ doubleReal +?" "?+ string1 +???????????????????????" and "?+ string2);??}?}Output:Enter an integer, a long integer, a floating-pointnumber, another floating-point number, and a string.Separate each with a blank or return.232425.0 233333333333333.444 HelloNow enter another value.23.4Here is what you entered:23 24 25.0 2.3333333333333344E14??Hello and 23.4Boolean MethodsWe said that the?Scanner?methods that read numeric data throw a?“InputMismatchException”?exception if the next value isnπt what the method expects.??We can avoid that problem using Boolean methods. Here are four useful Boolean methods that allow us to check to be sure that the next value is what we expect.Let's write a code fragment that instantiates a scanner and reads and prints an integer value and a second integer value if there is one.?Scanner in =?new?Scanner(System.in);System.out.println(in.nextInt());if?(in.hasNextInt())??System.out.println(in.nextInt());?There are methods equivalent to these for each of the Java built-in types.The following application applies the appropriate reading method to the data that is keyed in.?//************************************************************************// MixedTypeInput// This application demonstrates testing before reading to be// sure to use the correct input method for the data.//************************************************************************?import?java.io.*;import?java.util.Scanner;public?class?MixedTypeInput{??public?static?void?main(String[] args)??{????double?number;????Scanner in =?new?Scanner(System.in);????System.out.println("Enter your gross income: ");????if?(in.hasNextInt())????{??????number = (double)in.nextInt();??????System.out.println("You entered "?+ number);????}????else?if?(in.hasNextFloat())????{??????number = (double)in.nextFloat();??????System.out.println("You entered "?+ number);????}????else?if?(in.hasNextDouble())????{??????number = in.nextDouble();??????System.out.println("You entered "?+ number);????}?????????????????else??????System.out.println("Token not an integer or a real value.");?????}}?The application was run four times.??The input is shown in red.??Enter your gross income:55000You entered 55000.0?Enter your gross income:55000.0You entered 55000.0?Enter your gross income:55E10You entered 5.50000001024E11?Enter your gross income:Fifty Five HundredToken not an integer or a real value.??What would happen if there were no token in the file in the previous example? Each of the?boolean?methods would return?false. They return?true?if and only if the next token in the scanner can be interpreted as a value of their type.?We return to the subject of reading data from files later in this chapter and?show how to use these?Scanner?methods to allow us to read multiple values from a line in a file.?Except for some trivial cases, we must combine reading operations with loops to read through all of the data on a file.FilesTo read from a file rather than the keyboard, you instantiate a?Scanner?object with a?FileReader?object rather than?System.in.?Scanner in =?new?Scanner(System.in);???// Reading from the keyboardScanner inFile =?new?Scanner(new?FileReader(≥inFile.dat≤)); // Reading from a file?Although all of the methods applied to keyboard input can be applied to file input, there are methods that are usually applied only to files.??These are the methods that ask of there are more values in the file. If there are no more values in a file, we say that the file is at the end of the file (EOF).??For example,?inFile.hasNext();inFile.hasNextLine();?return?true?if?inFile?has another token in the file or if there is another line in the file.??What about the methods?hasNextInt?and so forth that we used to look ahead at the type of the next input token???These can be used to determine if there are more data values in the file, provided you know exactly how the files are organized?Be sure to close all files. If you forget to close?System.in, no harm is done, but forgetting to close a file can cause problems.Calendar ClassThe?java.util.calendar?class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.Following are the important points about Calendar:This class also provides additional fields and methods for implementing a concrete calendar system outside the package.Calendar defines the range of values returned by certain calendar fields.Class declarationFollowing is the declaration for?java.util.Calendar?class:public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar>FieldFollowing are the fields for?java.util.Calendar?class:static int ALL_STYLES?-- This is the style specifier for getDisplayNames indicating names in all styles, such as "January" and "Jan".static int AM?-- This is the value of the AM_PM field indicating the period of the day from midnight to just before noon.static int AM_PM?-- This is the field number for get and set indicating whether the HOUR is before or after noon.static int APRIL?-- This is the value of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars.protected boolean areFieldsSet?-- This is true if fields[] are in sync with the currently set time.static int AUGUST?-- This is the value of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars.static int DATE?-- This is the field number for get and set indicating the day of the month.static int DAY_OF_MONTH?-- This is the field number for get and set indicating the day of the month.static int DAY_OF_WEEK?-- This is the field number for get and set indicating the day of the week.static int DAY_OF_WEEK_IN_MONTH?-- This is the field number for get and set indicating the ordinal number of the day of the week within the current month.static int DAY_OF_YEAR?-- This is the field number for get and set indicating the day number within the current year.static int DECEMBER?-- This is the value of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.static int DST_OFFSET?-- This is the field number for get and set indicating the daylight savings offset in milliseconds.static int ERA?-- This is the field number for get and set indicating the era, e.g., AD or BC in the Julian calendar.static int FEBRUARY?-- This is the value of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.static int FIELD_COUNT?-- This is the number of distinct fields recognized by get and set.protected int[] fields?-- This is the calendar field values for the currently set time for this calendar.static int FRIDAY?-- This is the value of the DAY_OF_WEEK field indicating Friday.static int HOUR?-- This is the field number for get and set indicating the hour of the morning or afternoon.static int HOUR_OF_DAY?-- This is the field number for get and set indicating the hour of the day.protected boolean[] isSet?-- This is the flags which tell if a specified calendar field for the calendar is set.protected boolean isTimeSet?-- This is true if then the value of time is valid.static int JANUARY?-- This is the value of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars.static int JULY?-- This is the value of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.static int JUNE?-- This is the value of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.static int LONG?-- This is the style specifier for getDisplayName and getDisplayNames indicating a long name, such as "January".static int MARCH?-- This is the value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.static int MAY -- This is the value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.static int MILLISECOND?-- This is the field number for get and set indicating the millisecond within the second.static int MINUTE?-- This is the field number for get and set indicating the minute within the hour.static int MONDAY?-- This is the value of the DAY_OF_WEEK field indicating Monday.static int MONTH?-- This is the field number for get and set indicating the month.static int NOVEMBER?-- This is the value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.static int OCTOBER?-- This is the value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.static int PM?-- This is the value of the AM_PM field indicating the period of the day from noon to just before midnight.static int SATURDAY?-- This is the value of the DAY_OF_WEEK field indicating Saturday.static int SECOND?-- This is the field number for get and set indicating the second within the minute.static int SEPTEMBER?-- This is the value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.static int SHORT?-- This is the style specifier for getDisplayName and getDisplayNames indicating a short name, such as "Jan".static int SUNDAY?-- This is the value of the DAY_OF_WEEK field indicating Sunday.static int THURSDAY?-- This is the value of the DAY_OF_WEEK field indicating Thursday.protected long time?-- This is the the currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.static int TUESDAY?-- This is the value of the DAY_OF_WEEK field indicating Tuesday.static int UNDECIMBER?-- This is the value of the MONTH field indicating the thirteenth month of the year.static int WEDNESDAY?-- This is the value of the DAY_OF_WEEK field indicating Wednesday.static int WEEK_OF_MONTH?-- This is the field number for get and set indicating the week number within the current month.static int WEEK_OF_YEAR?-- This is the Field number for get and set indicating the week number within the current year. .static int YEAR?-- This is the field number for get and set indicating the year.static int ZONE_OFFSET?-- This is the field number for get and set indicating the raw offset from GMT in millisecondsClass constructorsFiles and I/OThe java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.StreamA stream can be defined as a sequence of data. There are two kinds of Streams ?InPutStream?? The InputStream is used to read data from a source.OutPutStream?? The OutputStream is used for writing data to a destination.Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one. Byte StreamsJava byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are,?FileInputStream?and?FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output fileExampleimport java.io.*;public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}Now let's have a file?input.txt?with the following content:Output: This is test for copy file.As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following.$javac CopyFile.java$java CopyFileCharacter StreamsJava?Byte?streams are used to perform input and output of 8-bit bytes, whereas Java?Character?streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are,?FileReader?and?FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output fileExampleimport java.io.*;public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}Now let's have a file?input.txt?with the following content.This is test for copy file.As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following$javac CopyFile.java$java CopyFileStandard StreamsAll the programming languages provide support for standard I/O where the user's program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streamsStandard Input?? This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as?System.in.Standard Output?? This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as?System.out.Standard Error?? This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as?System.err.Following is a simple program, which creates?InputStreamReader?to read standard input stream until the user types a "q".Exampleimport java.io.*;public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } }}Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program. This program continues to read and output the same character until we press 'q'.$javac ReadConsole.java$java ReadConsoleEnter characters, 'q' to quit.11eeqqReading and Writing FilesAs described earlier, a stream can be defined as a sequence of data. The?InputStream?is used to read data from a source and the?OutputStream?is used for writing data to a destination.Here is a hierarchy of classes to deal with Input and Output streams.The two important streams are?FileInputStream?and?FileOutputStream, which would be discussed in this tutorial.FileInputStreamThis stream is used for reading data from the files. Objects can be created using the keyword?new?and there are several types of constructors available.Following constructor takes a file name as a string to create an input stream object to read the file.InputStream f = new FileInputStream("C:/java/hello");Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as followsFile f = new File("C:/java/hello");InputStream f = new FileInputStream(f);Once you have?InputStream?object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.public void close() throws IOException{}This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.protected void finalize()throws IOException {}This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.public int read(int r)throws IOException{}This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file.public int read(byte[] r) throws IOException{}This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.public int available() throws IOException{}Gives the number of bytes that can be read from this file input stream. Returns an int.There are other important input streams available, for more detail you can refer to the following links ?ByteArrayInputStreamDataInputStreamByteArrayInputStreamThe ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array.ByteArrayInputStream class provides the following constructors.Constructor and Description:ByteArrayInputStream(byte [] a)This constructor accepts a byte array as a parameter.ByteArrayInputStream(byte [] a, int off, int len)This constructor takes an array of bytes, and two integervalues, where off is the first byteto be read and len is the number of bytes to be read.Once you have?ByteArrayInputStream?object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.DataInputStream:The DataInputStream is used in the context of DataOutputStream and can be used to read primitives.Following is the constructor to create an InputStreamInputStream in = DataInputStream(InputStream in);Once you have?DataInputStream?object in hand, then there is a list of helper methods, which can be used to read the stream or to do other operations on the stream.Method & Descriptionpublic final int read(byte[] r, int off, int len)throws IOExceptionReads up to len bytes of data from the input stream into an array of bytes. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file.Public final int read(byte [] b)throws IOExceptionReads some bytes from the inputstream and stores in to the byte array. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file.(a) public final Boolean readBooolean()throws IOException(b) public final byte readByte()throws IOException(c) public final short readShort()throws IOException(d) public final Int readInt()throws IOExceptionThese methods will read the bytes from the contained InputStream. Returns the next two bytes of the InputStream as the specific primitive type.public String readLine() throws IOExceptionReads the next line of text from the input stream. It reads successive bytes, converting each byte separately into a character, until it encounters a line terminator or end of file; the characters read are then returned as a String.FileOutputStreamFileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.Here are two constructors which can be used to create a FileOutputStream object.Following constructor takes a file name as a string to create an input stream object to write the file OutputStream f = new FileOutputStream("C:/java/hello");Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:File f = new File("C:/java/hello");OutputStream f = new FileOutputStream(f);Once you have?OutputStream?object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.File management in JavaFile processing is performed in Java using various classes. The primary class used to handle files is called File. The File class is part of the?java.io?package. To use it, you can start by importing it in your file. Here is an example:import java.io.File;public class Exercise { public static void main(String[] args) throws Exception { }}The?File?class is based on (implements) the?FileOutputStream?class. The?FileOutputStream?class is based on the?OutputStream?class. That is how it gets most of its functionality.To use a file, declare a?File?variable using one of its constructors. One of the constructors takes one argument as a string, the name of the file or its complete path. Of course, if the file has an extension, you must include it. Here is an example:import java.io.File;public class Exercise { public static void main(String[] args) throws Exception {File fleExample = new File("Example.xpl"); }}The only real thing the?File?class does is to indicate that you are planning to use a file. It does not indicate what you will do with the file. You must specify whether you will create a new file or open an existing one.Creating a FileIf you want to create a new file, you must use a class that is equipped to write values to a file. To do this, you can use the?PrintWriter?class. The?PrintWriter?class is defined in the?java.iopackage. Therefore, if you want to use it, you can import it in your document. This would? be done as follows:import java.io.PrintWriter;public class Exercise { public static void main(String[] args) throws Exception { }}The?PrintWriter?class is based on (implements) the?Writer?class. The class is equipped with the necessary means of writing values to a file.Before using the class, declare a variable for it. This class is equipped with many constructors. One of the constructors takes as argument an?OutputStream?object. We saw that the File class is based on?OutputStream. This means that you can pass a File object to a?PrintWriterconstructor.? This would be done as follows:import java.io.File;import java.io.PrintWriter;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to use a fileFile fleExample = new File("Example.xpl"); // Create that file and prepare to write some values to it PrintWriter pwInput = new PrintWriter(fleExample); }}Writing to a FileAfter creating a?PrintWriter?object, you can write values to the file. To support this, the?PrintWriter?class is equipped with the?print()?and?println()?methods that is overloaded with various versions for each type of values (boolean,?char,?char[],?int,?float,?double,?String, or?Object). Therefore, to write a value to a file, call the appropriate version of the?PrintWriter.print()?method and pass the desired value. Here are examples:import java.io.File;import java.io.PrintWriter;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to use a fileFile fleExample = new File("Example.xpl"); // Create that file and prepare to write some values to it PrintWriter pwInput = new PrintWriter(fleExample);// Write a string to the filepwInput.println("Francine");// Write a string to the file pwInput.println("Mukoko");// Write a double-precision number to the filepwInput.println(22.85);// Write a Boolean value to the filepwInput.print(true); }}After using a?PrintWriter?object, you should free the resources it was using. To assist you with this, the PrintWriter class is equipped with the Close() method. Here is an example of calling:import java.io.File;import java.io.PrintWriter;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to use a fileFile fleExample = new File("Example.xpl"); // Create that file and prepare to write some values to it PrintWriter pwInput = new PrintWriter(fleExample);// Write a string to the filepwInput.println("Francine");// Write a string to the file pwInput.println("Mukoko");// Write a double-precision number to the filepwInput.println(22.85);// Write a Boolean value to the filepwInput.print(true); // After using the PrintWriter object, de-allocated its memory pwInput.close(); // For convenience, let the user know that the file has been created System.out.println("The file has been created."); }}Opening a FileBesides creating a file, the second most common operation performed on a file consists of opening one. You can open a file using the File class. As done previously, first declare a File variable and pass the name of the file to its constructor. Here is an example:import java.io.File;public class Exercise { public static void main(String[] args) throws Exception {// Incidate that you are planning to opena fileFile fleExample = new File("Example.xpl");Reading from a FileTo support the ability to read a value from a file, you can use the?Scanner?class. To support this operation, the?Scanner?class is equipped with a constructor that takes a?File?object as argument. Therefore, you can pass it a?File?variable you will have previously declared. Here is an example of declaring and initializing a variable for it:import java.io.File;import java.util.Scanner;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to opena fileFile fleExample = new File("Example.xpl"); // Prepare a Scanner that will "scan" the document Scanner opnScanner = new Scanner(fleExample); }}The values of a file are stored in or more lines. To continuously read the lines from the file, one at a time, you can use a?while?loop. In the?while?loop, continuously use the?Scanner?object that can read a line of value(s). In the while statement, to check whether the Scanner object has not gotten to the last line, you can check the status of its hasNext() method. As long as this method returns true, the Scanner reader has not gotten to the end of the file. Once the Scanner object has arrived to the end, this method would return false. Here is an example of implementing this scenario:import java.io.File;import java.util.Scanner;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to opena fileFile fleExample = new File("Example.xpl"); // Prepare a Scanner that will "scan" the document Scanner opnScanner = new Scanner(fleExample);// Read each line in the file while(opnScanner.hasNext()) { // Read each line and display its value System.out.println("First Name: " + opnScanner.nextLine()); System.out.println("Last Name: " + opnScanner.nextLine()); System.out.println("Hourly Salary: " + opnScanner.nextLine()); System.out.println("Is Full Time?: " + opnScanner.nextLine());} }}After using the?Scanner?object, to free the resources it was using, call its close() method. Here is an example:import java.io.File;import java.util.Scanner;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to opena fileFile fleExample = new File("Example.xpl"); // Prepare a Scanner that will "scan" the document Scanner opnScanner = new Scanner(fleExample);// Read each line in the file while( opnScanner.hasNext() ) { // Read each line and display its value System.out.println("First Name: " + opnScanner.nextLine()); System.out.println("Last Name: " + opnScanner.nextLine()); System.out.println("Hourly Salary: " + opnScanner.nextLine()); System.out.println("Is Full Time?: " + opnScanner.nextLine());} // De-allocate the memory that was used by the scanner opnScanner.close(); }}File managementChecking the Existence of a FileBesides writing to a file or reading from it, there are many other actions you may to perform on a file.If you try opening a file that does not exist, you would receive an error:Exception in thread "main" java.io.FileNotFoundException: Example1.xpl (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.util.Scanner.<init>(Unknown Source) at Exercise.main(Exercise.java:9)Therefore, before opening a file, you may want to check first whether it exists. To assist you with this, the File class is equipped with the?exists()?method. Here is an example of calling it:import java.io.File;import java.util.Scanner;public class Exercise { public static void main(String[] args) throws Exception {// Indicate that you are planning to opena fileFile fleExample = new File("Example1.xpl"); // Find out if the file exists already if( fleExample.exists() ) { // Prepare a Scanner that will "scan" the document Scanner opnScanner = new Scanner(fleExample); // Read each line in the file while( opnScanner.hasNext() ) {// Read each line and display its value System.out.println("First Name: " + opnScanner.nextLine()); System.out.println("Last Name: " + opnScanner.nextLine()); System.out.println("Hourly Salary: " + opnScanner.nextLine()); System.out.println("Is Full Time?: " + opnScanner.nextLine()); } // De-allocate the memory that was used by the scanner opnScanner.close(); } else // if( !fleExample.exists() ) System.out.println("No file exists with that name"); }}Deleting a FileTo delete a file, you can call the?delete()?method of the?File?class. ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.