19. Marching Towards Java – Object-Oriented Programming with ANSI and Turbo C++

19

CHAPTER

Marching Towards JAVA

C
H
A
P
T
E
R

O
U
T
L
I
N
E
—•  19.1 Evolution of Java
—•  19.2 Java Technology
—•  19.3 Features of Java
—•  19.4 Overview of Java
—•  19.5 Differences Between C/C++ and Java
—•  19.6 Keywords
—•  19.7 Java Virtual Machine (JVM)
—•  19.8 Structure of a Java Program
—•  19.9 Implementing a Java Program
—•19.10 Constants, Variables and Data Types
—•19.11 Classes, Objects and Methods
—•19.12 Overriding Methods
—•19.13 Multithreading
—•19.14 Life Cycle of Thread
—•19.15 Packages
—•19.16 Applets

19.1 EVOLUTION OF JAVA

In January 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton, and several other experts met in Aspen, Colorado for the first time to discuss about a programming language, which was presented by Bill Joy. They wish to invent a better programming tool in the direction of Sun's “Stealth Project.”

The members of the Stealth Project were later recognized by another name “Green Project.” James Gosling's objectives were to modify and extend C++. This gave a better path for the progress of the project. Originally, the language was given the name “Oak,” which later on was renamed as “JAVA” in the year 1995. JAVA is a slang term for coffee. The first working version took about 18 months to develop.

Later many more helping hands were held together in the design and development of this project. Experts then speculated the name “JAVA” from some project members calls James Gosling, Arthur Van Hoff and Andy Bechtolsheim. At last, the day has come to implement the full version of Java, the vision of which was to develop “smart” consumer electronic devices that could be centrally controlled and programmed by a handheld remote control like device. It was expected to lead the humanity to a new era of modernization.

19.2 JAVA TECHNOLOGY

(1) Java Platform

A platform is a hardware or software background in which a program runs. The computers, nowadays, are interconnected by different networks worldwide and operate on many platforms. Among them are Microsoft Windows, Macintosh, OS/2, UNIX and NetWare. Software must be compiled separately to run on each platform, because they are specific to the same. The binary file for an application that runs on one platform cannot run on another platform because the binary file is platform-specific.

The Java platform is a software platform that delivers and runs highly interactive, dynamic, and secure applets and applications on networked computer systems, executing byte codes, which are not specific to any physical machine, but are machine instructions for a virtual machine. Files can run on any operating system that is running the Java platform. This portability is possible because at the core of the Java platform is the Java virtual machine.

The Java platform has two components:

• The Java Virtual Machine (Java VM)

• The Java Application Programming Interface (Java API)

(2) Java and Internet

Hot Java is a web browser that runs applets on Internet. Hence, Java is strongly connected with the Internet. Now users can easily compile applet programs in the Internet and run them locally by using a web browser like “ Hot Java.” They can even use this Web browser to download an applet located in a remote computer anywhere in the Internet in the world and run the application in their computer using the browser. Another important application is that Internet users can also set up their Web sites containing java applets that could be used by other remote users of Internet. This ability of Java has made it popular in the world.

(3) Java and World Wide Web

World Wide Web is used by the Internet's distributed environment. It contains information and controls about the Web pages. It is not like menu driven system. WWW is open through any direction. We can navigate any new part from any part. There is no restriction to follow the same path all the way every time. It is made possible with the help of a language called HTML. The HTML is Hypertext Markup Language. Web pages contain tags that enable us to find, retrieve, manipulate, and display documentation worldwide. Java is used in distributed environments such as Internet. Java is being easily imported into Web.

19.3 FEATURES OF JAVA

Java has the following important features:

(1) Compiled and interpreted

(2) Platform independent and portable

(3) Object-oriented

(4) Robust and secured

(5) Distributed

(6) Familiar, simple and small

(7) Multithreaded and interactive

(8) High performance

(9) Dynamic and extensible

(1) Java Environment

It includes large development tools, hundreds of classes and methods. Development tools are included in Java Development Kit (JDK). Classes and methods are parts of Java Standard Library (JSL).

(2) JDK

