Java Program2 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Java:

Features of Java:
1. Simple : Java is easy to learn and use. There is no surprising feature in Java.
2. Object Oriented: In Java everything depends upon object.
3. Distributed: Java is designed to support various levels of network connectivity, it
supports TCP/IT protocol. They can open and access remote objects on the
internet.
4. Interpreted : Java is compiled to bytecode which are interpreted by Java run time
environment.
5. Robust: Java is strictly typed language. It not only performs code check at compile
time but also at run time.
6. Secure
7. Architecture Neutral: Java bytecode can be interpreted by any system that
implements JVM. So Java applications are able to run on most platforms.
8. Dynamic:Java supports dynamic loading of classes(Load on demand), automatic
memory management(garbage collection)
9. Multithreaded

Java Bytecode:It is the intermediate representation of Java program. Once bytecode


has been generated, it can be transferred across a network and executed by JVM.
Bytecode files have “.class” extension.

Java Virtual Machine(JVM): It is a byte code processing machine that converts


bytecode into executable code. JVM is an interpreter for bytecode. JVM provides
run time environment in which bytecode can be executed.

JRE(Java Run time Environment)- It is used to provide run time environment. It


is the implementation of JVM. It contains set of libraries and other files JVM uses at
run time.
JRE -> JVM + set of libraries + other files

Java Development Kit(JDK)- It contains JRE + development tools(javac , java)


OOP principles
1. Encapsulation: it is defined as wrapping of data under a single unit. It is the
mechanism that binds together code and data it manipulates. It is a protective
shield that prevents the data from being accessed by the code outside the shield.
2. Polymorphism: it means many forms (one thing used in different forms). We can
perform polymorphism in Java by method overloading and method overriding.
3. Inheritance: it is a process by which one class can acquire the properties of
another class. The idea behind inheritance is that are built upon existing class.
When inherit from an existing class, we reuse the methods and fields of a parent
class and we can also add new methods also.
4. Abstraction: it is the process used to hide details and only show the essential
feature of the object. It deals with outside view of the object, only essential details
are displayed to the user.

Data types in Java: there are two types of data types


- Primitive (Numeric and Boolean)
Numeric (Character (2-bytes), Integral(integer(byte, short, int, long) and
floating))
Boolean (boolean 1-bit true or false)
- Non-primitive (String, Array)

Array in Java:
type name[]=new type[size];
int a[]=new int[10];
int a[]={2,4,6,7,};

Arrays are dynamically allocated in Java, so we cannot use any element outside the
range of array.

Defining a class:
class class-name
{
Member-1;
Member-2;
-
-
}
e.g. //Test.java
class Test
{
public static void main(String r[])
{
int a,b;
a=10;
b=12;
System.out.println(“a=”+a+”\nb=”+b);
}
}
*compile the source file javac Test.java
javac it is jdk tool that generates bytecode (Test.class)
*execute the bytecode java Test
*specify path
c:\documents and settings\students>path c:\program files\java\jdk1.6.0_21\bin

Constructor: It is a member function of a class that has the same as the class
name. It doesn’t have any return type not even main. It is used to initialize an
object upon its creation.

//Java Parameterless constructor

class Student
{
int roll;
String sname;
Student() //constructor
{
roll=90;
sname=”Amit”;
}
void display() //display function
{
System.out.println(“Rollno:”+roll+”\n Name:”+sname);
}
}
class Smain
{
public static void main(String s[])
{
Student s1=new Student(); //creating object
s1.display();
}
}

//Java Parameterized Constructor


class Student
{
int roll;
String sname;
Student(int r,String name) //constructor
{
roll=r;
sname=name
}
void display() //display function
{
System.out.println(“Rollno:”+roll+”\n Name:”+sname);
}
}
class Smain
{
public static void main(String s[])
{
Student s1=new Student(1011,”Amit”); //creating object
Student s2=new Student(1012,”Anil”);
s1.display();
s2.display();
}
}

//Constructor Overloading in Java


class Student
{
int roll;
String sname;
Student() //constructor
{
roll=1001;
sname=”Amit”;
}

Student(int r,String name) //constructor


{
roll=r;
sname=name
}
void display() //display function
{
System.out.println(“Rollno:”+roll+”\n Name:”+sname);
}
}

