Download java-introduction

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Definition Of JAVA
Java is a programming language and computing platform first
released by Sun Microsystems in 1995. There are lots of
applications and websites that will not work unless you have
Java installed, and more are created every day. Java is fast,
secure, and reliable. From laptops to datacenters, game
consoles to scientific supercomputers, cell phones to the
Internet, Java is everywhere!.
Concept of OOP
Object Oriented Programming
Advantage of OOPs over Procedure-oriented programming
language Difference between Objcet-oriented and Objcet-based
programming language. In this page, we will learn about basics
of OOPs. Object Oriented Programming is a paradigm that
provides many concepts such as inheritance, data binding,
polymorphism
etc.
Simula is considered as the first object-oriented programming
language. The programming paradigm where everything is
represented as an object, is known as truly object-oriented
programming
language.
Smalltalk is considered as the first truly object-oriented
programming language.
OOPs (Object Oriented Programming System)
java oops conceptsObject means a real word entity such as pen, chair,
table etc. Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:






Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and
logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g.
shape or rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog
barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different
medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private
here.
Advantage of OOPs over Procedure-oriented programming
language
1)OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented
programming language a global data can be accessed from
anywhere.
3)OOPs provides ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if we
are using the Object-Oriented Programming language.
Class And Object
Class
In java everything is encapsulated under classes. Class is the core of Java
language. Class can be defined as a template/ blueprint that describe the
behaviors /states of a particular entity. A class defines new data type. Once
defined this new type can be used to create object of that type. Object is an
instance of class. You may also call it as physical existence of a logical
template class. A class is declared using class keyword. A class contain
both data and code that operate on that data. The data or variables defined
within a class are called instance variables and the code that operates on
this data is known as methods.
Rules for Java Class








A class can have only public or default(no modifier) access specifier.
It can be either abstract, final or concrete (normal class).
It must have the class keyword, and class must be followed by a legal
identifier.
It may optionally extend one parent class. By default, it will extend
java.lang.Object.
It may optionally implement any number of comma-separated
interfaces.
The class's variables and methods are declared within a set of curly
braces {}.
Each .java source file may contain only one public class. A source file
may contain any number of default visible classes.
Finally, the source file name must match the public class name and it
must have a .java suffix.
A simple class example
Suppose, Student is a class and student's name, roll number, age will be
its property.
Lets see this in Java syntax
When a reference is made to a particular student with its property then it
becomes an object, physical existence of Student class.
After the above statement std is instance/object of Student class. Here the
new keyword creates an actual physical copy of the object and assign it to
the std variable. It will have physical existence and get memory in heap
area. The new operator dynamically allocates memory for an object.
creation of object in java
Q.
How
a
class
is
initialized
in
java?
A Class is initialized in Java when an instance of class is created
using either new operator or using reflection using class.forName(). A
class is also said to be initialized when a static method of Class is
invoked or a static field of Class is assigned.
Q. How would you make a copy of an entire Java object with its
state?
Make that class implement Cloneable interface and call clone()
method on its object. clone() method is defined in Object class which
is parent of all java class by default.
Concept of JVM
What is JVM?
Java virtual Machine(JVM) is a virtual Machine that provides runtime
environment to execute java byte code. The JVM doesn't understand Java
typo, that's why you compile your *.java files to obtain *.class files that
contain the bytecodes understandable by the JVM.
JVM control execution of every Java program. It enables features
such as automated exception handling, Garbage-collected heap.
Every Java developer knows that bytecode will be executed by JRE
(Java Runtime Environment). But many doesn't know the fact that
JRE is the implementation of Java Virtual Machine (JVM), which
analyzes the bytecode, interprets the code, and executes it. It is very
important as a developer that we should know the Architecture of the
JVM, as it enables us to write code more efficiently. In this article, we
will learn more deeply about the JVM architecture in Java and the
different components of the JVM.
How Does the JVM Work?
The JVM is divided into three main subsystems
 Class Loader Subsystem
 Runtime Data Area
 Execution Engine