It has a collection of the following things which are used to develop and run Java programs:

(A) Applet viewer—enables to run Java applets

(B) Javac (compiler)—the Java compiler which translates Java source code to byte code so that interpreter can understand

(C) Java interpreter—which runs applets and applications by reading and interpreting byte codes

(D) Javap—Java disk assembler enables us to convert byte code file into discs

(E) JavaH—produces header files for use with native methods

(F) Javadoc—creates HTML format documentation from Java source code file

(G) Java debugger—helps to find errors

(H) Java disk assembler

(3) JSL

JSL includes hundreds of classes and methods divided into 6 major packages:

(A) Language support package—collection of classes and methods required for implementing basic facial appearance of Java

(B) Utility package—provides utility functions such as date and time

(C) Input / output package—required for input and output manipulations

(D) Net package—a collection of classes for communicating with other computers on network

(E) AWT package—abstract window toolkit contains classes that implement platform independent GUI

(F) Applet package—includes a set of classes that enables creating Java applets

19.4 OVERVIEW OF JAVA

Programmers can develop two types of Java programs:

(1) Stand Alone Applications

They are the programs written in Java to carry out certain task on stand-alone local computers. There are two steps:

(i) Compiling source code into byte code using Java compiler

(ii) Executing byte code using Java interpreter

(2) Web Applets

Applets are small Java programs from which we can develop simple animated graphics to complex games and utilities. We can also use Web enabled Java compatible browser like Internet explorer for running applets; if applet viewer is not available.

19.5 DIFFERENCES BETWEEN C/C++ AND JAVA

Java does differ from C/C++ in many ways. Java was modeled after these languages but it does not incorporate many features of them. We will discuss here few points of differences between Java and C/C++.

(1) Java and C

There is a major difference between Java and C. Java is an object-oriented language whereas C is procedural language. In an effort to build simple and safe language many complicated parts of C are discarded in Java which are given below:

• Java does not support the pointer type.

• Java does not hold the C data types like struct, union, and enum.

• Java does not have the C keywords like goto, sizeof, and typedef.

• Java does not have preprocessors like C, and hence we cannot use #define, #include, and #ifdef statements.

• Java does not support any mechanism for defining variable arguments to functions.

• Java has added some new operators such as instanceof and unsigned right-shift(>>>), conditional logical, etc.

• Java adds labelled break and continue statements.

• Java adds all the features required for object-oriented programming.

(2) Java and C++

While discussing the differences between Java and C++ we will have to be conscious because both of them are object-oriented programming languages. Hence, both of them incorporate the features of OOP's. Now, Java is a true object-oriented language while C++ and C an object-oriented extension. The differences are enlisted bleow:

• Java does not support operator overloading.

• Java does not make use of pointers like C++.

• There are no header files in Java.

• Java has replaced the destructor function with finalize( ) function.

• Java does not support generic programming.

• Java does not support multiple inheritance classes.

• A new feature is added called as interface.

• Java does not support global variables.

Table 19.1 Differences between C++ and JAVA

C++ Java
C++ uses functions Java uses methods
In C++, members are by default private In Java, methods are by default public
In C++, program is only compiled In Java, program is first compiled and then interpreted

19.6 KEYWORDS

Some reserved words are kept in Java while designing, which can be used for some specific tasks only. These are called as Java's keywords. Keywords can be used only for that task for which they are designed; they will give error if used for other purposes. We cannot use these keyword names for variables, classes, methods etc. Java language has reserved 60 words. All keywords are written in lowercase letters, as Java is a case sensitive language. The keywords are given in Table 19.2.

Table 19.2 Java keywords

19.7 JAVA VIRTUAL MACHINE (JVM)

All language compilers translate source code into machine code for specific computer. Java compiler produces an intermediate code known as byte code, for a machine that does not exist but is known as Java virtual machine. It only exists inside the computer memory. It is a simulated computer within the computer and does all the major functions of real computer. Virtual machine code is not an actual machine code. The machine specific code is generated by Java interpreter by acting as an intermediary between virtual machine and real machine.

