0% found this document useful (0 votes)
79 views27 pages

UNIT 4 IO Programming

Uploaded by

bhaskargouda807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views27 pages

UNIT 4 IO Programming

Uploaded by

bhaskargouda807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 4 A thread goes through various stages in its life cycle.

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.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 1


Thread Priorities Step 2

As a second step, you will instantiate a Thread object using the


Every Java thread has a priority that helps the operating system
following constructor −
determine the order in which threads are scheduled.
Thread(Runnable threadObj, String threadName);
Java thread priorities are in the range between MIN_PRIORITY (a
constant of 1) and MAX_PRIORITY (a constant of 10). By default, every
Where, threadObj is an instance of a class that implements
thread is given priority NORM_PRIORITY (a constant of 5).
the Runnable interface and threadName is the name given to the new
thread.
Threads with higher priority are more important to a program and
should be allocated processor time before lower-priority threads.
However, thread priorities cannot guarantee the order in which threads Step 3
execute and are very much platform dependent.
Once a Thread object is created, you can start it by
calling start() method, which executes a call to run( ) method. Following
Create a Thread by Implementing a is a simple syntax of start() method −
Runnable Interface void start();

If your class is intended to be executed as a thread then you can achieve


Example
this by implementing a Runnable interface. You will need to follow
three basic steps −
Here is an example that creates a new thread and starts running it −

Step 1 1. class RunnableDemo implements Runnable {


2. private Thread t;
As a first step, you need to implement a run() method provided by 3. private String threadName;
a Runnable interface. This method provides an entry point for the
thread and you will put your complete business logic inside this method.
Following is a simple syntax of the run() method −
4. RunnableDemo( String name) {
public void run( ) 5. threadName = name;
6. System.out.println("Creating " + threadName );
7. }

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 2


8. public void run() { Output
9. System.out.println("Running " + threadName );
10. try { Creating Thread-1
11. for(int i = 4; i > 0; i--) {
a. System.out.println("Thread: " + threadName + ", " + i); Starting Thread-1
b. // Let the thread sleep for a while.
c. Thread.sleep(50); Creating Thread-2
12. }
13. } catch (InterruptedException e) { Starting Thread-2
14. System.out.println("Thread " + threadName + " interrupted.");
15. } Running Thread-1
16. System.out.println("Thread " + threadName + " exiting.");
17. } Thread: Thread-1, 4
18. public void start () {
19. System.out.println("Starting " + threadName ); Running Thread-2
20. if (t == null) {
Thread: Thread-2, 4
21. t = new Thread (this, threadName);
22. t.start ();
Thread: Thread-1, 3
23. }
24. }
Thread: Thread-2, 3
25. }
26. public class TestThread { Thread: Thread-1, 2
27. public static void main(String args[]) {
28. RunnableDemo R1 = new RunnableDemo( "Thread-1"); Thread: Thread-2, 2
29. R1.start();
Thread: Thread-1, 1

Thread: Thread-2, 1
30. RunnableDemo R2 = new RunnableDemo( "Thread-2");
31. R2.start(); Thread Thread-1 exiting.
32. }
33. } Thread Thread-2 exiting.

This will produce the following result −

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 3


private String threadName;
Create a Thread by Extending a Thread
Class
ThreadDemo( String name) {
The second way to create a thread is to create a new class that
extends Thread class using the following two simple steps. This threadName = name;
approach provides more flexibility in handling multiple threads created
using available methods in Thread class. System.out.println("Creating " + threadName );

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--) {

Step 2 System.out.println("Thread: " + threadName + ", " + 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( ); }

Example } catch (InterruptedException e) {

Here is the preceding program rewritten to extend the Thread − System.out.println("Thread " + threadName + " interrupted.");

class ThreadDemo extends Thread { }

private Thread t; System.out.println("Thread " + threadName + " exiting.");

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 4


} This will produce the following result −

Output
public void start () { Creating Thread-1

System.out.println("Starting " + threadName ); Starting Thread-1

if (t == null) { Creating Thread-2

t = new Thread (this, threadName); Starting Thread-2

t.start (); Running Thread-1

} Thread: Thread-1, 4

} Running Thread-2

} Thread: Thread-2, 4

public class TestThread { Thread: Thread-1, 3

public static void main(String args[]) { Thread: Thread-2, 3

ThreadDemo T1 = new ThreadDemo( "Thread-1"); Thread: Thread-1, 2

T1.start(); Thread: Thread-2, 2

ThreadDemo T2 = new ThreadDemo( "Thread-2"); Thread: Thread-1, 1

T2.start(); Thread: Thread-2, 1

} Thread Thread-1 exiting.

} Thread Thread-2 exiting.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 5