Methods in Java
Method describe behavior of an object. A method is a collection of
statements that are group together to perform an operation.
Syntax :
Example of a Method
Method definition in java
Modifier : Modifier are access type of method. We will discuss it in
detail
later.
Return Type : A method may return value. Data type of value return
by
a
method
is
declare
in
method
heading.
Method
name
:
Actual
name
of
the
method.
Parameter
:
Value
passed
to
a
method.
Method body : collection of statement that defines what method does.
Parameter Vs. Argument
While talking about method, it is important to know the difference between
two terms parameter and argument.
Parameter is variable defined by a method that receives value when the
method is called. Parameter are always local to the method they dont have
scope outside the method. While argument is a value that is passed to a
method when it is called. parameter and argument
Call-by-value and call-by-reference
There are two ways to pass an argument to a method call-by-value : In this
approach copy of an argument value is pass to a method. Changes made
to the argument value inside the method will have no effect on the
arguments. call-by-reference : In this reference of an argument is pass to a
method. Any changes made inside the method will affect the agrument
value. NOTE : In Java, when you pass a primitive type to a method it is
passed by value whereas when you pass an object of any type to a method
it is passed as reference.
Example of call-by-value
Example of call-by-reference
Method overloading
If two or more method in a class have same name but different parameters,
it is known as method overloading.
Method overloading is one of the ways through which java supports
polymorphism. Method overloading can be done by changing number of
arguments or by changing the data type of arguments. If two or more
method have same name and same parameter list but differs in return type
are not said to be overloaded method
Different ways of Method overloading
There are two different ways of method overloading
Method overloading by changing data type of Arguments
Example :
You can see that sum() method is overloaded two times. The first takes two
integer arguments, the second takes two float arguments.
Method overloading by changing no. of argument.
Example
:
In this example the find() method is overloaded twice. The first takes
two arguments to calculate area, and the second takes three
arguments
to
calculate
area.
When an overloaded method is called java look for match between the
arguments to call the method and the method's parameters. This
match need not always be exact, sometime when exact match is not
found, Java automatic type conversion plays a vital role.
Example
of
Method
overloading
with
type
promotion.
Constructor in Java
Constructor in java is a special type of method that is used to initialize
the object.
Java constructor is invoked at the time of object creation. It constructs
the values i.e. provides data for the object that is why it is known as
constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.


Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:



Default constructor (no-arg constructor)
Parameterized constructor
Java constructor
Java Default Constructor
A constructor that have no parameter is known as default
constructor.
Syntax of default constructor:
Example of default constructor
In this example, we are creating the no-arg constructor in the
Bike class. It will be invoked at the time of object creation.
Rule: If there is no constructor in a class, compiler
automatically creates a default constructor.
Default constructor
Q) What is the purpose of default constructor?
Default constructor provides the default values to the object like
0, null etc. depending on the type.
Example of default constructor that displays the
default values
Explanation:In the above class,you are not creating any
constructor so compiler provides you a default constructor.Here
0 and null values are provided by default constructor.
Java parameterized constructor
A constructor that have parameters is known as parameterized
constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to
the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student
class that have two parameters. We can have any number of
parameters in the constructor.
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class
can have any number of constructors that differ in parameter
lists.The compiler differentiates these constructors by taking
into account the number of parameters in the list and their
type.
Example of Constructor Overloading
Difference between constructor and method in
java
There are many differences between constructors and
methods. They are given below.
Java Constructor
Java Method
Constructor is used to initialize the state of an Method is used to expose
object.
behaviour of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default
Method is not provided by
constructor if you don't have any constructor. compiler in any case.
Constructor name must be same as the class Method name may or may not
name.
be same as class name.
Java Copy Constructor
There is no copy constructor in java. But, we can copy the
values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into
another in java. They are:

By constructor

By assigning the values of one object into another