19.8 STRUCTURE OF A JAVA PROGRAM

A java program contains one or more sections given below:

(1) Documentation Section (essential)

It comprises a set of comment lines giving the name of program, author, and other details. We can give comments by using // or /* */ or /** */ formats.

(2) Package Statements (optional)

It declares package name and informs the compiler that the classes defined in program belong to this package.

(3) Import Statements (optional)

This is similar to # include in C or C++.

(4) Interface Statements (optional)

An interface is like a class but includes a group of method declarations and used only when we are dealing with multiple inheritance concept in program implementation.

(5) Class Definitions (optional)

Java programs contain multiple class definitions.

(6) Main Method Class (essential)

It is the starting point of every standalone program.

19.9 IMPLEMENTING A JAVA PROGRAM

Implementation of Java application involves three steps:

(1) Creating a Program

At the command prompt give edit test.java and type the following code.

19.1 Write a simple Java program.

class test 
{
public static void main(String args[])
{
System.out.println("Hello"); 
}
}

OUTPUT
Hello

Explanation: In the above program, the statement System.out.println( ) displays the message “ Hello” on the screen. We save this file as test.java. The class name and file name should be the same. The Java program file should have extension.java. Java is case sensitive so wherever there is appearance of capital letter for any keyword then we must use that only and specify the name of the file according to class name.

(2) Compiling the Program

We must follow the given format to invoke Java compiler:
C:\javac test.java
After much complications, a class file is created. For example, after above compilation java.class file is created.

(3) Running the Program

We need to invoke here Java interpreter to run the program if there are no errors as given below:
C:\java test

Java is a pure OOP language, so everything should be placed in a class. The public static void main(String args[]) line defines method named main, which is the starting point for an interpreter to begin execution. In Java, there should be only one main function but can have multiple classes. The ‘public’ keyword is an access specifier, which declares main method as unprotected and therefore making it accessible to all other classes. The static keyword declares the method as one that belongs to entire class and not a part of any objects of class. The void keyword is a type modifier that states that main method will not return any value. The fifth line prints a message. The println is a member of out object that is static data member of System class.

19.10 CONSTANTS, VARIABLES AND DATA TYPES

Constants

Constants in Java refer to fix value that does not change during the execution of a program. Java supports several types of constants:

(a) integer

(b) real

(c) single character

(d) string

(e) back slash ‘\’ constants

Variables

A variable is an identifier that denotes a storage location used to store a data value. Variable names may consist of alphabets, digits, ‘_’, ‘$’ characters.

Data Types

Data types are broadly classified as primitive types called as intrinsic or built-in types and non-primitive types also known as derived types or reference types. Primitive data types may be numeric or non-numeric. The numeric data types are classified as integer and floating points. Non-numeric data types are classified as char and boolean. Non-primitive data types are classified as classes, interfaces, and arrays.

The data types determine the value and the operation that can be performed on the variable. For example, int var, defines variable var of type integer.

Java is a strongly typed language. This means every variable, expression has a type, and argument passing to the function is to check for type compatibility. The automatic type conversion is not allowed in Java as in other languages like C++.

In Java, there are two types of data types: primitive and reference.

A primitive type variable always contains only one value and its format is fixed. Examples of primitive type is a number, a character etc.

The following table shows all the primitive data types supported by the Java language.

Integer

In Java, there are four types of integer types. All the four integer data types will have signed, positive and negative values. But unsigned and positive-only integers are not supported by Java language. Table 19.3 shows the size and format of all the four integer data types.

Table 19.3 Table to show size and format of integer types.

Keywords Size Format
byte 8 bit Two's complement
short 16 bit Two's complement
int 32 bit Two's complement
long 64 bit Two's complement

byte The byte is smallest in all the integer data types.The size of byte type is 8-bit.So in byte the minimum value you can represent is –128 and the maximum value is 127.The variables are declared using the keyword byte. The declaration syntax for byte type variables is:
byte varl, var2,…,varn;
The following example declares byte variable:
byte a;

short It is a signed 16-bit quantity. So the range is from -32,768 to 32,767. The following example shows the declaration of short types:
short a;