class Smain
{
public static void main(String s[])
{
Student s1=new Student(); //creating object
Student s2=new Student(1012,”Anil”);
s1.display();
s2.display();
}
}

Inheritance in Java
1. Super class (Base class)
2. Sub Class (Derived class)
Class Abc
{
}
Class Abc1 extends Abc
{
}

e.g.
class Calc
{
int r;
void add(int a,int b)
{
r=a+b;
System.out.println(“Sum=”+r);
}
int sub(int a,int b)
{
r=a-b;
return r;
}
}

class Calc1 extends Calc


{
int r;
void multiplication(int a,int b)
{
r=a*b;
System.out.println(“Product=”+r);
}
}

class Smain
{
public static void main(String s[])
{
int z;
Calc1 s =new Calc1(); //creating object
s.add(20,30);
z=s.sub(78,21);
System.out.println(“Difference=”+z);
s.multiplication(9,15);
}
}

Types of Inheritance in Java Java


*To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

The super keyword


1. It is used to access the members of superclass that are hidden by the members of its
subclass(differentiate the members of superclass from the members of subclass, if they have
same names)
2. It is used to invoke the superclass constructor from subclass.
e.g. super.member(method or variable)
// method overriding
Class Abc
{
int a,b;
Abc(int i, int j)
{
a=i; b=j;
}
void sum()
{
int s;
s=a+b;
System.out.println(“Sum=”+s);
}
void display()
{
System.out.println(“\na=”+a+”\nb=”+b);
}
}

class Abc1extends Abc


{
int c;
Abc1(int i, int j, int k)
{
a=i; b=j; c=k;
}

void sum()
{
int s;
s=a+b+c;
System.out.println(“Sum=”+s);
}

void display()
{
System.out.println(“\na=”+a+”\nb=”+b+”\nc=”+c);
}
}

class Smain
{
public static void main(String s[])
{
Abc1 ob1 =new Abc1(); //creating object
Abc1 ob2 =new Abc1(10,20,30);
ob1.sum();
ob2.sum();
ob1.display();
ob2.display();

}
}

// uses of super keyword


Class Abc
{
int a,b;
Abc(int i, int j)
{
a=i; b=j;
}
int sum()
{
int s;
s=a+b;
return s;
}
void display()
{
System.out.println(“\na=”+a+”\nb=”+b);
}
}

class Abc1extends Abc


{
int c;
Abc1(int i, int j, int k)
{
super(i,j);
c=k;
}
void sum()
{
int s;
s=super.sum()+c;
System.out.println(“Sum=”+s);
}

void display()
{
super.display();
System.out.println(“\nc=”+c);
}
}

class Smain
{
public static void main(String s[])
{
Abc1 ob1 =new Abc1(); //creating object
Abc1 ob2 =new Abc1(10,20,30);
ob1.sum();
ob2.sum();
ob1.display();
ob2.display();

}
}
Method Overloading:
Method Overloading is a feature that allows a class to have more than one method having the
same name, but they must differ in number and type of arguments.
Method overloading is not possible by changing the return type of the method only.

e.g.
class Methodoverload
{
int sum(int a,int b)
{
return a+b;
}
float sum(float a,float b)
{
return a+b;
}
}
Class Smain
{
public static void main(String s[])
{
int r1;
float r2;
Methodoverload ob1 =new Methodoverload (); //creating object
r1=ob1.sum(20,600);
r2=(float)ob1.sum((float)20.6,(float)30.56);
System.out.println(“\ninteger Sum=”+r1);
System.out.println(“\nFloating Sum=”+r2);

}
}

The final Keyword : It is non-access modifier in Java. Final is used for finalizing the
implementation of variable, method or class.
-To prevent variable from its content being modified
-To prevent method overriding
-To prevent inheritance
e.g. class Test
{
final int a=90;//final variable initialize only once
void run()
{
a=400;
}
public static void main(String args[])
{
Test ob=new Test();
ob.run();
}
}
//compile time error

e.g. //To prevent method overriding


class Test
{
final void run()
{
System.out.println("running");
}

}
class Test1 extends Test
{
void run()
{
System.out.println("running safely ");
}

public static void main(String args[])


{
Test1 ot= new Test1();
ot.run();
}
}
//compile time error
Abstract class:
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods(methods with body). It needs to be extended and its method
implemented. It cannot be instantiated.
Sometimes we want to create a superclass that only defines a generalized form that will be
shared by all of its subclasses leaving it to each subclass to fill in the details , such a class
determine the nature of the methods that the subclass must implement.

