Friday, 10 October 2025

Applets in Java

Introduction to Applets

 

Applets are small applications that are 

  • accessed on an Internet server,
  •  transported over the Internet, 
  • Automatically installed, 
  • and run as part of a web document
An applet is a Java program that runs in a Web browser. They can be executed by browsers on multiple platforms like Windows, Linux, and Mac. They can be executed by browsers on various platforms, including Windows, Linux, and macOS.

Java can be used to create two types of programs: applications and applets. 




Applet

Application

It is initialised through init()

Starts its execution through the main() method

It is a small program that uses another application (browser) program for its execution.

An application is a program executed on a computer independently.

Cannot run independently, requires API's

Can run alone but requires JRE.

Prior installation is not needed. Browsers with an applet plug-in are enough.

Requires prior explicit installation on the local computer.

The files cannot be read or written on the local computer through the applet.

Applications are capable of performing those operations on the files on the local computer.

Requires security for the system as the applets are untrusted.

No security concerns exist.

Created by extending the Applet class

User-defined class with main()

Uses a GUI interface to interact with users

Uses I/O stream classes


Sample Applet Program
import java. awt.*;
import java.applet.*;
public class MyApplet extends Applet 
{
     public void paint(Graphics g)
     {
             g.drawString("Hello World!", 20, 20);
     }
}

/*<applet code="MyApplet" height="300" width="500">
</applet>*/

There are two ways to run an applet:
  •  Executing the applet within a Java-compatible Web browser, such as Netscape Navigator.
  • Using an applet viewer, such as the standard JDK tool, appletviewer

An appletviewer executes the applet in a window. This is generally the fastest and easiest way to test an applet.

To execute an applet in a Web browser, it is essential to write a short HTML text file that contains the appropriate APPLET tag
<applet code="SimpleApplet" width=200 height=60>
</applet>
This tag can also be embedded within a Java file inside a comment line.

 Applet begins with two import statements. 

The first imports the Abstract Window Toolkit (AWT) classes. 

The second import statement imports the applet package, which contains the class Applet

Every AWT-based applet must be a subclass (either directly or indirectly) of Applet.

The class SimpleApplet must be declared as public, because it will be accessed by code that is outside the program.

Life Cycle of an Applet
An applet's life cycle includes the following methods
  • init( )
  • start( )
  • paint( )
  • stop( )
  • destroy( )
When an applet begins, the AWT calls the following methods, in this sequence:
  • init( )
  • start( )
  • paint( )
When an applet is terminated, the following sequence of method calls takes place:
  • stop( )
  • destroy( )
init() and start() methods
The init( ) method is the first method to be called.
This is where the variables are initialised. 
init( ) is called once—the first time an applet is loaded

The start( ) method is called after init( ). 
start( ) is called each time an applet's HTML document is displayed on screen. 
So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint() method
The paint( ) method is called each time the applet's output must be redrawn.  
paint( ) is also called when the applet begins execution.
The paint( ) method has one parameter of type Graphics. 
This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. 
This context is used whenever output to the applet is required.

stop() and destroy()
The stop( ) method is called when a web browser leaves the HTML document containing the applet.
 Applet uses stop( ) to suspend threads that don't need to run when the applet is not visible. 

The destroy( ) method is called when the environment determines that the applet needs to be removed from memory. 
The stop( ) method is always called before destroy( ).

repaint() and update()
The paint () method is called automatically by the browser whenever the applet window needs to be redrawn.
The user can call the repaint() method whenever the applet window needs to be redrawn.
The repaint () method will call the update () method of the Component class, which clears the window with the background colour of the applet and then calls the paint () method.

Types of Applets
Applets are of two types
Simple applets can be created by extending Applet class
These applets use the Abstract Window Toolkit (AWT) to provide the graphical user interface.
This style of applet has been available since Java was first created. 
JApplets can be created by extending JApplet class of javax.swing package

Simple display methods in Applets
void drawString(String message, int x, int y);  //To display text on the applet window

void setBackground(Color newColor)            //To set the background colour of the applet window     
void setForeground(Color newColor)   //To set colour to the text and other components on the applet

setBackground(Color.green);
setForeground(Color.red);

An applet can also output a message to the status window of the browser or applet viewer on which it is running.
To do so, call showStatus( ) with the string to be displayed.

The HTML APPLET tag
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]

Document Base – Filename from where the Java file containing the applet tag is loaded
Code Base – directory where the applet class file resides

Passing parameters to Applets
Parameters specify extra information that can be passed to an applet from the HTML page. 
Parameters are specified using the HTML’s param tag.
The < APPLET> tag in HTML is used to pass parameters to an applet. 

The <param> tag is a subtag of the <applet> tag. 
The <param> tag contains two 
attributes: name and value 
which are used to specify the name of the parameter and its value, respectively.