int The int is the most commonly used integer data type. It is represented as a signed 32-bit integer type and has a range from -2,147,483,648 to 2,147,483,647. They are mostly used in control loops and in arrays to represent indexes.The following example shows the declaration of int type:
int a;

long The last integer type is long, which is a signed 64-bit type. The range is from -9,223, 372,036,854,775,808 to 9,223,372,036,854,775,807. It is used to hold very large values.

Real Numbers

Real numbers are also known as floating point numbers. They are mainly used to hold numbers containing fractional part. For example, in the number 245.54, .54 is a fractional part. The floating point types are two in number:

1. float

2. double

The float type are single-precision numbers whereas double type are double precision numbers. The floating point numbers are usually double precision numbers. If you want to represent a single precision number, you must append f or F to the number. For example,
2.3567f or 2.356F
Floating point types support one special value, which is known as Not-a-Number(NaN). It is used to represent the result of operations, where an actual number is not produced. For example, if you divide zero by zero, it will not produce any value.
The floating point types are discussed below:
float This is a single precision type and requires 32-bits for storage. It is required when a fractional component is needed. But it is not suitable to hold either very large or very small value. The following example shows the declaration of float variable:
float a;
double It is a double precision type and requires 64-bits for storage. Most of the mathematical functions, such as sin( ), cos( ) return double values.When you are evaluating very large numbers, double type is used. Table 19.4 gives the size and format of floating point types.

Table 19.4 Size and format of floating point types

Keyword Size Format
float 32 bit IEEE 754
double 64 bit IEEE 754

The following program shows the use of double type.

19.2 Write a program to show the use of double type.

class doubleType
class doubleType
 {
 public static void main(String args[])
  {
  double length=12.25;


  double breadth=25.24;


  double arearect=length* breadth;


  System.out.println("The value of length is :"+length+"cm");


  System.out.println("The value of breadth is :"+breadth+" cm");


  System.out.println("The area of rectangle is :"+arearect+" cm^2");
 }
}

OUTPUT
The value of length is :12.25cm
The value of breadth is :25.24 cm
The area of rectangle is :309.19 cm^2

Explanation: The above program calculates the area of rectangle. The variables length and breadth are defined as double. The value of area of rectangle is calculated and is displayed as double. If we define the variable area as int, then the fractional part of it is discarded, because int does not contain fractional part.

Character Type

In Java, to store character constants, character type called char is used. The char in Java requires two bytes for storage as compared to char in C/C++ which needs only one byte because Java uses unicode to represent characters. The range of char is from 0 to 65,536.There is no negative char. The following program shows the behaviour of character type of variables.

19.3 Write a program to demonstrate character type variables.

  class CharacterType
     {


public static void main(String args[])
       {
          char alphabet = ‘A’;
          System.out.print(alphabet);


          for (int  i=0; i<25; i++)
           {
           alphabet++;
     System.out.print("  "++alphabet); // Display alphabets
            if (i==10)


        System.out.println( );


      }
    }
}


OUTPUT
A B C D E F G H I J K L
M N O P Q R S T U V W X Y Z

Explanation: In the program CharacterType.java, variable alphabet is defined as char type and is initialized as A. Note that the character is represented within single quotes (‘ ‘). In for loop, the value of alphabet is incremented using ++ operator. The ++ operator is a unary operator since it is operated on single variable. The following program displays the ASCII value of character.