Thread Methods The current thread invokes this method on a second thread,
causing the current thread to block until the second thread
Following is the list of important methods available in the Thread class. terminates or the specified number of milliseconds passes.

7 public void interrupt()


Sr.No. Method & Description
Interrupts this thread, causing it to continue execution if it
1 public void start()
was blocked for any reason.
Starts the thread in a separate path of execution, then
8 public final boolean isAlive()
invokes the run() method on this Thread object.
Returns true if the thread is alive, which is any time after the
2 public void run()
thread has been started but before it runs to completion.
If this Thread object was instantiated using a separate
Runnable target, the run() method is invoked on that The previous methods are invoked on a particular Thread object. The
Runnable object. following methods in the Thread class are static. Invoking one of the
static methods performs the operation on the currently running thread.
3 public final void setName(String name)
Sr.No. Method & Description
Changes the name of the Thread object. There is also a
getName() method for retrieving the name. 1 public static void yield()
4 public final void setPriority(int priority)
Causes the currently running thread to yield to any other
threads of the same priority that are waiting to be scheduled.
Sets the priority of this Thread object. The possible values
are between 1 and 10. 2 public static void sleep(long millisec)
5 public final void setDaemon(boolean on)
Causes the currently running thread to block for at least the
specified number of milliseconds.
A parameter of true denotes this Thread as a daemon thread.
3 public static boolean holdsLock(Object x)
6 public final void join(long millisec)

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 6


}
Returns true if the current thread holds the lock on the given
Object. public void run() {
4 public static Thread currentThread()
while(true) {

Returns a reference to the currently running thread, which is System.out.println(message);


the thread that invokes this method.
}
5 public static void dumpStack()
}
Prints the stack trace for the currently running thread, which
is useful when debugging a multithreaded application. }

Following is another class which extends the Thread class −


