UNIT 4 IO Programming
UNIT 4 IO Programming
For example, a
thread is born, started, runs, and then dies. The following diagram shows
the complete life cycle of a thread.
I/O programming: Text and Binary I/O, Binary I/O classes,
Object I/O, Random Access Files. Multithreading in java:
Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally,
Collections in java, Introduction to JavaBeans and Network
Programming
Multithreading
Java is a multi-threaded programming language which means we can
develop multi-threaded program using Java. A multi-threaded program
contains two or more parts that can run concurrently and each part can Following are the stages of the life cycle −
handle a different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs. New − A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is also
By definition, multitasking is when multiple processes share common referred to as a born thread.
processing resources such as a CPU. Multi-threading extends the idea Runnable − After a newly born thread is started, the thread
of multitasking into applications where you can subdivide specific becomes runnable. A thread in this state is considered to be executing
operations within a single application into individual threads. Each of its task.
the threads can run in parallel. The OS divides processing time not only Waiting − Sometimes, a thread transitions to the waiting state
among different applications, but also among each thread within an while the thread waits for another thread to perform a task. A thread
application. transitions back to the runnable state only when another thread signals
the waiting thread to continue executing.
Multi-threading enables you to write in a way where multiple activities Timed Waiting − A runnable thread can enter the timed waiting
can proceed concurrently in the same program. state for a specified interval of time. A thread in this state transitions
back to the runnable state when that time interval expires or when the
Life Cycle of a Thread event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated
state when it completes its task or otherwise terminates.
Thread: Thread-2, 1
30. RunnableDemo R2 = new RunnableDemo( "Thread-2");
31. R2.start(); Thread Thread-1 exiting.
32. }
33. } Thread Thread-2 exiting.
Step 1 }
You will need to override run( ) method available in Thread class. This public void run() {
method provides an entry point for the thread and you will put your
complete business logic inside this method. Following is a simple syntax System.out.println("Running " + threadName );
of run() method −
try {
public void run( )
for(int i = 4; i > 0; i--) {
Once Thread object is created, you can start it by calling start() method, // Let the thread sleep for a while.
which executes a call to run( ) method. Following is a simple syntax of
start() method − Thread.sleep(50);
void start( ); }
Here is the preceding program rewritten to extend the Thread − System.out.println("Thread " + threadName + " interrupted.");
Output
public void start () { Creating Thread-1
} Thread: Thread-1, 4
} Running Thread-2
} Thread: Thread-2, 4
try {
thread1.setDaemon(true); }
thread4.start(); Goodbye
}
Exception Handling in Java
}
The Exception Handling in Java is one of the powerful mechanism to
This will produce the following result. You can try this example again handle the runtime errors so that the normal flow of the application can
and again and you will get a different result every time. be maintained.
Output In this tutorial, we will learn about Java exceptions, it's types, and the
difference between checked and unchecked exceptions.
Starting hello thread...
What is Exception in Java?
Starting goodbye thread...
Dictionary Meaning: Exception is an abnormal condition.
Hello
In Java, an exception is an event that disrupts the normal flow of the
Hello
program. It is an object which is thrown at runtime.
Hello
What is Exception Handling?
Hello
Exception Handling is a mechanism to handle runtime errors such as
Hello ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Hello
Advantage of Exception Handling
Goodbye
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
1) Checked Exception finally The "finally" block is used to execute the necessary code of the pr
exception is handled or not.
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For throw The "throw" keyword is used to throw an exception.
example, IOException, SQLException, etc. Checked exceptions are
throws The "throws" keyword is used to declare exceptions. It specifies th
checked at compile-time.
in the method. It doesn't throw an exception. It is always used wi
2) Unchecked Exception
If we divide any number by zero, there occurs an ArithmeticException. Java try block
1. int a=50/0;//ArithmeticException Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
2) A scenario where NullPointerException occurs
If an exception occurs at the particular statement in the try block, the
If we have a null value in any variable, performing any operation on the rest of the block code will not execute. So, it is recommended not to
variable throws a NullPointerException. keep the code in try block that will not throw an exception.
1. String s=null; Java try block must be followed by either catch or finally block.
2. System.out.println(s.length());//NullPointerException
Syntax of Java try-catch
3) A scenario where NumberFormatException occurs
1. try{
If the formatting of any variable or number is mismatched, it may result 2. //code that may throw an exception
into NumberFormatException. Suppose we have a string variable that 3. }catch(Exception_class_Name ref){}
has characters; converting this variable into digit will cause
NumberFormatException.
The catch block must be used after the try block only. You can use
The JVM firstly checks whether the exception is handled or not. If
multiple catch block with a single try block.
exception is not handled, JVM provides a default exception handler that
performs the following tasks:
Internal Working of Java try-catch block
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception
occurred).
Causes the program to terminate.
As displayed in the above example, the rest of the code is not executed rest of the code
(in such case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is Java Multi-catch block
not handled, all the code below the exception won't be executed.
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
Solution by exception handling perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
Let's see the solution of the above problem by a java try-catch block.
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
Example 1 }
MultipleCatchBlock1.java {
Java Applet
Applet is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and works
at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
As displayed in the above d
o Plugin is required at client browser to execute applet. Applet class extends Panel. Panel class extends Container which is the sub
Component.
Hierarchy of Applet
1. //First.java
java.awt.Component class 2. import java.applet.Applet;
3. import java.awt.Graphics;
The Component class provides 1 life cycle method of applet.
4. public class First extends Applet{
5.
1. public void paint(Graphics g): is used to paint the Applet. It
6. public void paint(Graphics g){
provides Graphics class object that can be used for drawing oval,
7. g.drawString("welcome",150,150);
rectangle, arc etc.
8. }
9.
10. }
Who is responsible to manage the life cycle of an
myapplet.html
applet?
1. <html>
EventHandling in Applet In the above example, we have created all the controls in init() method beca
invoked only once.
As we perform event handling in AWT or Swing, we can perform it in applet
also. Let's see the simple example of event handling in applet that prints a myapplet.html
message by click on the button.
1. <html>
Example of EventHandling in applet: 2.
3.
<body>
<applet code="EventApplet.class" width="300" height="300">
4. </applet>
1. import java.applet.*;
5. </body>
2. import java.awt.*;
6. </html>
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
Collections in Java
5. Button b;
6. TextField tf; Any group of individual objects that are represented as a single unit is
7. known as a Java Collection of Objects. In Java, a separate framework
8. public void init(){ named the “Collection Framework” has been defined in JDK 1.2 which
9. tf=new TextField(); holds all the Java Collection Classes and Interface in it.
10. tf.setBounds(30,40,150,20);
11.
In Java, the Collection interface (java.util.Collection) and Map interface
12. b=new Button("Click");
(java.util.Map) are the two main “root” interfaces of Java collection
13. b.setBounds(80,150,60,50);
classes.
14.
15. add(b);add(tf);
import java.io.*;
// Adding the element into the
import java.util.*;
// hashtable
h.put(1, "geeks");
class CollectionDemo {
h.put(2, "4geeks");
// but hashtable element insertion requires put() JavaBeans & Network Programming
JavaBeans Introduction…
// Accessing the first element of the - JavaBeans are reusable software components for Java
// array, vector and hashtable - Build re-useable applications or program building blocks called
components that can be deployed in a network on any major operating
System.out.println(arr[0]);
system platform.
System.out.println(v.elementAt(0));
- They are used to encapsulate many objects into a single object (the
bean), so that they can be passed around as a single bean object instead
System.out.println(h.get(1));
of as multiple individual objects.
} Advantages
Output A Bean obtains all of the benefits of Java's "write once, run
anywhere" paradigm.
1 The properties, events, and methods of a Bean that are exposed
to another application can be controlled.
1 Auxiliary software can be provided to help configure a Bean.
Application programs create, control, and use sockets through import java.io.*;
system calls like socket(), bind(), listen(), connect(), send(), recv().
public class ip
The term network programming refers to writing programs that execute
across multiple devices (computers), in which the devices are all {
connected to each other using a network.
public static void main ( String[] args ) throws IOException {
The java.net package of the J2SE APIs contains a collection of classes
and interfaces that provide the low-level communication details, String hostname = args[0];
allowing you to write programs that focus on solving the problem at
try
hand.
{
The term network programming refers to writing programs that execute
across multiple devices (computers), in which the devices are all
InetAddress ipaddress = InetAddress.getByName(hostname);
connected to each other using a network. The java.net package of the
J2SE APIs contains a collection of classes and interfaces that provide the System.out.println("IP address: " + ipaddress.getHostAddress());
low-level communication details, allowing you to write programs that
focus on solving the problem at hand. The java.net package provides }
support for the two common network protocols:
catch ( UnknownHostException e )
TCP: TCP stands for Transmission Control Protocol, which allows
for reliable communication between two applications. TCP is {
Output :
javac ip.java
java ip www.google.co.in
IP address : 173.194.38.184
********