For example, the param tags for passing name and age parameters 
<param name=”name” value=”Ramesh” />
<param name=”age” value=”25″ /> 

The getParameter() method of the Applet class can be used to retrieve the parameters passed from the HTML page. 
The syntax of the getParameter() method is as follows:
 
                      String getParameter(String param-name)

Program using the param tag
import java. awt.*;
import java.applet.*;
public class MyApplet extends Applet 
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
    public void paint(Graphics g)
    {
   g.drawString("Name is: " + n, 20, 20);
   g.drawString("Age is: " + a, 20, 40);
   }
}

/*
<applet code="MyApplet" height="300"  width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/

Graphics belongs to a package named java. awt

import java.awt.Graphics;

To use Graphics,  the above line must be placed at the very top of the applet program, before the public class header.


Each (x, y) position is a pixel  ("picture element").

Position (0, 0) is at the window's top-left corner.
x increases rightward and y increases downward.

The rectangle from (0, 0) to (200, 100) looks like this:

 

Method name

Description

g.drawLine(x1, y1, x2, y2);

line between points (x1, y1), (x2, y2)

g.drawOval(x, y, width, height);

Outline the largest oval that fits in a box of size width * height, with top-left at (x, y)

g.drawRect(x, y, width, height);

outline of a rectangle of size
width * height with top-left at (x, y)

g.drawString(text, x, y);

text with bottom-left at (x, y)

g.fillOval(x, y, width, height);

fill the largest oval that fits in a box of size width * height with top-left at (x, y)

g.fillRect(x, y, width, height);

fill rectangle of size width * height with top-left at (x, y)

g.setColor(Color);

Set Graphics to paint any following shapes in the given colour



          


      




Wednesday, 1 October 2025

Inner Classes in Java

A class can be defined inside another class. Such classes are called nested classes.

The nested class is like a member of the enclosing class. The enclosing class cannot access the members of the nested class directly. But the nested class can access all the members of the enclosing class, including the private members. 

For example,  


In the above figure, class B is nested inside class A. Class B is a member of Class A and can access all its members directly. But class A cannot access the members of class B.

There are two types of nested classes:  static and non-static.

Static nested class

The static nested class is declared with a static modifier. It can access only the static members of the enclosing class. It does not have access to the non-static members of the outer class.

class Outer 
{
    static class Inner 
    {
        public static void display() 
        {
            System.out.println("inside inner class Method");
        }
    }
}
public class Main 
{
    public static void main(String[] args) 
    {
        Outer.Inner.display();
    }
}

Non-static nested class / Inner class

An inner class is a non-static nested class. It can access all the variables and methods of the outer class, including the private members, directly. Members of the inner class are known only within the scope of the inner class and may not be used by the outer class.

// Demonstrate an inner class. 
class Outer 
  int outer_x = 100; 
  void test() 
  { 
    Inner inner = new Inner(); 
    inner.display(); 
  } 
  // this is an inner class 
   class Inner 
   { 
        void display() 
        { 
                    System.out.println("display: outer_x = " + outer_x); 
        } 
    } 
class InnerClassDemo 
  public static void main(String[] args) 
  { 
    Outer outer = new Outer(); 
    outer.test(); 
  } 
}
 
Advantages of Inner Class

Encapsulation: Inner classes can access private members of the outer class, improving encapsulation.

Code Organisation: They group related logic, making the code more modular and easier to maintain.

Polymorphism: Inner classes can implement polymorphic behavior by extending or implementing different classes/interfaces.

Callbacks: Useful for event-driven programming, such as defining callback functions.

Inner classes are a powerful feature in Java, enabling better design and modularity in object-oriented programming.


Friday, 29 August 2025

Steps to create Packages in Java

 

Here are the steps to create a package in Java:


1. Define the Package

  • Use the package keyword at the very top of the Java file.
  • Example:
    package mypackage;
    

2. Organize Your Files

  • Create a sub directory in the current directory with a name that matches the package name.
  • For example, if your package is mypackage, create a folder named mypackage.

3. Write Your Java Class

  • Save your Java file inside the corresponding folder.
  • Example:
    package mypackage;
    
    public class MyClass {
        public void displayMessage() {
            System.out.println("Hello from MyClass in mypackage!");
        }
    }
    

4. Compile the Package

  • After saving the file, move to the parent directory by entering cd.. at the command prompt.
  • Navigate to the parent directory of the package folder in the terminal/command prompt.
  • Use the javac command to compile the file:
    javac mypackage/MyClass.java
    

5. Use the Package

  • To use the package in another Java file, import it using the import statement.
  • Example:
    import mypackage.MyClass;
    
    public class Main {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.displayMessage();
        }
    }
    

Benefits of Using Packages

  • Organizes your code.
  • Avoids naming conflicts.
  • Provides access control.

Let me know if you'd like further clarification! 😊