Syntax:
abstract class Exam
{
------
}
An abstract class must have at least one abstract method.
abstract void sum();

e.g.
abstract class Shape
{
abstract void area();
}

class Rectangle extends Shape


{
int a,b;
Rectangle(int i, int j)
{
a=i; b=j;
}
void area()
{
int s;
s=a*b;
System.out.println("\nArea of rectangle "+s);
}
}

class Square extends Shape


{
int a;
Square(int i)
{
a=i;
}
void area()
{
int s;
s=a*a;
System.out.println("\nArea of square "+s);
}
}
class Test
{
public static void main(String args[])
{
Rectangle or=new Rectangle(15,8);
Square os=new Square(10);
or.area();
os.area()
}
}

//Another example
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor.
abstract class Person
{
String name,gender;
Person(String n,String g) //constructor
{
name=n; gender=g;
}
abstract void work(); //abstract method

String toString() // non-abstract method

{
return “Name-“+name+” Gender-“+gender”;
}
void changeName(String newname)
{
name=newname;
}
}
class Emp extends Person
{
int empid;
Emp(String n,String g,int id)
{
Super(n,g);
Empid=id;
}
public void work()
{
if(empid==0)
System.out.println("\Not Working ");
else
System.out.println("\nworking as employee ");
}
}
class Test
{
public static void main(String args[])
{
Emp ob1=new Emp(“Amit”,”m”,201);
Person ob2=new Emp(“Anil”,”m”,205); //in terms of abstract class
ob1.work();
ob2,work();
ob1.changeName(“Kumar”);
System.out.println(ob1.toString());
}
}

Java Input:
There are several ways to get input from the user in Java.
For that import Scanner class
import java.util.Scanner
create an object of Scanner class which will be used to get input from the user.
Scanner ip=new Scanner(System.in);
int a=ip.nextInt(); //method of Scanner class to get integer data
float b=ip.nextFloat(); //to get float data
String s=ip.next(); //to get string
String s=ip.nextLine();
Double d=ip.nextDouble();

Java Packages:
Java packages are group of similar type of classes, interfaces and sub-packages.
Packages in java categorized in two forms:
-built-in packages (java, lang, io, util)
-user defined packages

Advantages: 1. Provided access protection


2. Removing naming collision
3. Categorize the classes and interfaces so that can be easily maintained

Defining a package:
Syntax: package pkgname; //it is the first statement in any java source file

e.g package cs;

we can also create hierarchy of packages


package pkg1[.pkg2][.pkg3];
e.g. package cs.cs1.cs2;

*create a directory under current directory


*compile the source file
*put class file into directory created
*execute program

Importing packages: import keyword is used to import built-in and user defined packages
in Java source file.
Syntax : import pkg.*|classname;
e.g. import cs.*;
import cs.Test;

e.g package cs;


public class Circle
{
private double radius;
public Circle(double r)
{
radius=r;
}
public double area()
{
return(3.14*radius*radius);
}
}
import cs.*; //import cs.Circle;
class Test
{
public static void main(String args[])
{
double a;
Circle ob=new Circle(5.3);
a=ob.area();
System.out.println(“Area of circle:”+a);
}
}

Access Modifiers: In java there are four categories of visibility for class memebers
a). subclasses in same package
b). Non-sub classes in same package
c). subclasses in different package
d). Non-sub classes in different package

There are four access modifiers: Private, default(no-modifier), Protected, Public


Private are not accessible outside the class.
Public can be accessed form anywhere.
Default can be visible to subclasses as well as to other classes in the same package.
Protected can be accessible outside the package but only to subclasses.

*A class can have only two access: default and public (if a class have default access then it
is not accessible outside the package and public class can be accessed by any code).

//Exam.java (package cs)


package cs;
public class Exam
{
private int a;
int b;
protected int c;
public int c;
public Exam() //constructor
{
System.out.println(“Exam Constructor”);
a=5; b=6; c=7; d=8;
System.out.println(“\na=”+a+“\tb=”+b+“\tc=”+c+“\td=”+d);
}
}