Example
// File Name : GuessANumber.java
The following ThreadClassDemo program demonstrates some of these
methods of the Thread class. Consider a class DisplayMessage which // Create a thread to extentd Thread
implements Runnable −
public class GuessANumber extends Thread {
// File Name : DisplayMessage.java
private int number;
// Create a thread to implement Runnable
public GuessANumber(int number) {
public class DisplayMessage implements Runnable {
this.number = number;
private String message;
}

public void run() {


public DisplayMessage(String message) {
int counter = 0;
this.message = message;
int guess = 0;

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 7


do { System.out.println("Starting hello thread...");

guess = (int) (Math.random() * 100 + 1); thread1.start();

System.out.println(this.getName() + " guesses " + guess); Runnable bye = new DisplayMessage("Goodbye");

counter++; Thread thread2 = new Thread(bye);

} while(guess != number); thread2.setPriority(Thread.MIN_PRIORITY);

System.out.println("** Correct!" + this.getName() + "in" + counter + thread2.setDaemon(true);


"guesses.**");
System.out.println("Starting goodbye thread...");
}
thread2.start();
}

Following is the main program, which makes use of the above-


defined classes − System.out.println("Starting thread3...");

// File Name : ThreadClassDemo.java Thread thread3 = new GuessANumber(27);

public class ThreadClassDemo { thread3.start();

try {

public static void main(String [] args) { thread3.join();

Runnable hello = new DisplayMessage("Hello"); } catch (InterruptedException e) {

Thread thread1 = new Thread(hello); System.out.println("Thread interrupted.");

thread1.setDaemon(true); }

thread1.setName("hello"); System.out.println("Starting thread4...");

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 8


Thread thread4 = new GuessANumber(75); Goodbye

thread4.start(); Goodbye

System.out.println("main() is ending..."); 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

Goodbye The core advantage of exception handling is to maintain the normal


flow of the application. An exception normally disrupts the normal

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 9


flow of the application; that is why we need to handle exceptions. Let's
consider a scenario:

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;

Suppose there are 10 statements in a Java program and an exception


occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception
hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An
error is considered as the unchecked exception. However, according to
Oracle, there are three types of exceptions namely:

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 10


1. Checked Exception
2. Unchecked Exception Keyword Description
3. Error
try The "try" keyword is used to specify a block where we should p
we can't use try block alone. The try block must be followed by e
Difference between Checked and Unchecked
Exceptions catch The "catch" block is used to handle the exception. It must be pre
we can't use catch block alone. It can be followed by finally block

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

The classes that inherit the RuntimeException are known as unchecked


Java Exception Handling Example
exceptions. For example, ArithmeticException, NullPointerException,
Let's see an example of Java Exception Handling in which we are using
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
a try-catch statement to handle the exception.
checked at compile-time, but they are checked at runtime.
JavaExceptionExample.java
3) Error
1. public class JavaExceptionExample{
Error is irrecoverable. Some example of errors are OutOfMemoryError, 2. public static void main(String args[]){
VirtualMachineError, AssertionError etc. 3. try{
4. //code that may raise exception
Java Exception Keywords 5.
6.
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
Java provides five keywords that are used to handle the exception. The 8. System.out.println("rest of the code...");
following table describes each. 9. }
10. }

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 11


Output: 1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Exception in thread main java.lang.ArithmeticException:/ by zero
4) A scenario where ArrayIndexOutOfBoundsException occurs
rest of the code...
When an array exceeds to it's size, the
In the above example, 100/0 raises an ArithmeticException which is ArrayIndexOutOfBoundsException occurs. there may be other reasons
handled by a try-catch block. to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
Common Scenarios of Java Exceptions
1. int a[]=new int[5];
There are given some scenarios where unchecked exceptions may occur. 2. a[10]=50; //ArrayIndexOutOfBoundsException
They are as follows:
Java try-catch block
1) A scenario where ArithmeticException occurs

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.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 12


Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type
of exception within the parameter. The declared exception must be the
parent class exception ( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of
exception.

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.

But if the application programmer handles the exception, the normal


flow of the application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 13


Example 1 1. public class TryCatchExample2 {
2.
3. public static void main(String[] args) {
TryCatchExample1.java
4. try
5. {
1. public class TryCatchExample1 {
6. int data=50/0; //may throw exception
2.
7. }
3. public static void main(String[] args) {
8. //handling the exception
4.
9. catch(ArithmeticException e)
5. int data=50/0; //may throw exception
10. {
6.
11. System.out.println(e);
7. System.out.println("rest of the code");
12. }
8.
13. System.out.println("rest of the code");
9. }
14. }
10.
15.
11. }
16. }
Output:
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero

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.

Example 2 Points to remember


o At a time only one exception occurs and at a time only one catch block
TryCatchExample2.java
is executed.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 14


o All catch blocks must be ordered from most specific to most general, try{
i.e. catch for ArithmeticException must come before catch for Exception.
int a[]=new int[5];
Flowchart of Multi-catch Block
a[5]=30/0;

catch(ArithmeticException e)

System.out.println("Arithmetic Exception occurs");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("ArrayIndexOutOfBounds Exception occurs");

Example 1 }

Let's see a simple example of java multi-catch block. catch(Exception e)

MultipleCatchBlock1.java {

public class MultipleCatchBlock1 { System.out.println("Parent Exception occurs");

public static void main(String[] args) { System.out.println("rest of the code");

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 15


}

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:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.

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

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 16


Lifecycle methods for Applet: Java Plug-in software.

The java.applet.Applet class 4 life cycle methods and


java.awt.Component class provides 1 life cycle methods for an applet.
How to run an Applet?
java.applet.Applet class
There are two ways to run an applet
For creating any applet java.applet.Applet class must be inherited. It
1. By html file.
provides 4 life cycle methods of applet.
2. By appletViewer tool (for testing purpose).
1. public void init(): is used to initialized the Applet. It is invoked
only once.
2. public void start(): is invoked after the init() method or browser
is maximized. It is used to start the Applet. Simple example of Applet by html file:
3. public void stop(): is used to stop the Applet. It is invoked when
To execute the applet by html file, create an applet and compile it. After
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked that create an html file and place the applet code in html file. Now click
only once. the html file.

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>

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 17


2. <body> c:\>appletviewer First.java
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html> Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics
programming.
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that
Commonly used methods of Graphics class:
contains applet tag in comment and compile it. After that run it by:
1. public abstract void drawString(String str, int x, int y): is used to
appletviewer First.java. Now Html file is not required but it is for testing
draw the specified string.
purpose only. 2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
1. //First.java 3. public abstract void fillRect(int x, int y, int width, int height): is
2. import java.applet.Applet; used to fill rectangle with the default color and specified width and height.
3. import java.awt.Graphics; 4. public abstract void drawOval(int x, int y, int width, int height): is
4. public class First extends Applet{ used to draw oval with the specified width and height.
5. 5. public abstract void fillOval(int x, int y, int width, int height): is
6. public void paint(Graphics g){ used to fill oval with the default color and specified width and height.
7. g.drawString("welcome to applet",150,150); 6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used
8. } to draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
9.
ImageObserver observer): is used draw the specified image.
10. }
8. public abstract void drawArc(int x, int y, int width, int height, int
11. /* startAngle, int arcAngle): is used draw a circular or elliptical arc.
12. <applet code="First.class" width="300" height="300"> 9. public abstract void fillArc(int x, int y, int width, int height, int
13. </applet> startAngle, int arcAngle): is used to fill a circular or elliptical arc.
14. */ 10. public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
To execute the applet by appletviewer tool, write in command prompt: 11. public abstract void setFont(Font font): is used to set the graphics
current font to the specified font.
c:\>javac First.java

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 18


Example of Graphics in applet: Displaying Image in Applet
1. import java.applet.Applet; Applet is mostly used in games and animation. For this purpose image
2. import java.awt.*; is required to be displayed. The java.awt.Graphics class provide a
3.
method drawImage() to display the image.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){ Syntax of drawImage() method:
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50); 1. public abstract boolean drawImage(Image img, int x, int y,
9. g.drawLine(20,30,20,300); ImageObserver observer): is used draw the specified image.
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13. How to get the object of Image:
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30); The java.applet.Applet class provides getImage() method that returns the
16. g.drawArc(90,150,30,30,30,270); object of Image. Syntax:
17. g.fillArc(270,150,30,30,0,180);
18. 1. public Image getImage(URL u, String image){}
19. }
20. }
Other required methods of Applet class to
myapplet.html display image:
1. <html> 1. public URL getDocumentBase(): is used to return the URL of the
2. <body> document in which applet is embedded.
3. <applet code="GraphicsDemo.class" width="300" height="300"> 2. public URL getCodeBase(): is used to return the base URL.
4. </applet>
5. </body>
6. </html>
Example of displaying image in applet:
1. import java.awt.*;
2. import java.applet.*;

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 19


3.
4. Animation in Applet
5. public class DisplayImage extends Applet {
6. Applet is mostly used in games and animation. For this purpose image is
7. Image picture; required to be moved.
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
Example of animation in applet:
11. }
12. 1. import java.awt.*;
13. public void paint(Graphics g) { 2. import java.applet.*;
14. g.drawImage(picture, 30,30, this); 3. public class AnimationExample extends Applet {
15. } 4.
16. 5. Image picture;
17. } 6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
In the above example, drawImage() method of Graphics class is used to
9. }
display the image. The 4th argument of drawImage() method of is
10.
ImageObserver object. The Component class implements ImageObserver
11. public void paint(Graphics g) {
interface. So current class object would also be treated as ImageObserver
12. for(int i=0;i<500;i++){
because Applet class indirectly extends the Component class.
13. g.drawImage(picture, i,30, this);
14.
myapplet.html 15. try{Thread.sleep(100);}catch(Exception e){}
16. }
1. <html> 17. }
2. <body> 18. }
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet> In the above example, drawImage() method of Graphics class is used to
5. </body> display the image. The 4th argument of drawImage() method of is
6. </html> ImageObserver object. The Component class implements ImageObserver
interface. So current class object would also be treated as ImageObserver
because Applet class indirectly extends the Component class.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 20


