Java 3rd Unit
Java 3rd Unit
Java 3rd Unit
InputStream class:
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
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.
OutputStream Hierarchy:
3.2 - EXPLAIN HOW TO READ AND WRITE DATA THROUGH CONSOLEINPUT AND
OUTPUT STREAMS AND WRITE A SAMPLE PROGRAM :
Ways to read input from console in Java: In Java, there are four different ways for
reading input from the user in the command line environment (console).
1. Using Buffered Reader Class: This is the Java classical method to take input, introduced
in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the
user in the command line.
• The input is buffered for efficient reading.
• The wrapping code is hard to remember.
Implementation:
// Java program to demonstrate BufferedReader
import java. io. BufferedReader;
import java. io. IOException;
import java. io. InputStreamReader;
public class Test{
public static void main (String[args) throws IOException{
// enter data using BufferedReader
BufferedReader reader = new BufferedReader (new
InputStreamReader (System. in) ) ;
// Reading data using readLine
String name = reader. readLine () ;
// Printing the read line
System. out. println (name) ;
(A.")
}
}
Input: Kiran
Output: Kiran
Note: To read other types, we use functions like Integer. parselnt),
Double.parseDouble(). To read multiple values, we use split ).
2. Using Scanner Class: This is probably the most preferred method to take input. The
main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however, it is also can be used to read input from the user in the command
line.
• Convenient methods for parsing primitives (nextInt), nextFloat (), ...) from the
tokenized input.
• Regular expressions can be used to find tokens.
• The reading methods are not synchronized.
// Java program to demonstrate working of Scanner in Java
importjava.util. Scanner; class Get InputFromUser l
public static void main (String args [])
// Using Scanner for Getting Input from User
Scanner in = new Scanner (System. in) ;
String s = in. nextLine ();
System. out. println ("You entered string " + s) ;
int a = in. nextInt () ;
System. outprintin ("You entered integer " + a) ;
float b = in.nextFloat () ;
System. outprintln ("You entered float " + b) ;
}
}
Input:KiranForJava
12
3.4
Output: You entered string Kiran For Java
You entered integer 12
You entered float 3.4
3. Using Console Class: It has been becoming a preferred way for reading user's input
from the command line. In addition, it can be used for reading password-like input
without echoing the characters entered by the user; the format string syntax can also be
used (like System.out.printf()).
Advantages:
1. Reading password without echoing the entered characters.
2. Reading methods are synchronized.
3. Format string syntax can be used.
4. Does not work in non-interactive environment (such as in an IDE).
// Java program to demonstrate working of System. console ()
// Note that this program does not work on IDEs as System. console ()
may require console public class Sample
public static void main (Stringll args)
// Using Console to input data from user
String name = System. console () .readLine () ;
System. outprintln ("You entered string " + name) ;
Input: KiranForJava
Output: You entered string KiranForJava
4. Using Command line argument:
• This is most used user input for competitive coding.
• The command-line arguments are stored in the String format.
• The parselnt method of the Integer class converts string argument intoInteger. Similary
,for float & others during e xecution.
• The usage of args [] comes into existence in this input form.
• The passing of information takes place during the program run.
• The command line is given to args[] These programs have to be run on cmd.
Code: // Program to check for command line arguments
class Main {
public static void main (String(] args){
// check if length of args array is greater than 0
if (args. length › 0) {
System. out. println ("The command line arguments are:");
// iterating the args array and printing the command line
arguments
for (String val : args){
System. out. println (val) ;
}
else
System. outprintln ("No command line " + "arguments found.") ;
}
}
Command Line Arguments: java Main Hello World
Output:
The command line arguments are: Hello World
Ways to write output to console in Java: The following two methods are used to write
the output data to console in Java.
Method1: Writing with System.out.println
Ex: System.out.println ("Hello, world!");
Program output: Hello, world!
Method2: Writing with printf()
The printf(String format, Object... args) method takes an output string and multiple
parameters which are substituted in the given string to produce the formatted output
content. This formatted output is written in the console.
Ex: String name = "Lokesh";
int age = 38;
console. printf("My name is %s and my age is %d", name, age);
Program output : My name is Lokesh and my age is 38
All these methods will throw an exception named lOException when any error
encounters.
Java DatalnputStream Example Program:
Let's take an example program where we will write primitive data types in a file, then
read data from the file, and display them on the screen. Look at the following source
code below.
Program:
packagejavaProgram;
import java.io. DataInputStream; import java. io. DataOutputStream; import java. io.
FileInputStream; import java. 10.FileOutputStream;
import java. io. IOException;
public class DataInputStreamEx 1{
public static void main (String[] args) throws IOException{
String filepath = "D: | \myfileoutdat" ;
// Create a FileOutputStream object to connect with myfileout. dat
file.
FileOutputStreamfos = new FileOutputStream (filepath) ;
// Create a DataOutputStream object to wrap on fos.
DataOutputStream dos = new DataOutputStream (fos) ;
// Write following primitive data to the "myfileoutdat" file.
doswriteUTF ("Welcome to Java world") ;
doswriteInt (1246) ;
dos. writeDouble (125.25) ; dos. writeBoolean (true) ;
doswriteChar ('S') ;
dos. close () ; fos. close () ;
// Reading data from the "myfileout.dat" file.
FileInputStreamfis = new FileInputStream (filepath) ;
DataInputStream dis = new DataInputStream (fis) ;
System. outprintin(dis.readUTE()) ;
System. out. println (dis.readInt ()) ;
System. out. printin (dis.readDouble ()) ;
System. outprintln(dis. readBoolean ()) ;
System. outprintln (dis.readChar ()) ;
dis. close () ;
fis. close () ;
}
}
Output:
Welcome to Java world
1246
125.25
true
S
In this program, we have performed reading and writing primitive data types by
wrapping DatalnputStream on FileInputStream.
The program first creates "myfileout.dat" file on the mentioned filepath and then writes
the string and primitive data types into it using data output stream.
At the end of writing, streams are closed using close() method.
DataOutputStream in Java | Methods, Example:
It enables us conveniently to write strings and all primitive data types such as boolean,
int, float, long, etc to a stream. Java DataOutput Stream first converts primitive-type
values or strings into bytes and then writes them to the underlying output stream in an
appropriate way. Using data input stream, we can then read the data back in. Thus,
DataOutputStream works as wrappers on the existing output stream to filter data in the
original stream.
Java DataOutputStream class declaration:
DataOutputStream class extends Filter Output Stream class that extends Output Stream. It
implements the interface Data Output to use methods defined in the Data Output
interface. The general declaration for Data Output Stream class in Java is given below:
public class Data Output Stream extends Filter Output Stream implements Data Output.
Constructor of DataOutputStream class:
DataOutputStream class defines only a single constructor in Java that is as
follows:
DataOutputStream (OutputStreamoutputStream):
This constructor creates a DataOutputStream object that uses the specifie underlying
Output Stream. Here, output Stream defines the output stream which data will be
written.
A data output stream object for output can be created as follows:
File Output Stream fos = new File Output Stream (String filename);
Data Output Stream dos = new DataOutputStream(fos);
These two statements basically wrap dos on fos and use it as a filter. Look at the figure
below.
All of these methods can throw an exception named lOException if any error occurs.
Java DataOutputStream Example Program:
Let's take a simple example program where we will perform reading and writing
operations using DatalnputStream and DataOutputStream. Look at the following source
code below.
Program code 1:
packagejavaProgram
import java.io. DataInputStream;
import java. io. DataOutputStream;
import java.io. FileInputStream;
import java. io. FileOutputStream;
import java. io. IOException;
public class DataOutputStreamEx 1{
public static void main (String[]args) throws IOException{
String filepath = "D: | \myfileout.dat";
Create a FileOutputStream object to connect with myfileout.datafile.
FileOutputStreamfos = new FileOutputStream (filepath) ;
// Create a DataOutputStream object to wrap on fos.
DataOutputStream dos = new DataOutputStream (fos) ;
// Write following primitive data to the "myfileout.dat" file.
doswriteUTF ("Welcome to Java World ") ; dos writeInt (124) :
doswriteDouble (125.25) ; dos. writeBoolean (true) ;
doswriteChar ('A');
dos. close () ; fos. close () :
// Read data from the "myfileout.dat" file.
File InputStreamfis = new File InputStream (filepath) ;
DataInputStream dis = new DataInputStream (fis) ;
System. outprintin (dis. readUTF () ) ;
System. outprintln(dis.readInt ()) ;
System. outprintin (dis.readDouble () ) ;
System.outprintln(dis.readBoolean ()) ;
System. outprintin(dis. readchar ()) ;
dis. close () ;
fis.close () ;
}
}
Output: Welcome to Java World
124
125.2
true
This program first creates "myfileout.dat" file on the mentioned filepath and then writes
the string and primitive data types into it using data output stream.
At the end of writing, streams are closed using close() method.
3.4 - EXPLAIN VARIOUS FILE ACCESS OPERATIONS BY USING FILE STREAMS AND
WRITE A SAMPLE PROGRAM:
• File Handling is an integral part of any programming language as file handling enables
us to store the output of any particular program in a file and allows us to perform certain
operations on it. In simple words, file handling means reading and writing data to a file.
• In Java, with the help of File Class, we can work with files.
• This File Class is inside the java.io package.
• The File class can be used by creating an object of the class and then specifying the
name of the file.
Java File Class Methods :
The following table depicts several File Class methods:
Method Name Description Return
Type
can Read() It tests whether the file is readable Boolean
or not.
can Write() It tests whether the file is writable Boolean
or not.
create New File() It creates an empty file. Boolean
delete() It deletes a file. Boolean
exists() It tests whether the file exists or Boolean
not.
length() Returns the size of the file in bytes. Long
getName() Returns the name of the file. String
list() Returns an array of the files in the String[]
directory.
mkdir() Creates a new directory. Boolean
get Absolute Path() Returns the absolute pathname of String
the file.
File operations in Java:
The following are the several operations that can be performed on a file in Java :
Create a File
Read from a File
Write to a File
Delete a File
Now let us study each of the above operations in detail.
1. Create a File
In order to create a file in Java, you can use the createNewFile ) method.
If the file is successfully created, it will return a Boolean value true and false if the file
already exists.
Example program:
// Import the File class
import java.io. File;
// Import the IOException class to handle errors
import java. io. IOException;
public class KfJ {
public static void main (String[] args){
try {
File Obj = new File ("myfile.txt") ;
if (Obj. createNewFile ()) l
System. outprintin ("File created: "+ Obj. getName ()) ;
}
else {
System. out. println ("File already exists.") ;
}
catch (IOException e) {
System. outprintln ("An error has occurred.") ;
}
}
}
Output:
File created:myfile
2. Read from a File: We will use the Scanner class in order to read contents from a file.
Following is a demonstration of how to read contents from a file in Java :
// Import the File class
import java.io. File;
// Import this class for handling errors
import java. io. FileNotFoundException;
// Import the Scanner class to read content from text files
import java. util. Scanner;
public class KfJ {
public static void main (String[l args)
try {
File Obj = new File ("myfile.txt");
Scanner Reader = new Scanner (Obj ) ;
while (Reader. hasNextLine ()) {
String data = Reader. nextLine () ;
System. out. println (data) ;}
Reader. close () ;}
catch (FileNotFoundException e) {
System. outprintin ("An error has occurred.") ;
}
}
}
Output:
This is java programming
3. Write to a File: We use the FileWriter class along with its write() method in order to
write some text to the file.
Following is a demonstration of how to write text to a file in Java :
// Import the FileWriter class
import java.io. FileWriter;
// Import the IOException class for handling errors
import java. io. IOException;
public class Kfj{
public static void main (String [] args){
try {
FileWriter Writer= new FileWriter ("myfile. txt") ;
Writer. write ("Files in Java are seriously good!!");
Writer. close () ;
System. outprintin ("Successfully written.");
catch (IOException e) {
System. out. printin ("An error has occurred.") ;
}
}
}
Output:
Successfully written.
4. Delete a File: We use the delete ) method in order to delete a file.
Following is a demonstration of how to delete a file in Java :
// Import the File class
import java.io. File;
public class KEJ {
public static void main (String[]args)
{
File Obj = new File ("myfile.txt") ;
if (Obj. delete ()) {
System. out.printIn("The deleted file is : "+ Obj. getName ()) ;}
else {
System.out.printin ("Failed in deleting the file."); }
}
}
Output:
The deleted file is :myfile
3.5- WHAT IS A COLLECTION FRAMEWORK AND HIERARCHY OF COLLECTION
FRAMEWORK AND WRITE A SAMPLE PROGRAM:
The Collection in Java is a framework that provides architecture to store and manipulate
the group of objects, i.e. Java Collection means a single unit of objects i.e., a group.
• Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
• Collection framework has :
1. Interfaces and its implementations, i.e., classes
2. Algorithm
• Java Collection framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Hierarchy of Collection Framework:
Let us see the hierarchy of Collectionframework. The java, util package contains all the
classes and interfaces for the collection framework.
3.6 LIST INTERFACE:
->List is an interface which can store multiple values of a
singledata type
->this is used to store multiple values under a single variable by implementing the list
ARRAY LIST:
->In java array list class provides resizable array and implements the list Interface.
->It implements all list operations and it also permits all elements including null
NOTE :The array list has default size of ‘0’ and capacity ‘10’ if the size of elements in
array list is more than the capacity, the capacity will be doubled.
Program:
importjava.util.*;
classArrayListDemo {
public static void main(String[] args) {
ArrayList<String> v = new ArrayList<>();
v.add("a");
v.add("b");
v.add("c");
System.out.println(v);
ArrayList<String> v1 = new ArrayList<>();
v1.add("d");
System.out.println(v1);
v1.addAll(v);
System.out.println(v1);
v1.removeAll(v);
System.out.println(v1);
v1.clear();
System.out.println(v1);
}
}
Output:
[a, b, c]
[d]
[d, a, b, c]
[d]
[]
LINKED LIST:
->The linked list lass extends abstract sequential list and implements the list interface.
->It has address and pointers that are used to link the elements and each element in the
linked list consist of two parts
1) Head: Thehead of the list refers to the first node address of the list.
2) Tail: Thetail of the list refers to the next node address of the list.
Program:
importjava.util.*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> v = new LinkedList<>();
v.add("Apple");
v.add("Banana");
v.add("Orange");
v.add("Grapes");
System.out.println(v);
v.addFirst("Pineapple");
v.addLast("Mango");
System.out.println( v);
String firstElement = v.getFirst();
System.out.println("First Element: " + firstElement);
String lastElement = v.getLast();
System.out.println("Last Element: " + lastElement);
v.removeFirst();
v.removeLast();
System.out.println("LinkedList after removing first and last elements: " + v);
}
}
Output:
[Apple, Banana, Orange, Grapes][Pineapple, Apple, Banana, Orange, Grapes,
Mango]
First Element: Pineapple
Last Element: Mango
LinkedList after removing first and last elements: [Apple, Banana, Orange, Grapes]
Vector Class :
->The Vector class implements a grow able array of objects. Vectors fall in legacy
classes, but now it is fully compatible with collections. It is found in java.util
package and implement the List interface.
Program:
import java .util.*;
class vector{
public static void main(String [] args){
Vector <String> v1=new Vector<>();
System.out.println(v1);
System.out.println(v1.size());
System.out.println(v1.capacity());
v1.add("a");
v1.add("b");
v1.add("c");
System.out.println(v1);
System.out.println(v1.get(2));
System.out.println(v1.remove(1));
System.out.println(v1);
v1.clear();
System.out.println(v1)
}
}
Output:
[]
0
10
[a, b, c]
c
b
[a, c]
[]
STACK CLASS:
->It is a subclass of vector and it implements FIFO data structure.
->Stack contains all methods of vector class and also provide it’s methods.
Program:
import java .util.*;
class stack{
public static void main(String [] args){
Stack <String> v=new Stack<>();
v.push("a");
v.push("b");
v.push("c");
System.out.print(v.pop());
System.out.print(v.peek());
System.out.print(v.search("c"));
}
}
Output:
C b -1
QUEUE INTERFACE:
->Queue interface maintains FIFO order and it can be defined an ordered list
PRIORITY QUEUE:
->The priority queue class implements queue interface.
->It holds the elements or objects which are to be processed by their priorities, it does
not allow null values.
Program:
importjava.util.*;
classPriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer>pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
pq.offer(10);
System.out.println("PriorityQueue: " + pq);
while (!pq.isEmpty()) {
System.out.println("Removed: " + pq.poll());
}
}
}
Output:
PriorityQueue: [1, 2, 8, 5, 10]
Removed: 1
Removed: 2
Removed: 5Removed: 8
Removed: 10
ARRAY DEQUEUE:
->The interface called Deque is present in java.util package. It is the subtype of the
interface queue. The Deque supports the addition as well as the removal of elements
from both ends of the data structure.
-> the stack supports the Last In First Out (LIFO) operation, and the operation First In
First Out is supported by a queue.
Program:
importjava.util.*;
classArrayQueueExample {
public static void main(String[] args) {
ArrayDeque<Integer>pq = new ArrayDeque<>();
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
pq.offer(10);
System.out.println(pq);
System.out.println(pq.poll());
System.out.println(pq);
pq.pollFirst();
System.out.println(pq);
pq.pollLast();
System.out.println(pq);
System.out.println(pq.peek());
}
}
Output:
[5, 2, 8, 1, 10]
5
[2, 8, 1, 10]
[8, 1, 10]
[8, 1]
8
SET INTERFACE:
->It accepts unique elements only and it prints the data randomly.
->It is an unordered collection of objects in which duplicate values cannot be stored. It is
an interface that implements the mathematical set.
HASH SET:
->Java Hash Set class implements the Set interface, backed by a hash table which is
actually a Hash Map instance. No guarantee is made as to the iteration order of the hash
sets which means that the class does not guarantee the constant order of elements over
time.
Program:
importjava.util.*;
classHashMapExample {
public static void main(String[] args) {
HashSet<Integer> h = new HashSet<>();
h.add(5);
h.add(9);
h.add(7);
System.out.println(h);
for (Integer i : h) {
System.out.println(i);
}
}
}
Output:
[5, 7, 9]
5
7
9
TREE SET:
-> Tree Set is one of the most important implementations of the Sorted Set interface in
Java that uses a Tree for storage. The ordering of the elements is maintained by a set
using their natural ordering whether or not an explicit comparator is provided.
Program:
importjava.util.*;
class h1 {
public static void main(String[] args) {
TreeSet<Integer>treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(3);
treeSet.add(8);
treeSet.add(2);
System.out.println(treeSet);
treeSet.remove(3);
System.out.println(treeSet);
}
}
Output:
[2, 3, 5, 8]
[2, 5, 8]
MAP INTERFACE:
->In Java, Map Interface is present in java.util package represents a mapping between a
key and a value. Java Map interface is not a subtype of the Collection interface.
Therefore it behaves a bit differently from the rest of the collection types. A map
contains unique keys.
HASH TABLE:
-> The Hash class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. To successfully store and retrieve objects from a
hash table, the objects used as keys must implement the hash Code method and the
equal’s method.
Program:
importjava.util.*;
classHashTableExample {
public static void main(String[] args) {
HashTable<String, Integer>ht = new HashTable<>();
hashMap.put("sai", 25);
hashMap.put("Alice", 30);
hashMap.put("Bob", 35);
System.out.println(hashMap);
hashMap.remove("Alice");
System.out.println(hashMap);
}
}
Output:
{Bob=35, Alice=30, sai=25}
{Bob=35, sai=25}
Output :
India
Australia
England
Bangladesh
South Africa
Syntax for Listlterator:
public interface Listlterator<E> extends Iterator < E>
Example program:
importjava.util.*;
public class ListIteratorTest {
public static void main (String[] args) {
List<String>listObject = new ArrayList<String> () ;
listObject. add ("Java") ;
listObject. add ("Selenium") ;
listObject. add ("Python" ) ;
listObject. add ("Java Script") ;
listObject. add ("Cloud Computing") ;
ListIterator it = listobject. listIterator () ;
System. outprintln ("Iterating the elements in forward direction:");
while (it.hasNext ()) {
System. out. println (it.next () );
System. outprintln ("-----------------------------------------------------------------") ;
System. outprintln ("Iterating the elements in backward direction:");
while(it.hasPrevious()){
System. out. println (it. previous ()) ;
}
}
}
Output:
Iterating the elements in forward direction:
Java
Selenium
Python
Java Script
Cloud Computing
-----------------------------------------------------------------
Iterating the elements in backward direction:
Cloud Computing
Java Script
Python
Selenium
Java
3.10 - EXPLAIN ENUMSET & ENUMMAP CLASSES AND WRITE SAMPLE PROGRAM.
ENUMSET:
•The EnumSet is one of the specialized implementations of the Set interface for use with
theenumeration type. A few important features of EnumSet are as follows: It extends
AbstractSet class and implements Set Interface in Java.
PROGRAM:
importjava.util.*;
enum days{
Sunday,monday,tueday,wednesday
}
class h1{
public static void main(String []args){
Set <days> t=EnumSet.of(days.tueday,days.wednesday);
Iterator <days>i=t.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
Output:
tueday
wednesday
ENUMMAP:
•EnumMap is a specialized implementation of the Map interface for enumeration types.
It extends AbstractMap and implements the Map interface in Java. It belongs to java. util
package
PROGRAM:
Java EnumMap Example:
importjava.util.*;
classEnumMapExample {
// create an enum
publicenum Days {
Monday, Tuesday, Wednesday, Thursday
}