SlideShare a Scribd company logo
1 of 30
Download to read offline
Java Programming
Unit-4
Dr. K ADISESHA
Introduction
Exception
Exception Handling
Applets Programming
Designing Web Page
2
Exception Handling
& Applets in Java
Prof. K. Adisesha
Introduction
Prof. K. Adisesha
3
Exception in Java:
An exception (or exceptional event) is a problem that arises during the execution of a
program.
➢ When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
➢ An exception can occur for many different reasons. Following are some scenarios where
an exception occurs.
❖ A user has entered an invalid data.
❖ A file that needs to be opened cannot be found.
❖ A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Introduction
Prof. K. Adisesha
4
Java - Applet:
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
➢ There are some important differences between an applet and a standalone Java application:
❖ An applet is a Java class that extends the java.applet.Applet class.
❖ A main() method is not invoked on an applet, and an applet class will not define main().
❖ Applets are designed to be embedded within an HTML page.
❖ When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
❖ A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or
a separate runtime environment.
❖ The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Exception in Java
Prof. K. Adisesha
5
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
➢ The Exception class and Error is a subclass of the Throwable class.
➢ Errors are abnormal conditions that happen in
case of severe failures, these are not handled
by the Java programs.
➢ The Exception class has two main subclasses:
❖ IOException class
❖ RuntimeException Class.
Exception in Java
Prof. K. Adisesha
6
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:
❖ Checked Exception
❖ Unchecked Exception
❖ Error
Exception in Java
Prof. K. Adisesha
7
Types of Java Exceptions:
There are mainly two types of exceptions: checked and unchecked.
➢ Checked Exception: These exceptions cannot simply be ignored, the programmer should
take care of (handle) these exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
➢ Unchecked Exception: The classes that inherit the Runtime Exception are known as
unchecked exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
➢ Error: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Exception in Java
Prof. K. Adisesha
8
Java Exception Keywords:
Java provides five keywords that are used to handle the exception.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.
Exception in Java
Prof. K. Adisesha
9
Exception Handling in Java:
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
➢ In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
➢ The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
➢ Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Exception Handling in Java
Prof. K. Adisesha
10
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords.
➢ A try/catch block is placed around the code that might generate an exception.
➢ Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following. Syntax:
try {
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
➢ The code which is prone to exceptions is placed in the
try block.
➢ When an exception occurs, that exception occurred is
handled by catch block associated with it.
➢ Every try block should be immediately followed either
by a catch block or finally block.
Exception Handling in Java
Prof. K. Adisesha
11
Java try and catch:
When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).
➢ The try statement allows you to define a block of code to be tested for errors while it is being
executed.
➢ The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
➢ The try and catch keywords come in pairs:.
Syntax: try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example:
class JavaException
{ public static void main(String args[])
{ int d = 0; int n = 20;
try { int fraction = n / d;
System.out.println("This line will not be Executed"); }
catch (ArithmeticException e)
{ System.out.println("In the catch Block due to Exception = " + e);}
System.out.println("End Of Main"); } }
Exception Handling in Java
Prof. K. Adisesha
12
Java Catch Multiple Exceptions:
Java Multi-catch block: A try block can be followed by one or more catch blocks containing a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Syntax: try { // Block of code to try }
catch(ArithmeticException e) {
// Block of code to handle errors }
catch(Exception e) {
// Block of code to handle errors }
➢ At a time only one exception occurs and at a time only one catch block
is executed.
➢ All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Exception Handling in Java
Prof. K. Adisesha
13
The Throws/Throw Keywords:
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
➢ You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Syntax:
import java.io.*;
public class className {
public void withdraw(double amount) throws
RemoteException, InsufficientFundsException
{
// Method implementation
}
// Remainder of class definition
}
➢ throws is used to postpone the handling of a checked exception.
➢ throw is used to invoke an exception explicitly.
➢ A method can declare that it throws more than one exception,
in which case the exceptions are declared in a list separated
by commas. Syntax:
public void deposit(double amount) throws
RemoteException { // Method implementation
throw new RemoteException(); }
Exception Handling in Java
Prof. K. Adisesha
14
The Finally Block:
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception. Syntax:
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
➢ Using a finally block allows you to run any
cleanup-type statements that you want to
execute, no matter what happens in the
protected code.
➢ A finally block appears at the end of the catch
blocks and has the following syntax −.
Exception Handling in Java
Prof. K. Adisesha
15
The Finally Block:
A finally block appears at the end of the catch blocks and has the following Example −
public class ExcepTest
{ public static void main(String args[])
{ int a[] = new int[2];
try { System.out.println("Access element three :" + a[3]); }
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e); }
finally
{ a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed"); }
}
}
Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Java Applet
Prof. K. Adisesha
16
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.
➢ An applet is a Java class that extends the java.applet.Applet class.
➢ A main() method is not invoked on an applet, and an applet class will not define main().
➢ Applets are designed to be embedded within an HTML page.
➢ Advantage of Applet
❖ There are many advantages of applet. They are as follows:
❖ It works at client side so less response time.
❖ Secured
❖ It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac OS etc.
Java Applet
Prof. K. Adisesha
17
Java Applet:
Java Applets are programs stored on a web server, similar to web pages:
➢ When an applet is referred to in a web page that has been fetched and processed by a browser,
the browser generates a request to fetch (or download) the applet program, then executes the
program in the browser’s execution context, on the client host.
<applet code=HelloWorld.class</applet>
...
...
HelloWorld.class
server host
web server
myWebPage.html
browser host
browser
reqeust for
myWebPage.html
myWebPage.html
request for
HelloWorldclass
HelloWorld.class
HelloWorld.class
Java Applet
Prof. K. Adisesha
18
Applet Execution :
An applet program is a written as a subclass of the java.Applet class or the
javax.swing.Japplet class.
➢ There is no main method: you must override the start method. Applet objects uses AWT for
graphics. JApplet uses SWING.
➢ It is a Grapics object that runs in a Thread object, so every applet can perform graphics, and
runs in parallel to the browser process.
➢ When the applet is loaded, these methods are automatically invoked in order:
❖ The init( ) method is invoked by the Java Virtual Machine.
❖ The start( ) method
❖ The paint( ) method
Java Applet
Prof. K. Adisesha
19
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.
➢ Lifecycle of Java Applet
❖ Applet is initialized.
❖ Applet is started.
❖ Applet is painted.
❖ Applet is stopped.
❖ Applet is destroyed.
Java Applet
Prof. K. Adisesha
20
Lifecycle of Java Applet:
➢ init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
➢ start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
➢ stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
➢ destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
➢ paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
Java Applet
Prof. K. Adisesha
21
Applet Life Cycle in Java:
An applet is a Java application executed in any web browser and works on the client-side.
➢ It is created to be placed on an HTML page.
➢ The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
➢ The paint() method belongs to the awt.Component class.
class TestAppletLifeCycle extends Applet {
public void init()
{ // initialized objects }
public void start()
{ // code to start the applet }
public void paint(Graphics graphics)
{ // draw the shapes }
public void stop()
{ // code to stop the applet }
public void destroy()
{ // code to destroy the applet }
}
Java Applet
Prof. K. Adisesha
22
The Applet Class:
Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and services
from the browser context.
➢ These include methods that do the following −
❖ Get applet parameters
❖ Get the network location of the HTML file that contains the applet
❖ Get the network location of the applet class directory
❖ Print a status message in the browser
❖ Fetch an image
❖ Fetch an audio clip
❖ Play an audio clip
❖ Resize the applet
Java Applet
Prof. K. Adisesha
23
HTML tags for applets :
An applet may be invoked by embedding directives in an HTML file
<APPLET // the beginning of the HTML applet code
CODE="demoxx.class" // the actual name of the applet (usually a 'class' file)
CODEBASE="demos/“ // the location of the applet (relative as here, or a full URL)
NAME=“SWE622" // the name of the instance of the applet on this page
WIDTH="100" HEIGHT="50" // the physical width & height of the applet on the page
ALIGN="Top" // align the applet within its page space (top, bottom, center)
<PARAM //specifies a parameter that can be passed to the applet
NAME=“name1" //the name known internally by the applet in order to receive this parameter
VALUE="000000" the value you want to pass for this parameter > end of this parameter
<PARAM specifies a parameter that can be passed to the applet (applet specific)
NAME=“name2" the name known internally by the applet in order to receive this parameter
VALUE="ffffff" the value you want to pass for this parameter > end of this parameter
</APPLET> specifies the end of the HTML applet code
Java Applet
Prof. K. Adisesha
24
Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
➢ The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Java Applet
Prof. K. Adisesha
25
Running an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
➢ There are two ways to run an applet
➢ HTML file: To execute the applet by html file, create an applet and compile it.
❖ After that create an html file and place the applet code in html file.
❖ Now click the html file.
➢ appletViewer tool: To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it.
❖ After that run it by: appletviewer File.java.
Java Applet
Prof. K. Adisesha
26
Running an Applet:
HTML file: To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{ g.drawString("welcome",150,150); }
}
//myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Java Applet
Prof. K. Adisesha
27
Running an Applet:
Applet by applet viewer tool: To execute the applet by appletviewer tool, create an applet that
contains applet tag in comment and compile it. After that run it by: appletviewer First.java.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{ g.drawString("welcome to applet",150,150); }
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command
prompt:
c:>javac First.java
c:>appletviewer First.java
Java Applet
Prof. K. Adisesha
28
The HelloWorld Applet:
<HTML>
<BODY>
<APPLET code=hello.class width=900 height=300>
</APPLET>
</BODY>
</HTML>
// applet to display a message in a window
import java.awt.*;
import java.applet.*;
public class hello extends Applet{
public void init( ){
setBackground(Color.yellow);
}
public void paint(Graphics g){
final int FONT_SIZE = 42;
Font font = new Font("Serif", Font.BOLD, FONT_SIZE);
// set font, and color and display message on
// the screen at position 250,150
g.setFont(font);
g.setColor(Color.blue);
// The message in the next line is the one you will see
g.drawString("Hello, world!",250,150);
}
}
Server host Client host
HTTP server browser
applet
Host X
applet download
connection request
connection request
forbidden
allowed
server Y
server Z
Java Applet
Prof. K. Adisesha
29
Advanced Applets:
You can use threads in an applet.
➢ You can make socket calls in an applet, subject to the security constraints.
➢ A proxy server can be used to circumvent the security constraints.
Server host Client host
HTTP server browser
applet
Host X
applet download
connection request
server Y
server Z
connection request
Discussion
Prof. K. Adisesha (Ph. D)
30
Queries ?
Prof. K. Adisesha
9449081542

More Related Content

Similar to JAVA PPT -4 BY ADI.pdf

Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
exceptions in java
exceptions in javaexceptions in java
exceptions in javajaveed_mhd
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaManav Prasad
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming languageushakiranv110
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statementmyrajendra
 

Similar to JAVA PPT -4 BY ADI.pdf (20)

Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 

More from Prof. Dr. K. Adisesha

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfProf. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaProf. Dr. K. Adisesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfProf. Dr. K. Adisesha
 

More from Prof. Dr. K. Adisesha (20)

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
 

Recently uploaded

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 

JAVA PPT -4 BY ADI.pdf

  • 2. Introduction Exception Exception Handling Applets Programming Designing Web Page 2 Exception Handling & Applets in Java Prof. K. Adisesha
  • 3. Introduction Prof. K. Adisesha 3 Exception in Java: An exception (or exceptional event) is a problem that arises during the execution of a program. ➢ When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. ➢ An exception can occur for many different reasons. Following are some scenarios where an exception occurs. ❖ A user has entered an invalid data. ❖ A file that needs to be opened cannot be found. ❖ A network connection has been lost in the middle of communications or the JVM has run out of memory.
  • 4. Introduction Prof. K. Adisesha 4 Java - Applet: An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal. ➢ There are some important differences between an applet and a standalone Java application: ❖ An applet is a Java class that extends the java.applet.Applet class. ❖ A main() method is not invoked on an applet, and an applet class will not define main(). ❖ Applets are designed to be embedded within an HTML page. ❖ When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine. ❖ A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment. ❖ The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.
  • 5. Exception in Java Prof. K. Adisesha 5 Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. ➢ The Exception class and Error is a subclass of the Throwable class. ➢ Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. ➢ The Exception class has two main subclasses: ❖ IOException class ❖ RuntimeException Class.
  • 6. Exception in Java Prof. K. Adisesha 6 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: ❖ Checked Exception ❖ Unchecked Exception ❖ Error
  • 7. Exception in Java Prof. K. Adisesha 7 Types of Java Exceptions: There are mainly two types of exceptions: checked and unchecked. ➢ Checked Exception: These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time. ➢ Unchecked Exception: The classes that inherit the Runtime Exception are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile- time, but they are checked at runtime. ➢ Error: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 8. Exception in Java Prof. K. Adisesha 8 Java Exception Keywords: Java provides five keywords that are used to handle the exception. Keyword Description try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
  • 9. Exception in Java Prof. K. Adisesha 9 Exception Handling in Java: The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. ➢ In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. ➢ The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application ➢ Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
  • 10. Exception Handling in Java Prof. K. Adisesha 10 Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. ➢ A try/catch block is placed around the code that might generate an exception. ➢ Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following. Syntax: try { // Protected code } catch (ExceptionName e1) { // Catch block } ➢ The code which is prone to exceptions is placed in the try block. ➢ When an exception occurs, that exception occurred is handled by catch block associated with it. ➢ Every try block should be immediately followed either by a catch block or finally block.
  • 11. Exception Handling in Java Prof. K. Adisesha 11 Java try and catch: When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error). ➢ The try statement allows you to define a block of code to be tested for errors while it is being executed. ➢ The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. ➢ The try and catch keywords come in pairs:. Syntax: try { // Block of code to try } catch(Exception e) { // Block of code to handle errors } Example: class JavaException { public static void main(String args[]) { int d = 0; int n = 20; try { int fraction = n / d; System.out.println("This line will not be Executed"); } catch (ArithmeticException e) { System.out.println("In the catch Block due to Exception = " + e);} System.out.println("End Of Main"); } }
  • 12. Exception Handling in Java Prof. K. Adisesha 12 Java Catch Multiple Exceptions: Java Multi-catch block: A try block can be followed by one or more catch blocks containing a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Syntax: try { // Block of code to try } catch(ArithmeticException e) { // Block of code to handle errors } catch(Exception e) { // Block of code to handle errors } ➢ At a time only one exception occurs and at a time only one catch block is executed. ➢ All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 13. Exception Handling in Java Prof. K. Adisesha 13 The Throws/Throw Keywords: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. ➢ You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Syntax: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } // Remainder of class definition } ➢ throws is used to postpone the handling of a checked exception. ➢ throw is used to invoke an exception explicitly. ➢ A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. Syntax: public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); }
  • 14. Exception Handling in Java Prof. K. Adisesha 14 The Finally Block: The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Syntax: try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } ➢ Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. ➢ A finally block appears at the end of the catch blocks and has the following syntax −.
  • 15. Exception Handling in Java Prof. K. Adisesha 15 The Finally Block: A finally block appears at the end of the catch blocks and has the following Example − public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } Output: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
  • 16. Java Applet Prof. K. Adisesha 16 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. ➢ An applet is a Java class that extends the java.applet.Applet class. ➢ A main() method is not invoked on an applet, and an applet class will not define main(). ➢ Applets are designed to be embedded within an HTML page. ➢ Advantage of Applet ❖ There are many advantages of applet. They are as follows: ❖ It works at client side so less response time. ❖ Secured ❖ It can be executed by browsers running under many plateforms, including Linux, Windows, Mac OS etc.
  • 17. Java Applet Prof. K. Adisesha 17 Java Applet: Java Applets are programs stored on a web server, similar to web pages: ➢ When an applet is referred to in a web page that has been fetched and processed by a browser, the browser generates a request to fetch (or download) the applet program, then executes the program in the browser’s execution context, on the client host. <applet code=HelloWorld.class</applet> ... ... HelloWorld.class server host web server myWebPage.html browser host browser reqeust for myWebPage.html myWebPage.html request for HelloWorldclass HelloWorld.class HelloWorld.class
  • 18. Java Applet Prof. K. Adisesha 18 Applet Execution : An applet program is a written as a subclass of the java.Applet class or the javax.swing.Japplet class. ➢ There is no main method: you must override the start method. Applet objects uses AWT for graphics. JApplet uses SWING. ➢ It is a Grapics object that runs in a Thread object, so every applet can perform graphics, and runs in parallel to the browser process. ➢ When the applet is loaded, these methods are automatically invoked in order: ❖ The init( ) method is invoked by the Java Virtual Machine. ❖ The start( ) method ❖ The paint( ) method
  • 19. Java Applet Prof. K. Adisesha 19 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. ➢ Lifecycle of Java Applet ❖ Applet is initialized. ❖ Applet is started. ❖ Applet is painted. ❖ Applet is stopped. ❖ Applet is destroyed.
  • 20. Java Applet Prof. K. Adisesha 20 Lifecycle of Java Applet: ➢ init − This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed. ➢ start − This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. ➢ stop − This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. ➢ destroy − This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet. ➢ paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
  • 21. Java Applet Prof. K. Adisesha 21 Applet Life Cycle in Java: An applet is a Java application executed in any web browser and works on the client-side. ➢ It is created to be placed on an HTML page. ➢ The init(), start(), stop() and destroy() methods belongs to the applet.Applet class. ➢ The paint() method belongs to the awt.Component class. class TestAppletLifeCycle extends Applet { public void init() { // initialized objects } public void start() { // code to start the applet } public void paint(Graphics graphics) { // draw the shapes } public void stop() { // code to stop the applet } public void destroy() { // code to destroy the applet } }
  • 22. Java Applet Prof. K. Adisesha 22 The Applet Class: Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context. ➢ These include methods that do the following − ❖ Get applet parameters ❖ Get the network location of the HTML file that contains the applet ❖ Get the network location of the applet class directory ❖ Print a status message in the browser ❖ Fetch an image ❖ Fetch an audio clip ❖ Play an audio clip ❖ Resize the applet
  • 23. Java Applet Prof. K. Adisesha 23 HTML tags for applets : An applet may be invoked by embedding directives in an HTML file <APPLET // the beginning of the HTML applet code CODE="demoxx.class" // the actual name of the applet (usually a 'class' file) CODEBASE="demos/“ // the location of the applet (relative as here, or a full URL) NAME=“SWE622" // the name of the instance of the applet on this page WIDTH="100" HEIGHT="50" // the physical width & height of the applet on the page ALIGN="Top" // align the applet within its page space (top, bottom, center) <PARAM //specifies a parameter that can be passed to the applet NAME=“name1" //the name known internally by the applet in order to receive this parameter VALUE="000000" the value you want to pass for this parameter > end of this parameter <PARAM specifies a parameter that can be passed to the applet (applet specific) NAME=“name2" the name known internally by the applet in order to receive this parameter VALUE="ffffff" the value you want to pass for this parameter > end of this parameter </APPLET> specifies the end of the HTML applet code
  • 24. Java Applet Prof. K. Adisesha 24 Invoking an Applet: An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. ➢ The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the "Hello, World" applet − <html> <title>The Hello, World Applet</title> <hr> <applet code = "HelloApplet.class" width = "320" height = "120"> If your browser was Java-enabled, a "Hello, World" message would appear here. </applet> <hr> </html>
  • 25. Java Applet Prof. K. Adisesha 25 Running an Applet: An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. ➢ There are two ways to run an applet ➢ HTML file: To execute the applet by html file, create an applet and compile it. ❖ After that create an html file and place the applet code in html file. ❖ Now click the html file. ➢ appletViewer tool: To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. ❖ After that run it by: appletviewer File.java.
  • 26. Java Applet Prof. K. Adisesha 26 Running an Applet: HTML file: To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file. //First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet { public void paint(Graphics g) { g.drawString("welcome",150,150); } } //myapplet.html <html> <body> <applet code="First.class" width="300" height="300"> </applet> </body> </html>
  • 27. Java Applet Prof. K. Adisesha 27 Running an Applet: Applet by applet viewer tool: To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. //First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet { public void paint(Graphics g) { g.drawString("welcome to applet",150,150); } } /* <applet code="First.class" width="300" height="300"> </applet> */ To execute the applet by appletviewer tool, write in command prompt: c:>javac First.java c:>appletviewer First.java
  • 28. Java Applet Prof. K. Adisesha 28 The HelloWorld Applet: <HTML> <BODY> <APPLET code=hello.class width=900 height=300> </APPLET> </BODY> </HTML> // applet to display a message in a window import java.awt.*; import java.applet.*; public class hello extends Applet{ public void init( ){ setBackground(Color.yellow); } public void paint(Graphics g){ final int FONT_SIZE = 42; Font font = new Font("Serif", Font.BOLD, FONT_SIZE); // set font, and color and display message on // the screen at position 250,150 g.setFont(font); g.setColor(Color.blue); // The message in the next line is the one you will see g.drawString("Hello, world!",250,150); } }
  • 29. Server host Client host HTTP server browser applet Host X applet download connection request connection request forbidden allowed server Y server Z Java Applet Prof. K. Adisesha 29 Advanced Applets: You can use threads in an applet. ➢ You can make socket calls in an applet, subject to the security constraints. ➢ A proxy server can be used to circumvent the security constraints. Server host Client host HTTP server browser applet Host X applet download connection request server Y server Z connection request
  • 30. Discussion Prof. K. Adisesha (Ph. D) 30 Queries ? Prof. K. Adisesha 9449081542