By clone() method of Object class
In this example, we are going to copy the values of one object into
another using java constructor.
Copying values without constructor
We can copy the values of one object into another by assigning the
objects values to another object. In this case, there is no need to create
the constructor.
Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.All student
have its unique rollno and name so instance data member is good.Here,
college refers to the common property of all objects.If we make it
static,this field will get memory only once. Java static property is shared
to all objects.
Example of static variable
//Program of static variable
Static Variable
Program of counter without static variable
In this example, we have created an instance variable named count
which is incremented in the constructor. Since instance variable gets the
memory at the time of object creation, each object will have the copy of
the instance variable, if it is incremented, it won't reflect to other
objects. So each objects will have the value 1 in the count variable.
Program of counter by static variable
As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain
its value.
2) Java static method
If you apply static keyword with any method, it is known as static
method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an
instance of a class.
static method can access static data member and can change the
value of it.
Example of static method
Restrictions for static method
There are two main restrictions for the static method. They are:

The static method can not use non static data member or call
non-static method directly.

This and super cannot be used in static context.
Q) why java main method is static?
Ans) because object is not required to call static method if it
were non-static method, jvm create object first then call main()
method that will lead the problem of extra memory allocation.
3) Java static block


Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
Q) Can we execute a program without main()
method?
Ans) Yes, one of the way is static block but in previous version
of JDK not in JDK 1.7.
Test it Now
Output:static
block
is
invoked
(if
not
JDK7)
In
JDK7
and
above,
output
will
be:
Output:Error: Main method not found in class A3, please define the
main
method
as:
public static void main(String[] args)
This keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
 This can be used to refer current class instance variable.
 This can be used to invoke current class method (implicitly)
 This() can be used to invoke current class constructor.
 This can be passed as an argument in the method call.
 This can be passed as argument in the constructor call.
  This can be used to return the current class instance from the method.
Java this keyword
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If
there is ambiguity between the instance variables and parameters, this
keyword resolves the problem of ambiguity.
Note:- parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword
while invoking the method. Let's see the example
this keyword
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class
constructor. It is used to reuse the constructor. In other words, it is used for
constructor chaining.
Calling default constructor from parameterized constructor:
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is
mainly used in the event handling. Let's see the example:
5) this: to pass as argument in the constructor call
We can pass the this keyword in the constructor also. It is useful if we have
to use one object in multiple classes. Let's see the example:
6) this keyword can be used to return current class
instance
We can return this keyword as an statement from the method. In such
case, return type of the method must be the class type (non-primitive). Let's
see the example:
Syntax of this that can be returned as a statement
Example of this keyword that you return as a statement from the method
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of parent class, and you can add new
methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child
relationship.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax of Java Inheritance
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.
In the terminology of Java, a class which is inherited is called parent or
super class and the new class is called child or subclass.
Java Inheritance Example
Inheritance in java
Programmer is the subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A Employee.It means that
Programmer is a type of Employee.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
 Single
 Multilevel
 Hierarchical
In java programming, multiple and hybrid inheritance is supported through
interface only.
Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance.
For Example:
Single Inheritance Example
Multilevel Inheritance Example
Hierarchical Inheritance Example
To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
Method Overloading in Java
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Advantage of method overloading
 Method overloading increases the readability of the program.
 Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
In this example, we are creating static methods so that we don't need to
create instance for calling methods.
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The
first add method receives two integer arguments and second add method
receives two double arguments.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the
method that has been provided by one of its parent class, it is known as
method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 Method must have same name as in the parent class
 Method must have same parameter as in the parent class.
Must be IS-A relationship (inheritance).
Example of method overriding
In this example, we have defined the run method in the subclass as defined
in the parent class but it has some specific implementation. The name and
parameter of the method is same and there is IS-A relationship between
the classes, so there is method overriding.
Real example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get rate
of interest. But, rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Java method overriding example of bank
super keyword in java
The super keyword in java is a reference variable which is used to refer
immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class
is created implicitly which is referred by super reference variable.
Usage of java super Keyword
 Super can be used to refer immediate parent class instance variable.
 Super can be used to invoke immediate parent class method.
 Super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of