//Exam1.java (package cs) same package sub-class


package cs;
public class Exam1 extends Exam
{
public Exam1() //constructor
{
System.out.println(“Exam1 Constructor”);
b=60; c=70; d=80;
System.out.println(“\nb=”+b+“\tc=”+c+“\td=”+d);
}
}

//Exam2.java (package cs) same package non-sub class


package cs;
public class Exam2
{
public Exam2() //constructor
{
Exam ob=new Exam();
System.out.println(“Exam2 Constructor”);
ob.b=600; ob.c=700; ob.d=800;
System.out.println(“\nb=”+ob.b+“\tc=”+ob.c+“\td=”+ob.d);
}
}

//Exam3.java (package cs1) different package sub class


import cs.*; //or import cs.Exam
package cs1;
public class Exam3 extends Exam
{
public Exam3() //constructor
{
System.out.println(“Exam3 Constructor”);
c=7000; d=8000;
System.out.println(“\nc=”+c+“\td=”+d);
}
}

//Exam4.java (package cs1) different package non-sub class


import cs.*; //or import cs.Exam
package cs1;
public class Exam4
{
public Exam4() //constructor
{
System.out.println(“Exam4 Constructor”);
Exam ob=new Exam();
ob.d=80;
System.out.println(“\nd=”+ob.d);
}
}

// importing packages
import cs.*;
import cs1.*
class Test
{
public static void main(String args[])
{
Exam ob1=new Exam();
Exam1 ob2=new Exam1();
Exam2 ob3=new Exam2();
Exam3 ob4=new Exam3();
Exam4 ob5=new Exam4();

}
}
Interfaces:
Interfaces are similar to classes, but they lack instance variables and their methods are
declared without any body. Using an interface we specify what a class must do but not how
it does it.
Once an interface is defined, any number of classes can implement an interface. One class
can implement any number of interfaces.
An interface is blue print of class. It is a mechanism to achieve abstraction and multiple
inheritance in Java.

An interface is similar to class in the following ways:


- An interface can contain any number methods
- It is stored in a file with “.java” extension
- The bytecode of an interface appears in “.class” file
An interface is different from a class in the following ways:
- We cannot instantiate an interface
- It does not contain any constructor
- All the methods in an interface are abstract
*interfaces supports dynamic method resolution at run time
Defining an interface:
Syntax: access interface name
{
type var=value;
return-type method1(parameter list);
return-type method2(parameter list);
}

class Main implements interface1,interface2----


{

access is either public or not used


name is the name of interface
methods which are declared have no bodies
variable in interface are implicitly final and static
//program
e.g.
interface shape
{
void area();
}

class Rectangle implements Shape


{
int a,b;
Rectangle(int i,int j)
{
a=i; b=j;
}
public void area()
{
int s;
s=a*b;
System.out.println(“\nArea of Rectangle:’+s);
}
}
Class Test
{
public static void main(String args[])
{
Rectangle ob=new Rectangle(51,23);
Ob.area();
}
}

Java Exceptions: An exception is an object that describes an exceptional condition, during the
execution of program. When an exceptional condition arises the normal flow of program
disrupted and program terminates abnormally.
An exception can occur for many different reasons:
- A user has entered an invalid data
- A network connection in the middle
- A file that needs to be opened cannot be found
Java exception handling is managed via five keywords- try, catch, throw, throws and finally

Program statements that we want to monitor for exceptions are contained within a try block.
If an exceptions occurs within try block it is thrown. We can catch the exception using catch
block.
System generated exceptions are automatically thrown by Java run time system.
To manually thrown an exception use throw clause.
Any code that must be absolutely executed it is put in finally block.

Syntax: try
{
---------
}
catch(Exceptiontype obj)
{
--------
}
finally
{
--------
}

//uncaught exception
class Test
{
public static void main(String args[])
{
int a,b=0;
a=100/b;
System.out.println(“\na=”+a);
}
}

The program construct an exception and throws the exception


Output of above program:
java.lang.ArithmeticException:/by zero at Test.main(Test.java:6)
any exception that is not caught by our program will be processed by default exception
handler.

Using try and catch:


class Test
{
public static void main(String args[])
{
int a,b=0;
try
{
a=100/b;
System.out.println(“\na=”+a);
}

catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
System.out.println(“\After try catch”);
}
}

//we can display the description of exception


System.out.println(“\Exception:”+e);
Multiple catch clauses:
import java.util.*;
class Test
{
public static void main(String args[])
{
int a,b;
int c[]={2,4,6};
Scanner ob=new Scanner(System.in);
System.out.println(“\nEnter values for b”);
b=ob.nextInt();
try
{
if(b==1)
a=50/(b-1); //divide by zero
else
c[3]=100; //ArrayIndexOutOfBoundsException
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“\nException”+e);
}

finally
{
System.out.println(“\nFinally block”);
}
}
}
throw clause: it is used to manually throw an exception.
Syntax: throw throwableinstance;