19.4 Write a program to demonstrate ASCII value of character.


  class CharValue
      {
         public static void main(String args[])
            {
             char charvalue=‘A’;


             int value=(int) charvalue;



System.out.println("The ASCII value of "+charvalue+"is: "+value);
             value++;
charvalue=(char)value;System.out.println("The ASCII value
"+value+" will have character: "+ charvalue);


            }
        }



OUTPUT
The ASCII value of Ais: 65
The ASCII value 66 will have character: B

Explanation: In the above program, CharValue displays the ASCII value of character variable. For example, in the above program variable is initialized as character A. Then its ASCII value is stored in the integer variable. When you assign the incompatible types, use typecasting.

Boolean type

Boolean type takes only one of two possible values; true or false.

It is used to test a particular condition and for performing logical operations. The keyword used to represent Boolean type is Boolean. The two values true and false have been declared as keyword in Java language. It uses only one bit for storage. Table 19.5 shows the size and format of character and Boolean types.

Table 19.5 Size and format of character and boolean types

Keyword Size Format
char 16 bit unicode
boolean 1 bit true/false

The following program BooleanTest explains the application of boolean type.

19.5 Write a program to demonstrate Boolean values.

   class BooleanTest
     {
       public static void main(String args[])
         {



           int a=3,b=5;
            System.out.println("The value of a="+a);


            System.out.println("The value of b="+b);


           if(a<b) // conditional statement


            System.out.println("The condition(a<b)is:"+(a<b));//
            print the result as true or false


           else


           if(a>b)


           System.out.println("The condition (a>b) is:"+(a>b));


          }
      }


OUTPUT

The value of a=3
The value of b=5
The condition (a<b)is : true

Explanation: The above program explains the application of Boolean values. The variables a and b are declared and initialized as int type. In the if statement, the values of variables a and b are compared. The result of if statement is either true or false. If the condition is satisfied then the result is Boolean value true and if the given condition is false, then the output of if statement is Boolean value false. In the above example, a=3 and b=5. Then the condition statement (a < b) is true and hence the output is Boolean value true, otherwise the result is Boolean value false.

19.6 Write a program to declare and initialize variables and display their values.

class program
class program
{
   public static void main(String args[])
{
int a,b;
a=-2,147,483,648;
b=2,147,483,648;
System.out.println("Value in a="+a);
System.out.println("\n Value in b="+b);
}
 }

OUTPUT:

Value of a=-2,147,483,648 Value of b=2,147,483,648

Explanation: In the above program, a and b are integer variables. They are initialized with integer values. Using system.out.println( ) they are displayed on the screen.

19.7 Write a program to declare and initialize integer variables. Also display the value of variable.

class num
{
   public static void main (String args[])
{
     int n;
     n=458;
    System.out.println("n="+n);


    n=n+5;
   System.out.println("Now n="+n);
}
}

OUTPUT
n=458
Now n=463

Explanation: In the above program, integer n is declared and initialized with 458. The value of n is displayed on the screen using System.out.println( ) function. 5 is added to variable n and new value is displayed.

19.11 CLASSES, OBJECTS AND METHODS

A class is a user-defined type which holds both data and methods. The internal data of a class are called as data members and the functions are called as member functions or methods. The variables of a class are called as objects. Class can be declared as:

   class classname [ extends superclass name ]
{
variable declarations;
method declarations;
}

Here, the keyword extends the properties of superclass to the classname class. This concept is known as inheritance.

Example

    class area
{
     double r;
}

The class area contains one member variable of double type.

Creating Objects

An object in Java is essentially a block of memory that contains space to store all instance variables. Objects in Java are created by using new operator.
classname objectname;
objectname=new classname( );
Example
area a;
a=new area( );
First statement declares a variable to hold the object reference and second actually assigns the object reference to the variable. Both the statements can also be combined in one sentence as
area a=new area(0);

19.8 Write a program to define class. Declare objects.

class  area
{
float r;
}



class classdemo
{
public static void main (String  args[])
{
double ar;
area a= new area( );
a.r=4;
ar=3.14*a.r*a.r;
System.out.println("Area : "+ar);
}
}

OUTPUT

Area: 50.24

Explanation: In the above program, class area is defined with member variable r. An object of class area is defined. Using object member variable, r is initialized to four and area is calculated and displayed.
Methods can be added as

        type methodname(parameter list)
{
method body;
}

19.9 Write a program to define method in a class and display the area.

class  area
{
    float r;


    void show( )


     {
        System.out.print("Area : ");
        System.out.println(3.14*r*r);
     }
}



class classdemo
{
   public static void main(String  args[])
  {
     area a= new area( );
     a.r=4;
     a.show( );
}
}

OUTPUT

Area: 50.24

Explanation: This program is same as the last one. Here, method show( ) is defined which displays the area. The method show( ) is invoked using object a.

19.12 OVERRIDING METHODS

There may be certain occasions when we want an object to respond to the same method but have different behaviour when that method is called. That means we should override methods in super class. This is possible by defining a method class that has same name, same argument and return type as a method of superclass. When that method is called, the method defined in subclass is invoked and executed instead of the one in superclass. This is known as overriding.

19.10 Write a program to overload a member function.

class overload
{


 void show( )
 {   System.out.println("Without parameters");  }




 void show( int x)
 {
   System.out.println("With one parameter");

   System.out.println(" x = "+x);
 }


}


class over
{
  public static void main ( String args[])
  {


   overload o= new overload( );
   o.show( );
   o.show(9);


  }


}

OUTPUT

Without parameters With one parameter

x = 9

Explanation: In the above program, the class overload contains two methods with same name. The show( ) method is overloaded with and without parameter. When a method show( ) is invoked without parameter, the function body without parameter is executed. When one integer is passed the function body with one parameter is executed.

19.13 MULTITHREADING

Multithreading is a conceptual programming paradigm where a program process is divided into two or more subprograms (processes) which can be implemented at the same time in parallel. For example, one subprogram displays animation while other one builds another animation. This is similar to dividing task into subtasks and assigning them to different processes for execution independently and simultaneously. Thread is similar to a program that has a single flow of control. It has a beginning, body, and an end, which execute commands sequentially. Our simple programs are single threaded programs. A program that contains multiple flows of control is known as multithreaded program.

Multithreading is a powerful programming tool and distinct from other programming languages. It enables a programmer multiple things at one time. Longer programs can be divided into threads and executed in parallel. For example, we can send task such as printing into the background and continue to perform some other task in foreground.

19.14 LIFE CYCLE OF THREAD

There are many states thread can enter during life time:

1. new thread state

2. runnable

3. running

4. blocked state (optional)

5. dead state

There are certain methods that are used to implement threads.
Threads are implemented in the form of objects that contain a method called as run( ) which is heart and soul of any thread. Whenever we want to start a thread we can use start( ) method. If we want to stop a thread from running further we may do so by calling stop( ) method. A thread can also be temporarily suspended or blocked as :

1. sleep( ) blocks for a specified time.

2. suspend( ) blocks until further orders.

3. wait( ) blocks until certain condition occurs.

19.11 Write a program to demonstrate multithreading.

Class A extends thread
{
public void run( )
{
for(i=1;i<=5;i++)
{
if(i==1)
yield( );
System.out.println("From thread A : i= "+i);
}
System.out.println("Exit from A");
}    }
Class B extends thread
{
public void run( )
{
for(j=1;j<=5;j++)
{
System.out.println("From thread A : j= "+j);
if(j= =3)
stop( );
}


System.out.println("Exit from B");
}     }
Class C extends thread
{
public void run( )
{
for(k=1;k<=5;k++)
{
System.out.println("From thread C : k= "+k);
if(k= =1)
try
{
sleep(1000);
}
catch(Exception e)    {     }
}
System.out.println("Exit from C");
}     }
class threadmethods
{
public static void main(String args[])
{
A threadA=new A( );
B threadB=new B( );
C threadC=new C( );
System.out.println("Start thread A");
threadA.start( );
System.out.println("Start thread B");
threadB.start( );
System.out.println("Start thread C");
threadC.start( );
System.out.println("End  of main thread");
}         }

OUTPUT:
Start thread A
Start thread B
Start thread C
From thread B : j=1
From thread B : j=2

From thread A : i=1

From thread A : i=2

End of main thread

From thread C : k=1

From thread B : j=3

From thread A : i=3

From thread A : i=4

From thread A : i=5

Exit from A

From thread C : k=2

From thread C : k=3

From thread C : k=4

From thread C : k=5

Exit from C

19.15 PACKAGES

To use classes from other programs without physically copying them into the program under development, can be accomplished in Java by using packages similar to class libraries in other languages. Packages are Java's way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact packages act as containers for classes. Packages provide a way to hide the classes, thus preventing other programs or packages from accessing classes that are meant for internal use only. Java packages are of two types:

1. Java system packages - Java system provides a large number of classes grouped into different packages according to functionality as:

(A) Java.lang – language support classes.

(B) Java.util – language utility classes.

(C) Java.io – input/output support classes.

(D) Java.awt – set of classes used to implement GUI.

(E) Java.net – classes for networking.

(F) Java.applet – classes for creating & implementing applets.

2. User defined packages—These are defined by users for their use.

19.16 APPLETS

Applets are small Java programs that are primarily used in Internet computing. They can be transported over Internet from one computer to another computer and run using applet viewer or any Java compatible Internet browser. It can perform arithmetic operations, display graphics, play sound, accept user input, create animation, and play interactive games.

(1) Local and Remote Applets :

We can embed applets into web pages in two ways:

Local We can write our own applet and embed them into web pages.

Remote We can download an applet from remote system and then embed it into web pages.

(2) Preparing to Write Applets :

Before we try to write applet we make sure that Java is properly installed and also have applet viewer / Java enabled browser. The steps are given below.

1. Building an applet code (.java file)

2. Creating an executable file (.class file)

3. Designing a web page using HTML tags

4. Preparing applet tag

5. Incorporating applet tag into web page

6. Creating HTML tag

7. Testing applet code

(3) Building Applet Code

It is essential that our applet code uses services of class namely graphics and applets from Java class library. Applet class contained in java.applet class provides life and behavior to the applet through its methods such as init( ), start( ), paint( ). The paint method displays result of applet code on the screen. Output may be text or sound. The paint( ) requires a graphic object as an argument defined as:

public void paint(Graphics g)

This requires the applet code import java.awt that contains graphics class. The general applet code format is given below.

    import java.awt.*;
import java.applet.*;
public class appletclassname extends Applet
{
public void paint(Graphics g)
{
}     }
the appletclassname through a main class for the applet.

19.12 Write a program to create an applet.

//Hello Java ! applet program
import java.awt.*;
import java.applet.*;
public class hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawstring("Hello Java !",10,100);


}      }

