Professional Documents
Culture Documents
History Of Java
In December 1990, Patrick Naughton, James Gosling and Mike Sheridan of Sun
Microsystems started to work on a project known as the Green Project. At that tme the
programming languages that was ruling the software market was C and C++. However, C
and C++ have certain complexity and limitations as the programmers have to be
concerned about the platform which they are working on. This frustrated the project team
and they decided to create an object-oriented development environment based on C++,
but easier to learn and use. In April 1991, the team decided on embedded systems
software for smart consumer devices as the delivery platform for their project. James
Gosling wrote the original compiler called "Oak" and, with the other team members,
developed a runtime interpreter for what would become the Java language. In 1994 the
Green Project was aborted because of its restricted market. But from the "OAK emerged
a new language called JAVA.
Java can be used to create two different types of programs, which are
2. Applets: - Applets are programs that are woven directly into Web pages. It requires a
web browser that has JVM to run on the desktop. They are pieces of executable Java
code that are embedded in an HTML document using the <APPLET> tag. To run an
applet without a browser we need Appletviewer (discussed in the later part of the
book). Applets have been discussed in detail in the later chapters of this book.
Features of Java
Java is a simple, Object Oriented, distributed, interpreted, robust, secure, architecture
neutral, portable, high performance, multithreaded and dynamic language.
> Simple
The fundamental concepts of Java technology can be are grasped quickly and hence
programmers can be productive from the very beginning.
> Object Oriented
Java is purely object-oriented and supports the basic features of object orientation such as
abstraction, encapsulation, inheritance, and polymorphism.
> Distributed
It has been developed in such a way that it has the capability to share data and resources
across the network. Using Java, multiple programmers can work on a single project from
multiple remote locations.
> Interpreted and compiled
The Java compiler doesn't generate "machine code" in the sense of native hardware
instructions--rather, it generates byte-codes a high-level, machine-independent code for a
hypothetical machine called the Java Virtual Machine (JVM) that is implemented by
the Java interpreter and run-time system. When a program has to be executed, the code is
fetched into the memory and interpreted on the user machine.
> Robust
Java is intended for developing software that must be robust, highly reliable, and secure,
in a variety of ways.
> Secure
Memory allocation and reference model impose the First level of security in Java. The
memory layout decision is not made during the compilation time but during the runtime
depending upon the Hardware and software platform where it is executed. The Second
line of defense is the class loader. Whenever a Java system is executing it may in turn
load class or classes from network, which is verified and tested by the byte code loader.
Java programs cannot read or write outside the program environment. So there is less
probability for the existing resources in the memory to be infected by virus.
> Architecture neutral
The Java programs are not transformed into machine dependent executable code during
compilation. Instead the Java compiler converts the source code into a binary format
called Byte code. The Java Interpreter that resides inside the Java Virtual Machine then
executes this Byte code within the Java Virtual Machine .
Portable
Since Java programs take an approach of byte code therefore it is portable to any system
on which the Java interpreter and run-time systems have been implemented.
> High performance
Java gives better performance than any Interpreter based language since the interpreter
can run at full speed without checking the runtime environment.
Like as
Output :
Hello this is is Java
Java is Good Language
The last step before you can use the JDK is to set the PATH environment variable to
indicate where the JDK's tools are installed.
1. Opening the System Properties dialog. Right click on the My Computer icon on
your desktop and select Properties from the menu.
2. Opening the Environment Variables dialog. Select the Advanced tab at the top of
the System Properties dialog (Fig. 14). Click the Environment Variables button to
display the Environment Variables dialog (Fig. 15).
Next :-
1. Changing the contents of the PATH variable. Place the cursor inside the Variable Value
field. Use the left-arrow key to move the cursor to the beginning of the list. At the
beginning of the list, type the name of the directory in which you placed the JDK followed
by \bin; (Fig. 17). If you chose the default installation directory in Step 4 of Installing the
J2SE Development Kit (JDK), you will add C:\Program Files\Java\jdk1.5.0\bin; to
the PATH variable. Click the OK button to complete the modification of the PATH variable.
[Note: The default installation directory is named jdk1.5.0, even though the JDK is now
version 5.0.]
Java Architecture
JDK Tools :
Java Development kit consist mainly of core API classes , a java compiler , and a java
virtual machine interpreter . It also consist of useful utilities for debugging dissemblers ,
documenting java source and for interfacing to java code.
javac filename.java
2. java : The java interpreter ,execute java application byte does directly from class
file.
java classname
3. jdb : The java debugger allows you to step through the program one line at a
time ,set break point and examine variables.
4. Rmic : create skeleton and stubs for remote method invocation .
Rmic filename.class
Start rmiregisrty
6. Jar : java archieve (jar ) file to generate jar files allows multiple java classes and
resources to distributed in one compressed file.
Javadoc filename.java
The java API consist of many classes and methods grouped into several packages . jdk1.2
has 58 packages, it is also known as Java Standard Library.
1. Java.lang :- It contains the main language support class. These deals with object ,
Strings , Multithreading and basic features of Java.
2. Java.util :- It provides classes that support collections, date ,time, calendar
operation , parsing and Basic event processing.
3. Java.io :- This package that provides reading and writing data in the form of
streams and device independent file services.
4. Java.awt :- This package provides classes for creating GUI programs . It Contains
java Abstract window Toolkit(AWT).
5. Java.applet : This package includes a set of classes with the support for HTML
embedded java Applet.
6. Java.net : It combines the classes supporting low level Internet programming and
www.
7. Javax.swing : It offers classes for components , higher level controls and
pluggable look . it means that capability of swing classes for customization.
The java.lang package consist a useful class system . This is used to access the
system level behavior , provided for platform independent way. This class consist of
console I/O methods.
1. System.in
2. System.out
3. System.err
Class Input {
int a;
a=Integer.parseInt(br.readLine());
System.out.println(“value of I IS :” +a);
}}
The class is the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and the nature of an object. Any concept
that we wish to implement in a Java program must be encapsulated within a class.
A collection of variable and related function grouped together into a single
unique name is called Class .
Apart from the above rules it is a good programming practice to ensure that the first letter of the
class should be in upper case.
Class Cube
{
Int breadth;
Int height;
Int length;
Sum();
}
class CubeVolume {
public static void main (String args [])
{
Cube myCube = new Cube ();
myCube.length = 20;
Methods
Methods are the functionality exhibited by the object. These methods are described in the
class, the designing template of object.
The syntax for declaring a method is:
class CubeVolume {
public static void main (String args [])
{
Cube myCubel = new Cube ();
Cube myCube2 = new Cube ();
myCubel.setCube(10, 10, 10);
myCube2.setCube(20, 20, 20);
int volume = 0;
volume = myCubel.length * myCubel.breadth * myCubel.height;
System.out.println ("The volume of the first cube is : " + volume);
volume = myCube2.length * myCube2.breadth * myCube2.height;
System.out.println("The volume of the second cube is : " + volume);
}}
Class A
{
Int a;
Public int b;
Private int c;
Void setc(int i)
{
C=I;
}
Int getc()
{
Return c;
}
}
Class Acce
{
Public static void main(String args[])
{
A ob=new A();
Ob.a=10;
Ob.b=23;
Ob.setc(100);
System.out.println(“The value of a is :”+a);
System.out.println(“The value of b is :”+b);
System.out.println(“The value of c is :”+getc());
}}
Constructor
A constructor is a method defined inside the class having the same name that of the class. The
constructor should not have a return type. The constructor contains the code for initializing the
data members of the class. It is executed automatically when an object of the class is created.
At the time of defining a constructor, we have to comply the following two rules:
> A constructor is a method defined inside the class having the same name as that of
the class.
> The constructor should not have a return type. As it is called automatically, you
cannot return any value.
Constructors can be divided into two broad categories, namely:
Default constructors
Every class has at least one constructor. Even if no user-defined constructor is provided,
Java provides a default constructor with no argument and an empty body.
class defaultConst
{
String ecode;
String name;
defaultConst()
{
ecode=”90”;
name=”Susan”;
}
void display()
{
System.out.println("the code of the employee is" + ecode);
System.out.println("the name of the employee is" + name);
}
class dConst{
c1.display();
}
}
Parameterized Constructors
This is because the instance variables of all the objects of defaultConst that we create
will have the value 90 and Susan. So, in order to create multiple objects of defautConst
class that will have different values of ecode and name, we take the help of
Parameterized Constructors .
class
parameterConst{
String ecode;
String name;
parmeterConst(String x,String y)
{
ecode=x;
name=y;
}
void disp()
{
System.out.println("the code of the employee is"+ecode);
System.out.println("the name of the employee is"+name);
}
}
class argumentConst{
public static void main(String args[])
{
parameterConst c1=new parameterConst("9","David");
parameterConst c2 = new parameterConst("10","John");
c1.disp();
c2.disp();
}
}
When an object is no longer referred to by any variables, Java
automatically reclaims the memory used by that object. This is
known as garbage collection. Thus, there are no destructor
methods in Java as in C/C++.
The Finalize () method
Java have the garbage collection mechanism which automatically free up the memory
allocated by the object when that particular object goes out of scope. However, garbage
collector has a limitation in the sense that it is unable to de-allocate the memory occupied
by the non-Java objects such as file descriptors or window system fonts. In order to free
up this space we should use the finalize () method that is defined in java. Before an object
is reclaimed by the garbage collector the finalize () defined for that object will be
invoked.
class Calculator
{
int add(int x,int y)
{
return (x + y);
}
float add(float x,int y)
{
return (x + y);
}
float add(float x,float y)
{
return (x + y);
}
float add(float y,float x, float z)
{
return (x + y +z);
}
}
class overloadDemo {
public static void main(String args[])
{
int i;
float j, k;
Calculator calcobj = new Calculator();
i = calcobj.add (2,2);
System.out.println (i);
j = calcobj.add (2.1f,3.1f);
System.out.println (j);
k = calcobj.add (5, 5.5f);
System.out.println (k);
k = calcobj.add (6.6f, 7.7f ,8.8f);
System.out.println (k);
}}
Overloading Constructors
Like overloaded methods, we can also have overloaded constructors. It means more than one
constructor within a class definition having different signature.
class Addition
{
int x;
int y;
Addition
{
x=0;
y=0;
}
Addition (int a)
{
x=a;
y=0;
}
Addition (int a, int b) // Two argument constructor
{
x=a;
y=b;
}
void display ()
{
System.out.println("Values of x and y are : " +
x + " " + y);
}
}
class overloadedConstructorDemo {
public static void main(String args[])
{
Addition obj1=new Addition ();
obj1.display ();
Addition obj2=new Addition (10);
obj2.display ();
Addition obj3=new Addition (10,20);
obj3.display ();
}
}
The output of the above program is as follows:
Values of x and y are: 0 0
Values of x and y are: 10 0
Values of x and y are: 10 20
Exercise
a=10;
b=20;
}
void sum()
{
System.out.println("The result will be ="+(a+b));
}
}
public class cons1
{
public static void main(String args[])
{
add a1=new add();
a1.sum();
}
}
class add
{
int a,b;
a=a1;
b=b1;
}
void sum()
{
class cons2
{
public static void main(String args[])
{
add ae=new add(10,20);
ae.sum();
}
}
import java.io.*;
class swap
{
int a,b;
swap(int x,int y)
{
a=x;
b=y;
}
void method_swap()
{
int t=a;
a=b;
b=t;
}
void display()
{
System.out.println("The VALUE OF A IS:"+a);
System.out.println("The VALUE OF B IS:" +b);
}
}
class cons3
{
public static void main(String args[]) throws IOException
{
int u,v;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value for A:");
System.out.flush();
u=Integer.parseInt(br.readLine());
System.out.println("Enter the value for B:");
v=Integer.parseInt(br.readLine());
import java.io.*;
class teacher
{
String name;
String address;
int basic;
double da;
double hra;
double gross;
}
void display()
{
System.out.println("Employee name is:"+name);
System.out.println("Employee Address is:"+address);
System.out.println("--------------------------");
System.out.println("Basic Salary is:"+basic);
System.out.println("Dearness allowances:"+da);
System.out.println("House Rent allownaces is:"+hra);
System.out.println("The Gross salary is:"+gross);
hra=0.40*basic;
}
}
class cons4
{
public static void main(String args[]) throws IOException
String n,a;
int b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// Constructor Overloading
class add
{
int a,b,c;
add(int x, int y)
{
a=x;
b=y;
}
void sum()
{
System.out.println("The Sum is :="+(a+b+c));
}
}
class cons5
{
public static void main(String args[])
{
add aw=new add(12,12,10);
aw.sum();
add ae=new add(12,12,0);
ae.sum();
}
}
c1=new cu(5);
c2=new cu(7,5);
c3=new cu(7,5,2);
System.out.println("The volume of a cube is");
c1.display();
c2.display();
c3.display();
}
}
Inheritance :
Inheritance is the process of Creation of new class from an already
existing class.
Types of Inheritance :
1. Single
2. Multilevel
3. Hierarchical
4. Multiple
Class A
Class A Class A
Class B Class B
Class B Class C Class D
Class D
Class A Class B
Multilevel
Class C
Multiple Inheritance
But in Java does not support Multiple Inheritance , so use the new Technique for
implement Multiple Inheritance is called Interface.
Advantage of Inheritance :
1. Reusability of code.
2. Accessibility of Variables
3. Methods and functions derived from Parent Class.
class b extends a
{
int b, s=0;
void sum()
{
s=a+b;
b b1=new b();
b1.a=10;
b1.b=20;
b1.sum();
}}
// This is the Example of the multilevel Inheritance
class a
{
int a;
}
class b extends a // it inherit class a
{
int b;
}
class c extends b // it also inherit the class a, and b
{
int c;
int s=0;
void sum()
{
s=a+b+c;
System.out.println("The sum is :"+s);
class in2
{
public static void main(String args[])
{
c c1=new c();
c1.a=12;
c1.b=14;
c1.c=13;
c1.sum();
}}
// This is the example of Hierarchical Inheritance
class a
{
int a,b;
{
void sum()
{
System.out.println("The sum is :"+(a+b));
}
}
class c extends a
{
void multi()
{
System.out.println("The multiplication is :"+(a*b));
}
}
class d extends a
{
void sub()
{
System.out.println("The substraction is :"+(a-b));
}
}
class in3
{
public static void main(String args[])
{
b b1=new b();
b1.input_data(12,10);
b1.sum();
c c1=new c();
c1.input_data(1,12);
c1.multi();
d d1=new d();
d1.input_data(12,10);
d1.sub();
}}
class Base
{
int num;
}
class Child extends Base
{
int num;
Child (int x, int y)
{
super.num = x; //num of Base class
num = y;//num of Child class
}
void display ()
{
System.out.println ("Value of num in class Base is :
" +super.num);
System.out.println ("Value of num in class Child is :
" + num);
}
}
class testSuper {
public static void main (String args []) {
Child sub = new Child (10,70);
sub.display ();
}
}
Note :- In the above program, both the class Base and Child have an instance variable of the
same name (num). In such cases, num in class Child hides the instance variable num in class
Base. So, super is used to access the access the variable num in class Base.
Class Test1
{
int a;
int b;
Test1(int x, int y)
{
a=x;
b=y;
}
}
Class B extends Test1
{
Int c;
b(int x , int y, int p)
{
Super(x,y);
C=p;
}
Void sum()
{
System.out.println(“ The sum is “ +(a+b+c));
}
}
Class T1
{
Overriding
Overriding is a mechanism of creation of methods in the
subclasses with the same name and signature at that of the
parent or the super class. The datatype of the value returned
by both the overriding and the overridden methods must be the
same.
This is a significant difference between method overriding and
method overloading. In the latter case the overloaded methods
can differ in their return type. The new method declared in
the subclass hides the method of super class.
class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}
}
class Chair extends Furniture
{
void display( )
{
System.out.println (" This is a Chair");
}
}
class overrideDemo
{
public static void main (String args [])
{
Chair c = new Chair( );
c.display( ); // the display( ) method of class Chair is
called
}
}
Note : In the above example an object of Chair class is created. It will call the version of display ()
method present in the Chair class because the version of display ( ) inside Chair class overrides the display
() method defined inside the Furniture class. Thus, the output of the above program will be :
This is a Chair
In order to access the display () method of the Furniture class the keyword super
should
be used as illustrated below:
class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}}
class staticClass
{
static int ivar1 = 2;
static int ivar2 = 2 * 4;
static void display (int x)
{
ivar1 = ivar1 * x;
ivar2 = ivar1 + x;
System.out.println ("The values of ivar1 and ivar2 are :
" + ivar1 + " " + ivar2);
}
}
class staticDemo
{
public static void main (String args [])
{
staticClass.display (10);
}
}
In the above program, the method display () in the staticClass
has been declared as
static. Thus, we have used the name of the class (staticClass)
to invoke the method
display () without creating an instance of staticClass.
The output of the above program is :
The values of ivar1 and ivar2 are : 20 30
1. Final Class :
The classes are declared final in Java to ensure security.
Once a class is declared final, we cannot create a subclass
of that class. So we can not access the class using
Inheritance Property. We can prevent inherit from this
Final keyword.
Like as :
Final class A
{
Int a;
Class B extends A
{
} // It create Error Because A is Final so it can not Inherit by another Class.
2. Final Variable :
When a variable has been declared as final, it cannot be
modified. A final variable is similar to a const in C++. An
object reference variable declared as final cannot be
changed.
Final a=4;
3. Final methods:
Methods declared final cannot be overridden in a subclass.
When a final method is called, the Java compiler copies the
byte code for the subroutine directly to the compiled code of
the calling method, thus eliminating a costly method call.
Abstract Class
Abstract classes are created using abstract keyword. A class
is declared as abstract if it contains one or more abstract
methods. Abstract methods are those methods, whichhave only
method declaration but no method body. The syntax for
declaring an abstract method is as follows:
Example :
Abstract class A
{
Abstract void callme();
Void display()
{
System.out.println(“This is Display method”);
}}
Class B extends A
{
Void callme()
{
System.out.println(“This is derived from Parent class:”);
}
Class A1
{
public static void main(String args[])
{
A A1=new A();
A1.display();
A1.callme();
}
}
Example 2:
abstract class abs1
{
abstract public void add(int x, int y);
abstract public void sub(int a, int b);
public void disp()
{
System.out.println("This is te Abstract calss");
}
}
class abs2 extends abs1
{
int x;
int y;
public void add(int x, int y)
{
this.x=x;
this.y=y;
System.out.println(x+y);
}
public void sub(int a, int b)
{
x=a;
y=b;
System.out.println(x-y);
}
public static void main(String[] args)
{
abs2 ab=new abs2();
ab.add(10,20);
ab.sub(40,2);
ab.disp();
System.out.println("Hello World!");
}
}
Interfaces
Declaration of Interface :
Example:
Interface In
{
Static final int reg=1234;
Static final String n=”Jahiruddin Ahamed”;
Void display();
}
Class B implements In
{
Void display()
{
System.out.println(“The int value is :”=+reg);
System.out.println(“The String value is :”=+n);
}}
Class Me {
Public static void main(String args[])
{
B b1=new B();
B1.display();
}}
Another Example :
interface area
{
final static double pi = 3.14;
double calcArea (double x);
}
class circle implements area
{
public double calcArea (double x)
{
return (pi*x*x);
}
public static void main(String args[])
{
circle cr=new circle();
area ar;
ar=cr;
System.out.println("area of circle is" + ar.calcArea(2));
}}
Note :
Thus in our program we are declaring an object reference variable of type area
called ar.To this variable we are storing the reference to the object (cr) of
class circle. When the method area () is invoked using ar the area () method of
the object (whose reference is stored in cr) of class circle will be invoked.
interface ABC {
void method1();
void method2();
}
//XYZ interface extends ABC interface
interface XYZ {
void method3();
}
//class Myclass implements XYZ interface
class Myclass implements XYZ {
public void method1()
{
System.out.println("This is method 1 ");
}
public void method2()
{
System.out.println("This is method 2 ");
}
public void method3()
{
System.out.println("This is method 3 ");
}
}
class Mtest {
public static void main(String arg[])
{
Myclass obj = new Myclass();
obj.method1();
obj.method2();
obj.method3();
}
}
The output of the program is as follows:
This is method1
This is method2
This is method3.
Exception Handling
Runtime Error :
1. Division by zero.
2. Array index out of bounds.
3. Incompatible data types.
4. Passing wrong arguments to a method.
5. Negative index for array.
6. Converting non numeric string to number.
Java has a class that called Throwable class thatv deals with
exception and error.
> ClassNotFoundException
> IllegalAccessException
> InterruptedException
Some of the exception classes under RuntimeException class are:
ArithmeticException
> ArrayStoreException
> IllegalArgumentException
> IllegalMonitorStateException
> ArrayIndexOutOfBoundsException
There are two reserve words in java for deal with exception.
1. Try
2. Catch
try: - If any part of code is expected to give rise to an exception, it is put inside a try
block The statements that comprise the try block should be enclosed within curly braces.
A try block cannot comprise of a single statement. It is possible to develop nested try
blocks that is one try block can be placed inside another try block.
catch: The catch block comes after the try block and performs the actual error handling
functions. One try block may be associated with one or more catch blocks. All the corresponding
catch blocks for a try block should come after the try block.
Example :
Class myclass
{
Public static void main(String args[])
{
Int a=23;
Int b=0;
try
{
C=a/b;
}
Catch(Exception e)
{
System.out.println(“Zero divide error :”);
}}
}
In above program the try clause tells the compiler to try to
execute the code . But if it fails to execute then an
exception is generated and thrown which is caught by catch
clause.
Like as :
Class Test
{
Public static void ExceptionTest() throws ArithmaticException
{
Throw new ArithmeticException(“Demo”);
}
Public staic void main(String args[])
{
Try
{
ExcepTest();
}
Catch(ArithmaticException e)
{
System.out.println(e);
}}
Import java.io.*;
Class Test {
Public static void main(String args[]) throws IOException{
String s;
Buffereader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter your Name :”);
S=br.readLine();
System.out.println(“Your name is :”+s);
}
}
Finally :
Syntax :
Try {
Example:
Class exedemo
{
Public static void main(String args[])
{
Try
{
Int b=5,a=0;
C=b/a;
}catch(Exception e)
{
System.out.println(“arithmetic exception caught”);
}
finally
{
System.out.println(“ This is finally block”);
}
System.out.println(“Program completed:”);
}
}
APPLET
Applet is Small Java Programs that are integrated into webpage like HTML . For this
reasons applet is most important features of Java , Because Today Internet has an over
bearing presence in our day –to- day life.
Applets are powerful tools in Supporting client-side programming , a major issue for the
web.
Advantage of Applet :
1. There is no Installation Issue.
2. An Applet has true platform independence (including the ability to easily play audio file
nad many more ….)
3. Applets completely eliminate the fear of viruses.
4. It is integrated with HTML, so it is so simple for build.
Security Restrictions:
Applets Cannot…
Called once by the applet container when an applet is loaded for execution. This
method initializes an applet. Typical actions performed here are initializing fields,
creating GUI components, loading sounds to play, loading images to display (
Multimedia: Applets and Applications) and creating threads ( Multithreading).
public void start()
Called by the applet container after method init completes execution. In addition, if
the user browses to another Web site and later returns to the applet's HTML page,
method start is called again. The method performs any tasks that must be completed
when the applet is loaded for the first time and that must be performed every time the
applet's HTML page is revisited. Actions performed here might include starting an
animation or starting other threads of execution .
Called by the applet container after methods init and start. Method paint is also
called when the applet needs to be repainted. For example, if the user covers the applet
with another open window on the screen and later uncovers the applet, the paint
method is called. Typical actions performed here involve drawing with the Graphics
object g that is passed to the paint method by the applet container.
public void stop()
This method is called by the applet container when the user leaves the applet's Web
page by browsing to another Web page. Since it is possible that the user might return
to the Web page containing the applet, method stop performs tasks that might be
required to suspend the applet's execution, so that the applet does not use computer
processing time when it is not displayed on the screen. Typical actions performed here
would stop the execution of animations and threads.
public void destroy()
This method is called by the applet container when the applet is being removed from
memory. This occurs when the user exits the browsing session by closing all the
browser windows and may also occur at the browser's discretion when the user has
browsed to other Web pages. The method performs any tasks that are required to clean
up resources allocated to the applet.
Applet is not application program so it does not execute in console based interpreter .
we execute the java applets by using web browser like internet explorer or Netscape
Navigator or an Appletviewer. In java Applets always extends Applet class that is
defined in java.applet package . It has several methods to manipulate and the control
of the execution of Applet.
Java Applet package three parts :-
1. Applet Context
2. Audio Clip
3. Applet Stub
Also import all methods of awt(Abstract window Toolkit) class . It is used for load and
display image and load to play the audio clip. Etc. It also supports for Window based
Interface.
Now that we have created at least a skeleton let us learn how to compile and execute an
applet.
Compilation of an applet
The process that we follow for compiling an applet is the same that is required to compile
a Java application i.e
javac file_name.java
In the above syntax, file_name stands for the name of the Java source file. This name
should be the same as the name of the class that extends the Applet class.
Execution of an applet
We can execute an applet in the following two manner:
Executing the Applet within a Java-compatible Web browser, such as Netscape
Navigator or Internet Explorer. To execute an Applet in a Web browser, we need to
write a short HTML text file that contains the appropriate APPLET tag.
Using an applet viewer, such as standard JDK tool, appletviewer. This is the fastest
and easiest way to test the applet that we have created.
EMBEDDING AN APPLET :
The applet program is embedded in the web page by writing a short HTML code whose
syntax is shown below:
<Applet
codebase = codebaseURL
code = applet_name
alt = alternative text
width = w
height = h
alignment = a
vspace = v
hspace = h
>
<param name = parameter_name value = parameter_value>
</applet>
Let us now learn about the significance about each of the above attributes.
Internet Programming Using Core Java – Part 2
SR/JAVP2/301/1001/SC/3.0 13
The CODEBASE attribute of the applet tag is for specifying the path or the URL of
the applet program. This is needed if the applet does not exist in the same directory as
the web page. By default, the directory of the HTML file in which the applet is
embedded will be considered as the codebase. It is an optional attribute.
The CODE attribute specifies the name of the html file that embeds the .class file
that constitutes the applet. The browser will call this html file and then the applet will
then be interpreted and displayed in the browser.
Width and height attributes specify the area in pixels in which the applet is
displayed. The applet can be resized if it is being run it the appletviewer but in the
browser it cannot be resized.
The ALT attribute is an optional attribute that specifies a short text message that
should be displayed if the browser is not able to execute the Applet.
The ALIGN attribute is used to stipulate the alignment of the applet. This attribute
can take the following values:
• LEFT
• RIGHT
• TOP
• BOTTOM
• MIDDLE
• BASELINE
• TEXTTOP
• ABSMIDDLE
• ABSBOTTOM
The VSPACE and HSPACE attributes are optional and are specified in pixels.
VSPACE is used to arrange the space above and below the applet and HSPACE is
used to determine the spacing on both the sides of the applet.
THE <PARAM> TAG:
The applet can use run time values, which may be passed to it from the web page. To
pass parameter from the web page the PARAM tag is used. This parameter has two
attributes: (name : the name of the parameter. And value : the value of the parameter.
The syntax is as follows:
<applet code=appletname width=w height=h>
<param name = font value = “TimesRoman”>
<param name = size value=“28”>
</applet>
Thus for each parameter a single param tag is used.
First Example :
import java.awt.*; //Graphics Class which contains Paint()
import java.applet.*;
/*
<applet code = "sampleApplet" width = 300 height = 50>
</applet>
*/
public class sampleApplet extends Applet
{
public void init ()
{
setBackground (Color.cyan);
setForeground (Color.red);
}
public void paint (Graphics g)
{
g.drawString ("Welcome to the exciting world of Java
Applets", 20, 30);
showStatus ("Status Line Calling!!!");
}
}
Drawing Color :
• setColor, getColor
– Specifies the foreground color prior to drawing operation – By default, the graphics
object receives the foreground color of the window – AWT has 16 predefined colors
(Color.RED, Color.BLUE, etc.) or create your own color:
new Color(r, g, b)– Changing the color of the Graphics object affects only
the drawing that explicitly uses that Graphics object
• To make permanent changes, call the applet’s
setForeground method.
setFont, getFont
– Specifies the font to be used for drawing text – Determine the size of a character through
FontMetrics (in Java 2 use LineMetrics) – Setting the font for the Graphics object does not
persist to subsequent invocations of paint – Set the font of the window (I.e., call the applet’s
setFont method) for permanent changes to the font – Standard Java font names: Serif (e.g., Times
New Roman), SansSerif (e.g., Arial), Monospaced (e.g., Courier New), Dialog, and
DialogInput.
Draw a Image :
import java.applet.Applet;
import java.awt.*;
/** An applet that loads an image from a relative URL. */
public class JavaMan1 extends Applet {
private Image javaMan;
public void init() {
javaMan = getImage(getCodeBase(),"images/Java-Man.gif");
}
public void paint(Graphics g) {
g.drawImage(javaMan, 0, 0, this);
}
}
import java.awt.*;
import java.applet.*;
/*
<applet code=shapes height=200 width=400>
</applet>*/
public class shapes extends Applet
{
public void paint (Graphics g)
{
g.drawLine(40,20,100,20); // line drawing
g.drawRect(40,70,60,40); //Rectangle
g.fillRect(140,60,70,40); //Filled Rectangle
g.drawRoundRect(240,60,70,40,10,20);
g.fillRoundRect(140,120,70,40, 10,20);
g.drawOval(210,105,70,40);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code= "AppFace" width=500 height=400>
</applet> */
public class AppFace extends Applet
{
public void paint(Graphics g) {
//face
g.setColor(Color.orange);
g.fillOval( 90,40, 220,280);
//left eye
g.setColor(Color.black);
g.drawOval(120,120, 70,50);
//left eye ball
g.fillOval(150,135, 20,20);
//left eye brow
g.drawArc(110,100,80,20,0,160);
//right eye
g.drawOval(215,120, 70,50);
//right eye ball
g.fillOval(245,135, 20,20); //for right Eye Ball
g.drawArc(215,100,80,20,20,180);
g.drawOval( 195,140,20,70); //noise
//mouth
g.setColor(Color.red);
g.fillArc( 150,190,100,70,0,-180);
g.setColor(Color.orange);
g.fillArc( 150,200,100,50,0,-180);
}}
Add components
Components are stored as classes inside the java.awt package. Now if we want to place
them inside the window, we have to create the instance of the component object first,
then that object must be added to the window. To do this, we use the add(CompObj)
method.
Here is the syntax:
add(obj1);
Where obj1 is the component object.
Add components
Components are stored as classes inside the java.awt package. Now if we want to place
them inside the window, we have to create the instance of the component object first,
then that object must be added to the window. To do this, we use the add(CompObj)
method.
Here is the syntax:
add(obj1);
Where obj1 is the component object.
Types of Components
Labels
The Label control is used to display text inside the window. It is a passive control, means
it never responds to the user interaction.
The constructors are:
Label() :- Constructs a empty label
Label(String) :- Constructs a label with the string specified and left justified.
Label(String, int) :- Constructs a label with the string specified and int represents
the alignment. The alignment can be LEFT, CENTER and RIGHT.
Buttons
Button object is used to create a push button, which will respond whenever the user will
press it.
The constructors are:
Button() :- Creates a button with no label
Button(String) :- Creates a button with the label specified in the string
You can create the button object by calling its constructor. Here we are creating a Button
with a Caption “OK”.
Button b1=new Button(“OK”);
Where b1 is the object variable to this Button object. Once the object is created, add it to
the window.
Checkbox
Checkbox is a component that can be in either an "on" or "off" state. Clicking on a
checkbox changes its state from "on" to "off," or from "off" to "on."
Radio Buttons
There is no special class known as Readio Button, but you can get the functionality of the
Radio Button by manipulating the Checkbox class. For that, first you have to create a
CheckboxGroup object. Once it is created, then that object will be used in a special
constructor of the Checkbox.
That constructor is:
Checkbox(String str, boolean value, CheckboxGroup cbg);
Checkboxes present under a common CheckboxGroup behave like Radio Buttons, only
one option can be selected within a sigle CheckboxGroup.
Here how it works:
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox(“One”,true,cbg);
Checkbox cb2=new Checkbox(“Two”,false,cbg);
TextField
TextField component is used to accept input from the user. However, it is applicable for
single line entry. While creating the object, you can specify the number of columns as a
parameter to the constructor. That does not mean, the input is restricted within that
number of characters only. You can enter characters more than the number of columns
specified, only that many numbers of characters will be visible at a time.
The constructors are:
TextField() :- Creates a new textfield
TextField(int) :- Creates a new empty textfield with the specified length
TextField(String) :- Creates a new textfield initialized with the string value
TextField(String int) :- Creates a new textfield initialized with the string value and
the maximum length it can hold.
If you want to use the TextField to accept the password from the user, then you can use
the setEchoChar() method.
Choice Control
Choice control is used to make a drop down list. While using the choice control only the
instantiation of this class is not enough, you have to add different elements to this control.
The constructor is:
Choice() :- Creates a new choice control
Some of the methods available in this class are:
Example :
First create a Choice control in this way:
Choice ch=new Choice();
Then call the addItem() method on this object. Here is the example:
ch.addItem(“Sunflower”);
ch.addItem(“Lily”);
ch.addItem(“Rose”);
ch.addItem(“Tulip”);
Now suppose you want to access the element, which is selected. For that you have a
getSelectedItem() present in the Choice control. This method returns the String associated
with the currently selected object.
Example :
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test2 height=400 width=400>
</Applet>
*/
public class Test2 extends Applet{
Label l,l1;
}
public void start(){
add(l);
add(l1);
}
}
Ex2 :
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test3 height=400 width=250>
</Applet>
*/
public class Test3 extends Applet{
Label l,l1;
TextField t1,t2;
Button b1,b2;
}
public void start(){
add(l);
add(t1);
add(l1);
add(t2);
add(b1);
add(b2);
}}
Ex3 : This Program for Applet & Action Listener.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test4 height=400 width=250>
</Applet>
*/
public class Test4 extends Applet implements ActionListener{
Label l,l1,l2,l3;
TextField t1,t2,t3;
Button b1,b2;
TextArea ta;
Choice ch;
setFont(new Font("SansSerif",Font.BOLD,12));
t2.setEchoChar('*');
l2=new Label("Address:-");ta=new TextArea("",10,20);
l3=new Label("Region");
ch=new Choice();
ch.addItem("East");
ch.addItem("West");
ch.addItem("North");
ch.addItem("South");
b1=new Button("Submit");
b2=new Button("Cancel");
t3=new TextField(20);
}
public void start(){
add(l);
add(t1);
add(l1);
add(t2);
add(l2);
add(ta);
add(l3);
add(ch);
add(t3);
add(b1);
add(b2);
add(t3);
b1.addActionListener(this);
b2.addActionListener(this);
}
}
else
{
t3.setText("Access Denied:");
}
}}