myapplet.html 16. b.addActionListener(this);
17.
18. setLayout(null);
1. <html>
19. }
2. <body>
20.
3. <applet code="DisplayImage.class" width="300" height="300">
21. public void actionPerformed(ActionEvent e){
4. </applet>
22. tf.setText("Welcome");
5. </body>
23. }
6. </html>
24. }

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);

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 21


What You Should Learn in Java Collections? o TreeSet
o ConcurrentSkipListSet Class
 List Interface  Map Interface
o Abstract List Class o SortedMap Interface
o Abstract Sequential List Class o NavigableMap Interface
o Array List o ConcurrentMap Interface
o Vector Class o TreeMap Class
o Stack Class o AbstractMap Class
o LinkedList Class o ConcurrentHashMap Class
 Queue Interface o EnumMap Class
o Blocking Queue Interface o HashMap Class
o AbstractQueue Class o IdentityHashMap Class
o PriorityQueue Class o LinkedHashMap Class
o PriorityBlockingQueue Class o HashTable Class
o ConcurrentLinkedQueue Class o Properties Class
o ArrayBlockingQueue Class  Other Important Concepts
o DelayQueue Class o How to convert HashMap to ArrayList
o LinkedBlockingQueue Class o Randomly select items from a List
o LinkedTransferQueue o How to add all items from a collection to an ArrayList
 Deque Interface o Conversion of Java Maps to List
o BlockingDeque Interface o Array to ArrayList Conversion
o ConcurrentLinkedDeque Class o ArrayList to Array Conversion
o ArrayDeque Class o Differences between Array and ArrayList
 Set Interface
