SlideShare a Scribd company logo
Multithreading in Java
• Multithreading in java is a process of executing
multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
• But we use multithreading than multiprocessing
because threads share a common memory area. They
don't allocate separate memory area so saves
memory, and context-switching between the threads
takes less time than process.
• Java Multithreading is mostly used in games,
animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
2) You can perform many operations together
so it saves time.
3) Threads are independent so it doesn't affect
other threads if exception occur in a single
thread
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
• Each process have its own address in memory i.e. each process allocates separate
memory area.
• Process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• Thread is lightweight.
• Cost of communication between the thread is low.
What is Thread in java
• A thread is a lightweight sub process, a
smallest unit of processing. It is a separate
path of execution.
• Threads are independent, if there occurs
exception in one thread, it doesn't affect
other threads. It shares a common memory
area.
• As shown in the above figure, thread is executed inside the
process. There is context-switching between the threads.
• There can be multiple processes inside the OS and one
process can have multiple threads.
Java Thread class
• Thread class is the main class on which java's
multithreading system is based.
• Thread class provide constructors and
methods to create and perform operations on
a thread.
• Thread class extends Object class and
implements Runnable interface.
Java Thread Methods
Life cycle of a Thread (Thread States)
• A thread can be in one of the five states.
• According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated.
• There is no running state.
• But for better understanding the threads, we are explaining
it in the 5 states.
• The life cycle of the thread in java is controlled by JVM. The
java thread states are as follows:
– New
– Runnable
– Running
– Non-Runnable (Blocked)
– Terminated
Life cycle of a Thread
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread
• There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Thread class:
• Thread class provide constructors and methods to create and
perform operations on a thread.
• Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
– Thread()
– Thread(String name)
– Thread(Runnable r)
– Thread(Runnable r,String name)
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
• The Runnable interface should be implemented by any
class whose instances are intended to be executed by a
thread.
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
• start() method of Thread class is used to start a newly
created thread.
• It performs following tasks: A new thread starts(with new
callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run()
method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
• If you are not extending the Thread class,your
class object would not be treated as a thread
object.
• So you need to explicitely create Thread class
object.
• We are passing the object of your class that
implements Runnable so that your class run()
method may execute.
Java I/O
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
• We can perform file handling in java by Java I/O API.
Stream
• A stream is a sequence of data.In Java a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
• In java, 3 streams are created for us automatically. All these streams are attached
with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
• Let's see the code to print output and error message to the console.
• System.out.println("simple message");
• System.err.println("error message");
• Let's see the code to get input from console.
• int i=System.in.read();//returns ASCII code of 1st character
• System.out.println((char)i);//will print the character
OutputStream vs InputStream
• The explanation of OutputStream and InputStream classes are
given below:
OutputStream
• Java application uses an output stream to write data to a
destination, it may be a file, an array, peripheral device or socket.
InputStream
• Java application uses an input stream to read data from a source, it
may be a file, an array, peripheral device or socket.
• Let's understand working of Java OutputStream and InputStream by
the figure given below.
• OutputStream class
• OutputStream class is an abstract class. It is the super class of
all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink.
OutputStream Hierarchy
• InputStream class
• InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
InputStream Hierarchy
Java FileOutputStream Class
• Java FileOutputStream is an output stream used for writing
data to a file.
• If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well
as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use
FileWriter than FileOutputStream.
FileOutputStream class declaration
• Let's see the declaration for Java.io.FileOutputStream class:
• public class FileOutputStream extends OutputStream
Java FileOutputStream Example 1: write byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
Java FileInputStream Class
• Java FileInputStream class obtains input bytes from a
file. It is used for reading byte-oriented data (streams
of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading
streams of characters, it is recommended to use
FileReader class.
Java FileInputStream class declaration
• Let's see the declaration for java.io.FileInputStream
class:
• public class FileInputStream extends InputStream
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which
is 87 (in byte form). To see the text, you need to convert it into character.
Output:
W
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt

More Related Content

Similar to web programming-Multithreading concept in Java.ppt (20)

PPTX
Multithreading in java
junnubabu
 
PPTX
Threads in Java
HarshaDokula
 
PPTX
Multithreading.pptx
ssuserfcae42
 
PPT
multhi threading concept in oops through java
Parameshwar Maddela
 
PPTX
Multithreading in java
Raghu nath
 
PPT
Md09 multithreading
Rakesh Madugula
 
PDF
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
PPTX
Internet Programming with Java
kavitha muneeshwaran
 
PPT
BCA MultiThreading.ppt
sarthakgithub
 
PPTX
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
PDF
Java threads
Prabhakaran V M
 
PPTX
Multi threading
Mavoori Soshmitha
 
PPTX
Lecture 23-24.pptx
talha ijaz
 
PPTX
Multithreading in java
Monika Mishra
 
PPTX
Multithreading programming in java
Elizabeth alexander
 
PDF
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
DOCX
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
PPT
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
PPTX
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading in java
junnubabu
 
Threads in Java
HarshaDokula
 
Multithreading.pptx
ssuserfcae42
 
multhi threading concept in oops through java
Parameshwar Maddela
 
Multithreading in java
Raghu nath
 
Md09 multithreading
Rakesh Madugula
 
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Internet Programming with Java
kavitha muneeshwaran
 
BCA MultiThreading.ppt
sarthakgithub
 
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
Java threads
Prabhakaran V M
 
Multi threading
Mavoori Soshmitha
 
Lecture 23-24.pptx
talha ijaz
 
Multithreading in java
Monika Mishra
 
Multithreading programming in java
Elizabeth alexander
 
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 

More from mcjaya2024 (20)

PPT
cyber forensics Email Investigations.ppt
mcjaya2024
 
PPT
Cell Phone and Mobile Devices Forensics.ppt
mcjaya2024
 
PPT
Computer Forensics Analysis and Validation.ppt
mcjaya2024
 
PPT
cyber forensics Footprinting and Scanning.ppt
mcjaya2024
 
PPT
cyber forensics-enum,sniffing,malware threat.ppt
mcjaya2024
 
PPT
Classless Interdomain Data Routing CIDR.ppt
mcjaya2024
 
PPT
Computer Network in Network software.ppt
mcjaya2024
 
PPT
web program-Extended MARKUP Language XML.ppt
mcjaya2024
 
PPTX
Web programming-Introduction to JSP.pptx
mcjaya2024
 
PPT
web program -Life cycle of a servlet.ppt
mcjaya2024
 
PPT
web programmimg- concpt in JAVABEANS.ppt
mcjaya2024
 
PPT
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
PPT
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
PPT
Processing Crime and Incident Scenes.ppt
mcjaya2024
 
PPT
Working with Windows and DOS Systems (1).ppt
mcjaya2024
 
PDF
enterprise resource plnning ERP vendors.pdf
mcjaya2024
 
PPT
ERP and elctronic commerce online12.ppt
mcjaya2024
 
PPT
Enterprise resourse planning ERPlife cycle.ppt
mcjaya2024
 
PPT
Project Management Issues in ERP IS 6006.ppt
mcjaya2024
 
PDF
mySAP_Supply_Chain_Management_Solution_Map.pdf
mcjaya2024
 
cyber forensics Email Investigations.ppt
mcjaya2024
 
Cell Phone and Mobile Devices Forensics.ppt
mcjaya2024
 
Computer Forensics Analysis and Validation.ppt
mcjaya2024
 
cyber forensics Footprinting and Scanning.ppt
mcjaya2024
 
cyber forensics-enum,sniffing,malware threat.ppt
mcjaya2024
 
Classless Interdomain Data Routing CIDR.ppt
mcjaya2024
 
Computer Network in Network software.ppt
mcjaya2024
 
web program-Extended MARKUP Language XML.ppt
mcjaya2024
 
Web programming-Introduction to JSP.pptx
mcjaya2024
 
web program -Life cycle of a servlet.ppt
mcjaya2024
 
web programmimg- concpt in JAVABEANS.ppt
mcjaya2024
 
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Processing Crime and Incident Scenes.ppt
mcjaya2024
 
Working with Windows and DOS Systems (1).ppt
mcjaya2024
 
enterprise resource plnning ERP vendors.pdf
mcjaya2024
 
ERP and elctronic commerce online12.ppt
mcjaya2024
 
Enterprise resourse planning ERPlife cycle.ppt
mcjaya2024
 
Project Management Issues in ERP IS 6006.ppt
mcjaya2024
 
mySAP_Supply_Chain_Management_Solution_Map.pdf
mcjaya2024
 
Ad

Recently uploaded (20)

PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
smart lot access control system with eye
rasabzahra
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
smart lot access control system with eye
rasabzahra
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Ad

web programming-Multithreading concept in Java.ppt

  • 2. • Multithreading in java is a process of executing multiple threads simultaneously. • Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. • But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. • Java Multithreading is mostly used in games, animation etc.
  • 3. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread
  • 4. Multitasking • Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: • Process-based Multitasking(Multiprocessing) • Thread-based Multitasking(Multithreading) 1) Process-based Multitasking (Multiprocessing) • Each process have its own address in memory i.e. each process allocates separate memory area. • Process is heavyweight. • Cost of communication between the process is high. • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. 2) Thread-based Multitasking (Multithreading) • Threads share the same address space. • Thread is lightweight. • Cost of communication between the thread is low.
  • 5. What is Thread in java • A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. • Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.
  • 6. • As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. • There can be multiple processes inside the OS and one process can have multiple threads.
  • 7. Java Thread class • Thread class is the main class on which java's multithreading system is based. • Thread class provide constructors and methods to create and perform operations on a thread. • Thread class extends Object class and implements Runnable interface.
  • 9. Life cycle of a Thread (Thread States) • A thread can be in one of the five states. • According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. • There is no running state. • But for better understanding the threads, we are explaining it in the 5 states. • The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: – New – Runnable – Running – Non-Runnable (Blocked) – Terminated
  • 10. Life cycle of a Thread
  • 11. 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated A thread is in terminated or dead state when its run() method exits.
  • 12. How to create thread • There are two ways to create a thread: • By extending Thread class • By implementing Runnable interface. Thread class: • Thread class provide constructors and methods to create and perform operations on a thread. • Thread class extends Object class and implements Runnable interface. Commonly used Constructors of Thread class: – Thread() – Thread(String name) – Thread(Runnable r) – Thread(Runnable r,String name)
  • 13. Commonly used methods of Thread class: • public void run(): is used to perform action for a thread. • public void start(): starts the execution of the thread.JVM calls the run() method on the thread. • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. • public void join(): waits for a thread to die. • public void join(long miliseconds): waits for a thread to die for the specified miliseconds. • public int getPriority(): returns the priority of the thread. • public int setPriority(int priority): changes the priority of the thread. • public String getName(): returns the name of the thread. • public void setName(String name): changes the name of the thread. • public Thread currentThread(): returns the reference of currently executing thread. • public int getId(): returns the id of the thread. • public Thread.State getState(): returns the state of the thread. • public boolean isAlive(): tests if the thread is alive. • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. • public void suspend(): is used to suspend the thread(depricated). • public void resume(): is used to resume the suspended thread(depricated). • public void stop(): is used to stop the thread(depricated). • public boolean isDaemon(): tests if the thread is a daemon thread. • public void setDaemon(boolean b): marks the thread as daemon or user thread. • public void interrupt(): interrupts the thread. • public boolean isInterrupted(): tests if the thread has been interrupted. • public static boolean interrupted(): tests if the current thread has been interrupted.
  • 14. Runnable interface: • The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. • Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: • start() method of Thread class is used to start a newly created thread. • It performs following tasks: A new thread starts(with new callstack). • The thread moves from New state to the Runnable state. • When the thread gets a chance to execute, its target run() method will run.
  • 15. 1) Java Thread Example by extending Thread class class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output:thread is running...
  • 16. 2) Java Thread Example by implementing Runnable interface class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } } Output:thread is running...
  • 17. • If you are not extending the Thread class,your class object would not be treated as a thread object. • So you need to explicitely create Thread class object. • We are passing the object of your class that implements Runnable so that your class run() method may execute.
  • 18. Java I/O • Java I/O (Input and Output) is used to process the input and produce the output. • Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. • We can perform file handling in java by Java I/O API. Stream • A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. • In java, 3 streams are created for us automatically. All these streams are attached with console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream • Let's see the code to print output and error message to the console. • System.out.println("simple message"); • System.err.println("error message");
  • 19. • Let's see the code to get input from console. • int i=System.in.read();//returns ASCII code of 1st character • System.out.println((char)i);//will print the character OutputStream vs InputStream • The explanation of OutputStream and InputStream classes are given below: OutputStream • Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. InputStream • Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket. • Let's understand working of Java OutputStream and InputStream by the figure given below.
  • 20. • OutputStream class • OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
  • 22. • InputStream class • InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes.
  • 24. Java FileOutputStream Class • Java FileOutputStream is an output stream used for writing data to a file. • If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. FileOutputStream class declaration • Let's see the declaration for Java.io.FileOutputStream class: • public class FileOutputStream extends OutputStream
  • 25. Java FileOutputStream Example 1: write byte import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); fout.write(65); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } } Output: Success... The content of a text file testout.txt is set with the data A. testout.txt A
  • 26. Java FileInputStream Class • Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. Java FileInputStream class declaration • Let's see the declaration for java.io.FileInputStream class: • public class FileInputStream extends InputStream
  • 27. import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=fin.read(); System.out.print((char)i); fin.close(); }catch(Exception e){System.out.println(e);} } } Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content: Welcome to javatpoint. After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character. Output: W