OUTPUT

The output will be Hello Java ! in the applet viewer.

We have to add applet tag for the execution of applet as :

   <APPLET
        CODE=hellojava.class
        WIDTH=400
        HEIGHT=400>
</APPLET>

SUMMARY

(1) A platform is a hardware or software environment in which a program runs. The computers, nowadays, are interconnected by different networks worldwide, and operate on many platforms, Microsoft Windows, Macintosh, OS/2, UNIX and NetWare.

(2) Hot Java is a web browser that runs applet on Internet. Hence, Java is strongly interconnected with the Internet.

(3) World Wide Web is designed for use by the Internet's distributed environment. It contains information and controls about the web pages. It is not like menu driven system. WWW is open through any direction.

(4) All language compilers translate source code into machine code for specific computers. Java compiler produces an intermediate code known as byte code for a machine that does not exist, and is known as Java virtual machine.

(5) Data types are broadly classified as: Primitive types called as intrinsic or built-in types and Non-primitive also known as derived types or reference types. Primitive data types may be numeric or non-numeric. The numeric data types are classified as integer and floating point. Non-numeric data types are classified as char and Boolean. Nonprimitive data types are classified as classes, interfaces, and arrays.

(6) Multithreading is a conceptual programming paradigm where a program process is divided into two or more subprograms (processes) which can be implemented at the same time in parallel.

(7) To use classes from other programs without physically copying them into the program under development, can be accomplished in Java by using packages similar to class libraries in other languages. Packages are Java's way of grouping a variety of classes and/or interfaces together.

(8) Applets are small Java programs that are primarily used in Internet computing. They can be transported over Internet from one computer to another computer and run using applet viewer or any Java compatible Internet browser.

EXERCISES

[A] Answer the following questions.

(1) Explain evolution of Java.

(2) Explain Java technology.

(3) Explain structure of Java program.

(4) What are static members and functions?

(5) What do you mean by overriding methods?

(6) Explain multithreading programming in Java.

(7) What are packages and applets?