o Abstract Set Class Framework in Java
o CopyOnWriteArraySet Class
o EnumSet Class A framework is a set of classes and interfaces which provide a ready-
o ConcurrentHashMap Class made architecture. In order to implement a new feature or a class, there
o HashSet Class is no need to define a framework. However, an optimal object-oriented
o LinkedHashSet Class design always includes a framework with a collection of classes such
that all the classes perform the same kind of task. To get more about
 SortedSet Interface
o NavigableSet Interface

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 22


the framework in Java you can explore Java free programming course, // vector and hashtable
this course
int arr[] = new int[] { 1, 2, 3, 4 };
Need for a Separate Collection Framework in Java
Vector<Integer> v = new Vector();
Before the Collection Framework(or before JDK 1.2) was introduced, the
standard methods for grouping Java objects (or collections) Hashtable<Integer, String> h = new Hashtable();
were Arrays or Vectors, or Hashtables. All of these collections had no
common interface. Therefore, though the main aim of all the collections
is the same, the implementation of all these collections was defined
independently and had no correlation among them. And also, it is very // Adding the elements into the
difficult for the users to remember all the different methods, syntax,
// vector
and constructors present in every collection class.
v.addElement(1);
// Java program to demonstrate
v.addElement(2);
// why collection framework was needed

import java.io.*;
// Adding the element into the
import java.util.*;
// hashtable

h.put(1, "geeks");
class CollectionDemo {
h.put(2, "4geeks");

public static void main(String[] args)


// Array instance creation requires [],
{
// while Vector and hastable require ()
// Creating instances of the array,

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 23


// Vector element insertion requires addElement(), geeks

// 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.

- A JavaBeans is a Java Object that is serializable, has a 0-argument


// Array elements are accessed using [], constructor, and allows access to properties using getter and setter
methods.
// vector elements using elementAt()
- Like Java applets, JavaBeans components (or "Beans") can be used to
// and hashtable elements using get() give World Wide Web pages (or other applications) interactive
capabilities such as computing interest rates or varying page content
} based on user or browser characteristics.

} 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.

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 24


 The configuration settings of a Bean can be saved in a persistent Methods in this interface determine if a
DesignMode
storage and can be restored at a later time. bean is executing in design mode.
 A Bean may register to receive events from other objects and can A method in this interface is invoked when
ExceptionListener
generate events that are sent to it. an exception has occurred.
A method in this interface is invoked when
Disadvantages PropertyChangeListener
a bound property is changed.
Objects that implement this interface allow
 A class with a constructor is subject to being instantiated in an PropertyEditor the designer to change and display
invalid state. If such a class is instantiated manually by a property values.
developer (rather than automatically by some kind of
Methods in this interface allow a bean to
framework), the developer might not realize that the class has
Visibility execute in environments where GUI is not
been improperly instantiated.
available.
 The compiler can’t detect such a problem, and even if it’s
documented, there’s no guarantee that the developer will see the
documentation.
 Having to create a getter for every property and a setter for Network Programming Introduction… - - - -
many, most, or all of them, creates an immense amount of
boilerplate code. Network programming involves writing computer programs that enable
processes to communicate with each other across a computer network.
JavaBeans API –
Network programming is client–server programming
The JavaBeans functionality is provided by a set of classes and interfaces
in the java.beans package.  The process initiating the communication is a client, and the
process waiting for the communication to be initiated is a server.
Interface Description The client and server processes together form a distributed
Methods in this interface are used to system. In a peer-to-peer communication, the program can act
AppletInitializer
initialize Beans that are also applets. both as a client and a server.
This interface allows the designer to specify
BeanInfos information about the events, methods Network programming is socket programming
and properties of a Bean.
This interface allows the designer to  The endpoint in an interprocess communication is called a
Customizer provide a graphical user interface through socket, or a network socket
which a bean may be configured

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 25


 Since most communication between computers is based on the typically used over the Internet Protocol, which is referred to as
Internet Protocol, an almost equivalent term is Internet socket. TCP/IP.
 The data transmission between two sockets is organised by  UDP: UDP stands for User Datagram Protocol, a connection-less
communications protocols, usually implemented in the protocol that allows for packets of data to be transmitted
operating system of the participating computers. Application between applications.
programs write to and read from these sockets. Therefore,
network programming is essentially socket programming. Example - Find IP address

Standard API import java.net.*;

 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 {

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 26


System.out.println("Could not find IP address for: " + hostname);

Output :

javac ip.java

java ip www.google.co.in

IP address : 173.194.38.184

********

UNIT 4 I/O Programming in Java By. KAMALAKAR HEGDE Page No | 27

You might also like