parent class. It is used if parent class and child class have same
fields.
Java Package
A java package is a group of similar types of classes, interfaces and subpackages.
Package in java can be categorized in two form, built-in package and
user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
Advantage of Java Package
 1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 2) Java package provides access protection.
 3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
How to access package from another package?
There are three ways to access the package from outside the package.
 1.import package.*;
 2.import package.classname;
 3.fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
Example of package that import the packagename.*
//save by A.java
//save by B.java
2) Using packagename.classname
If you import package.classname then only declared class of this package
will be accessible.
Example of package by import package.classname
//save by A.java
//save by B.java
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java
//save by B.java
Java Array
Normally, array is a collection of similar type of elements that have
contiguous memory location.
Java array is an object the contains elements of similar data type. It is a
data structure where we store similar elements. We can store only fixed set
of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Java Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
 Single Dimensional Array
 Multidimensional Array
 Single Dimensional Array in java
Syntax to Declare an Array in java
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
Output: 10
20
70
40
50
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic
on any array.
Let's see the simple example to get minimum number of an array using
method.
Multidimensional array in java
In such case, data is stored in row and column based index (also known as
matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
Example to initialize Multidimensional Array in java
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method
passing a value, it is known as call by value. The changes being done in
the called method, is not affected in the calling method.
Example of call by value in java
In case of call by value original value is not changed. Let's take a
simple
example:
read in java
A thread is a lightweight sub process, a smallest unit of processing. It is a
separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't
affect other threads. It shares a common memory area.
Multithreading in Java
Multithreading in java is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a
common memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less time
than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
 1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
 2) You can perform many operations together so it saves time.
 3) Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU. Multitasking can be achieved by two
ways:
 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process have its own address in memory i.e. each process allocates separate memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading registers,
memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space
 Thread is lightweight.
 Cost of communication between the thread is low.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5
states.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread
There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run():
is used to perform action for a thread.
public void start():
starts the execution of the thread.JVM calls the
run() method on the thread.
public void sleep(long
miliseconds):
Causes the currently executing thread to sleep
(temporarily cease execution) for the specified
number of milliseconds.
waits for a
thread to die.
public void join():
public void join(long
miliseconds):
waits for a thread to die for the specified
miliseconds.
public int getPriority():
returns the priority of the thread.
public int setPriority(int
priority):
changes the priority of the thread.
public String getName(): returns the name of the thread.
public void
changes the name of the thread.
setName(String name):
public Thread
currentThread():
returns the reference of currently executing
thread.
public int getId():
returns the id of the thread.
public Thread.State
getState():
returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield():
causes the currently executing thread object to
temporarily pause and allow other threads to
execute.
public void suspend():
is used to suspend the thread(depricated).
public void resume():
is used to resume the suspended
thread(depricated).
public void stop():
is used to stop the thread(depricated).
public boolean isDaemon():
public void
marks the thread as daemon or user thread.
setDaemon(boolean b):
public void interrupt():
interrupts the thread.
public boolean
isInterrupted():
tests if the thread has been interrupted.
public static boolean
interrupted():
tests if the current thread has been interrupted.
tests if the
thread is a
daemon thread.
Runnable interface:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface
have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:start() method of Thread class is used to start a newly created thread.
The
thread
moves
from
New
state
to
the
Runnable
state.
When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
Output:thread is running...
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:
 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.
Lifecycle of Java Applet
 Applet is initialized.
 Applet is started.
 Applet is painted.
 Applet is stopped.
 Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component
class provides 1 life cycle methods for an applet.
Java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.
 Public void init(): is used to initialized the Applet. It is invoked only once.
 Public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
 Public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
 Public void destroy(): is used to destroy the Applet. It is invoked only once.
How to run an Applet?
There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).
Simple example of Applet by 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
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
myapplet.html
Simple example of Applet by 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
First.java. Now Html file is not required but it is for testing purpose only.
//First.java
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java