import java.util.*;
class Test
{
public static void main(String args[])
{
int a,b;
Scanner ob=new Scanner(System.in);
System.out.println(“\nEnter values for b”);
b=ob.nextInt();
try
{
if(b==0)
throw new ArithmeticException(“Divide by zero”);
else
{
a=50/b;
System.out.println(“\na=”+a);
}
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
}
}

throws clause: a throws clause lists the types of exceptions that a method might throw
Syntax:
return-type method-name() throws exception-list
{
-----------
}
e.g.
class Test
{
public static void main(String args[])
{
try
{
calc();
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
}
void calc() throws ArithemeticException
{
int a=0,b;
b=200/a;
System.out.println(“\nb=”+a);
}
}
String Handling: A string is a sequence of characters. Java implements string as object of type
String. (String is an in-built class of java.lang package)
When we create a string object, we are creating a string that cannot be changed.
The String constructor:
String can support several constructors.
String s=new String();
To create string initialized by an of characters:
Char a[]={‘B’,’i’,’r’,’l’,’a’};
String s=new String(a); // is initialize with “Birla”
String s1=new String(s); //create string object that contain same character sequence as
another string object
System.out.println(s);
System.out.println(s1); //output of both statements are “Birla”

Character Extracion: we can extract character characters from a given string.

charAt()- to extract a single character from a given string.


char charAt(int pos); // pos is index of character
e.g. char c;
c=”Programming”.charAt(5) //assign r to c
getChars()- to extract more than one character.
void getChars(int start,int end,char a[],int astart);
a- Where extracted character copied
astart- index in a where extracted character copied
e.g.
String s=”This is my Java program”;
int start=12, end=15;
char a[]=new char[15];
s.getChars(start,end,a,0);

//program
public class Sexample
{
public static void main(String args[])
{
int start=9,end=10;
String s1="This is my Java Program"; //creating string by java string literal
char s2[]={'P','r','o','g','r','a','m'};
String s3=new String(s2); //converting char array to string
String s4=new String("JAVA"); //creating java string by new keyword
char ch;
char st[]=new char[15];
ch=s1.charAt(4);
s1.getChars(start,end,st,0);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(ch);
System.out.println(st);
}
}

*when we creating String object, we are creating a string that cannot be changed.
For modification of string there is companion class of String called StringBuffer, whose
object contain strings that can be modified after they are created.
Java StringBuffer class is used to create modifiable string.
Constructor of StringBuffer class:
StringBuffer() //creates an empty string buffer with initial capacity of 16
StringBuffer(String s) //creates a string buffer with the specified string
StringBuffer(int capacity); // creates an empty string buffer with specified capacity
//methods of StringBuffer class
append()- it is used to append the specified string with this string.
e.g. StringBuffer sb=new StringBuffer(“Java”);
sb.append(“Program”);
insert(int offset,String s)- it is used to insert the specified string with this string at specified
position.
e.g. StringBuffer sb=new StringBuffer(“Java program”);
sb.insert(5 ,“ First”);

Multithreading in Java: Thread is light weight process, a small unit of processing.


Multithreading in Java is a process of executing multiple threads simultaneously.
Multiprocessing and multithreading both are used to achieve multitasking.
Multithreading enables to write very efficient programs that make maximum use of CPU
because idle time can kept to a minimum.
The transmission of data over a network is much slower than the rate at which the computer ca
process it.in s single thread environment program has to wait for each pf these task to finish
before it can proceed to the next one- though CPU is sitting idle most of the time.
The benefit of Java Multithreading is that one thread can pause without stopping other parts of
program.

A thread can be running, It can be ready to run as soon as it gets CPU time.
A running thread can be suspended, which temporarily suspends its activity. A suspended
thread can be resumed, allowing it to pick up where it left off.
A thread can be blocked while waiting fir a resource.
At any time a thread can be terminated, once terminated, it cannot be resumed.

Thread Priorities: Java assigns to each thread a priority that determines how one thread treated
with respect to the others i.e. when one to switch from one running thread to the next.
A thread can be pre-empted by a higher priority thread.

Thread class and Runnable interface: Java Multithreading is built upon Thread class and its
companion Runnable interface. To create a new thread, program either extends Thread class or
implements the Runnable interface.

Methods of Thread class:


getName()- obtains thread name.
gerPriority()- obtains thread priority
isAlive()- determine if thread is still running
join()- wait for thread to terminate
run()- entry point for the thread
sleep()- suspends a thread for a period of time
start()- start a thread by calling its run method

The Main thread- when a Java program starts up one thread is automatically created i.e. the
main thread.
It is important for two reasons :
- It is the thread from which other “child” will be spawned
- It must be the last thread to finish execution because it perform various shutdown
activities
Creating a Thread: There are two ways for creating a thread in Java:
- extends the Thread class
- implements Runnable interface

to implement Runnable a class only implement a single method called run().


After creating a new thread, it will not start until call its start() method.

e.g. class NThread implements Runnable


{
Thread t;
NThread()
{
//create a new thread
t=new Thread(this,”My Thread”);
System.out.println(“New Thread:”+t);
t.start();
}
//entry point for the thread
public void run()
{
try
{
for(int i=1;i<5;i++)
{
System.out.println(“Child Thread:”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
}
System.out.println(“Exiting New thread”);
}
}
class TDemo
{
public static void main(String args[])
{
new NThread();
try
{
for(int i=1;i<5;i++)
{
System.out.println(“Main Thread:”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“Main Interrupted”);
}
System.out.println(“Exiting Main thread”);
}
}

Output:
New Thread:Thread[New Thread,5,main]
Main Thread:1
New Thread:1
Main Thread:2
New Thread:2
--
--

Creating Multiple Threads:


class NThread implements Runnable
{
String name;
Thread t;
NThread(String tname)
{
//create a new thread
name=tname;
t=new Thread(this,name);
System.out.println(“New Thread:”+t);
t.start();
}
//entry point for the thread
public void run()
{
try
{
for(int i=1;i<5;i++)
{
System.out.println(name+“Thread: ”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
}
System.out.println(name+“Exiting”);
}
}

class TDemo
{
public static void main(String args[])
{
new NThread(“one”);
new NThread(“two”);
new NThread(“three”);

try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println(“Main Interrupted”);
}
System.out.println(“Exiting Main thread”);
}
}

Applets: Applets are small Java programs transmitted over the internet and can be
automatically installed and run as a part of web document.
An applet does not have any main method. Applets are designed to be embedded within an
HTML page.

Advantages:
1). It works on client side so it has less response time.
2). Secured
3). It can be executed by Java compatible web browser

Life cycle of Applet:


init()- it is the first method to be called. In this we initialize variables. The method is executed
only once during the run time of applet.

start() : it is automatically called after init. It is called each time an applet is displayed on
screen. If a user leaves a page and comes back, the applet resumes execution at start()

paint(): it is invoked automatically after the start() method and also any time the applet needs
to repaint itself in the browser.
stop(): it is called automatically when user leaves web page containing an applet (goes to
another page)

destroy(): it is called when an applet needs to be removed completely from memory. To free
resources the applet may be using. The stop() is always called before destroy.

e.g
import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume execution
}
public void paint(Graphics g)
{
//display contents of window
}
public void stop()
{
//suspends execution
}
public void destroy()
{
//perform shutdown activities
}

Applet display methods:


drawString() method of Graphics class
void drawstring(String message, int x, int y)
message is the message to be displayed
x and y are the coordinates

To set foreground and background color:


void setForeground(Color newcolor)
void setBackground(Color newcolor)
Color.red Color,green

e.g.
import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“BKBIET”,20,30);
}
}

Invoking an applet: It is invoked by embedding an applet in an HTML file.


(.html file)
<HTML>
<applet code=”MyApplet” width=”100” height=”100”>\
</applet>
</HTML>

You might also like