JavaProgramming Unit-III
JavaProgramming Unit-III
OutputStream vs InputStream
OutputStream- Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
InputStream- Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
read(), read(byte b[]), read(byte b[], int n, int m), available(), skip(n), reset(), and close() methods.
write(), write(byte b[]), write(byte b[], int n, int m), close(), flush()
File I/O:
Example of reading and writing bytes from one file to another file.
import java.io.*;
Reader stream classes are designed to read character from the files. Reader class is the base class for all
other classes in his group. The classes and methods are functionally very similar to the input stream classes.
Like output stream classes, the writer stream classes are designed to perform all output operations on files.
only difference is that while output stream classes are designed to write bytes, the writer stream classes are
designed to write characters.
Example of reading and writing characters from one file to another file.
import java.io.*;
try
{
ins = new FileReader(inFile);
outs = new FileWriter(outFile);
int ch;
while((ch = ins.read()) != -1)
outs.write(ch);
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e)
{}
}
}
}
Note : pls. refer lab programs on File I/O.
Chapter-2-Multi Threading
Multithreading is a feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread.
So, threads are light-weight processes within a process.
Thread vs Process
Process Thread
A program in execution is often referred as A thread is a subset(part) of the process. Hence
process. it is called lightweight process
A process consists of multiple threads. A thread is a smallest part of the process that
can execute concurrently with other
parts(threads) of the process
A process has its own address space A thread uses the process’s address space and
share it with the other threads of that process
A process can communicate with other process A thread can communicate with other thread
by using inter-process communication. (of the same process) directly by using
methods like wait(), notify(), notifyAll().
A process does not have control over the A process does not have control over the
sibling process, it has control over its child sibling process, it has control over its child
processes only. processes only.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states.
Creating Threads
Example :
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}}}
output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
Example :
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +Thread.currentThread().getId()+”is running”);
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}}}
// Main class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}}}
OUTPUT:
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
• Thread class provides some inbuilt methods like yield(), interrupt() etc. that are not
available in Runnable interface, Runnable interface supports only run( ) method.
Thread Priority
Each thread has a priority.
Priorities are represented by a number between 1 and 10.
Thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
3 Thread Priority constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();}}
various methods can be called on Thread class object. These methods are very
useful when writing a multithreaded application.
Thread Synchronization
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Synchronization is better option where we want to allow only one thread to access the
shared resource.
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Concept of Lock
Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it.
A thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done
with them.
Example :
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5); } }
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}}
Output: 5
100
10
200
15
300
20
400
25
500
With synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}}
public class TestSynchronization2
{
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }
Output: 5
10
15
20
25
100
200
300
400
500
Inter-thread communication
1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
Syntax: public final void wait()throws InterruptedException
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax: public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll().
Chapter-3-java.util.package
The Collection framework represents a unified architecture for storing and manipulating a
group of objects.
List Interface
This interface represents a collection of elements whose elements are arranged in
sequentially ordered.
List maintains an ordered of elements means the order is retained in which we add
elements
We can insert elements into the list at any location.
The list allows storing duplicate elements in Java.
ArrayList, vector, and LinkedList are three concrete subclasses which implement
list interface.
Set Interface
This interface represents a collection of elements that contains unique elements.
Set interface does not maintain any order while storing elements and while
retrieving, we may not get the same order as we put elements.
Set does not allow any duplicate elements.
HashSet, LinkedHashSet, TreeSet classes implements the set interface
SortedSet Interface
This interface extends a set whose iterator transverse its elements according to
their natural ordering.
TreeSet implements the sorted interface.
Map Interface
LinkedList class
LinkedList class uses a doubly linked list to store the elements.
o LinkedList class can contain duplicate elements.
o LinkedList class maintains insertion order.
o LinkedList class is non synchronized.
o LinkedList class can be used as a list, stack or queue.
Constructor Description
boolean add(E e) It is used to append the specified element to the end of a list.
import java.util.*;
public class LinkedList1{
public static void main(String args[])
{
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
System.out.println("After adding elements to the list: "+ll);
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
}
}
OUTPUT:
Initial list of elements: []
After adding elements to the list: [Ravi, Vijay, Ravi, Ajay] After invoking addFirst(E e) method:
[Lokesh, Ravi, Vijay, Ravi, Ajay]
After invoking remove(object) method: [Lokesh, Ravi, Ravi, Ajay]
HashMap class
HashMap class implements the map interface by using a hash table. It inherits AbstractMap class
and implements Map interface
Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map<? extends K,? extends It is used to initialize the hash map by using the elements of the given
V> m) Map object m.
It is used to initializes the capacity of the hash map to the given
HashMap(int capacity)
integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of the hash
loadFactor) map by its arguments.
Example:
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 MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new HashMap<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()){
o int key=entry.getKey();
o Book b=entry.getValue();
o System.out.println(key+" Details:");
o System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
}
}
}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
TreeSet class
o TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. TreeSet class contains
unique elements only like HashSet.
o TreeSet class access and retrieval times are quiet fast.
o TreeSet class doesn't allow null element.
o TreeSet class is non synchronized.
o TreeSet class maintains ascending order.
Constructors
Constructor Description
It is used to construct an empty tree set that will be sorted in ascending
TreeSet()
order according to the natural order of the tree set.
TreeSet(Collection<? extends E> It is used to build a new tree set that contains the elements of the
c) collection c.
TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according to
comparator) given comparator.
It is used to build a TreeSet that contains the elements of the given
TreeSet(SortedSet<E> s)
SortedSet.
Methods
Method Description
It is used to add the specified element to this set if it is not already
boolean add(E e)
present.
boolean addAll(Collection<? extends It is used to add all of the elements in the specified collection to
E> c) this set.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
boolean isEmpty() It returns true if this set contains no elements.
It is used to remove the specified element from this set if it is
boolean remove(Object o)
present.
void clear() It is used to remove all of the elements from this set.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.
Example
import java.util.*;
class TreeSetDemo{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Highest Value: "+set.pollFirst());
System.out.println("Lowest Value: "+set.pollLast());
}
}
OUTPUT:
Highest Value: 12
Lowest Value: 66
StringTokenizer class
StringTokenizer class in Java is used to break a string into tokens.
Constructors
Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str,
creates StringTokenizer with specified string and delimeter.
String delim)
creates StringTokenizer with specified string, delimeter and
StringTokenizer(String str,
returnValue. If return value is true, delimiter characters are
String delim, boolean
considered to be tokens. If it is false, delimiter characters serve
returnValue)
to separate tokens.
Methods
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Example:
import java.util.StringTokenizer;
public class STDemo{
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 khan
Date class
Constructors:
Constructo Description
r
Date() Creates a date object representing current date and time.
Date(long Creates a date object for the given milliseconds since January 1,
milliseconds) 1970, 00:00:00 GMT.
Methods :
Method Description
boolean after(Date date) tests if current date is after the given date.
boolean before(Date date) tests if current date is before the given date.
boolean equals(Date date) compares current date with given date for equality.
void setTime(long time) changes the current date and time to given time.
Example:
Random class
Java Random class is used to generate a stream of pseudo random numbers.
Constructors:
Random(long seed): Creates a new random number generator using a single long seed
Methods
Methods Description
next() Generates the next pseudorandom number.
nextBoolean() Returns the next uniformly distributed pseudorandom boolean value
from the random number generator's sequence
nextByte() Generates random bytes and puts them into a specified byte array.
nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0
from the random number generator's sequence
nextFloat() Returns the next uniformly distributed pseudorandom Float value
between 0.0 and
1.0 from this random number generator's sequence
nextInt() Returns a uniformly distributed pseudorandom int value generated
from this random number generator's sequence
nextLong() Returns the next uniformly distributed pseudorandom long value
from the random number generator's sequence.
Example:
import java.util.Random;
public class JavaRandomExample2 {
public static void main(String[] args) {
Random random = new Random();
//return the next pseudorandom integer value
System.out.println("Random Integer value : "+random.nextInt());
// setting seed
long seed =20;
random.setSeed(seed);
//value after setting seed
System.out.println("Seed value : "+random.nextInt());
//return the next pseudorandom long value
Long val = random.nextLong();
System.out.println("Random Long value : "+val);
}}
Output: Random Integer value : 1294094433
Seed value : -1150867590
Random Long value : -7322354119883315205
Scanner Class
Scanner class is used to read the data from the keyboard
The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default.
Constructor :
Scanner in = new Scanner(System.in);
Modifier &
Method Description
Type
Boolean hasNext() It returns true if this scanner has another token in its input.
String next() It is used to get the next complete token from the scanner which is in use.
It scans the next token of the input into a boolean value and returns that
Boolean nextBoolean()
value.
Byte nextByte() It scans the next token of the input as a byte.
Double nextDouble() It scans the next token of the input as a double.
Float nextFloat() It scans the next token of the input as a float.
Int nextInt() It scans the next token of the input as an Int.
String nextLine() It is used to get the input string that was skipped of the Scanner object.
Long nextLong() It scans the next token of the input as a long.
Short nextShort() It scans the next token of the input as a short.
String toString() It is used to get the string representation of Scanner using.
Example:
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your college name: ");
String name = in.nextLine();
System.out.println("College Name is: " + name);
in.close();
} } output: Enter your college name: vjit
College Name is: vjit