Java Applications and Applets
1. Java Application
● A Java Application is a standalone program that runs directly on the Java Virtual
Machine (JVM).
It has a main method as its entry point:
public class MyApp {
public static void main(String[] args) {
System.out.println("This is a Java Application.");
}
}
●
● How to run:
1. Compile: javac MyApp.java
2. Execute: java MyApp
2. What Is a Java Applet?
● A Java Applet is a small program designed to be embedded in a web page and run
inside a browser.
● To run applet programs you need to first install JDK 8.
Applet Lifecycle
It extends the Applet (or JApplet) class and implements at least one of these lifecycle
methods:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 25);
}
}
●
● How to run in a browser:
1. Compile: javac HelloApplet.java
Write an HTML file:
<html>
<body>
<applet code="HelloApplet.class" width="200" height="50">
</applet>
</body>
</html>
2.
3. Open the HTML file in a (legacy) browser or applet viewer.
3. Key Differences
Aspect Java Application Java Applet
Execution environment JVM on desktop/server Browser or Applet Viewer
Entry point public static void init(), start(),
main(String[] args) paint(Graphics)
User interface support Swing, AWT, JavaFX, AWT (lightweight), restricted
console I/O Swing
Security restrictions Full access to file system, Sandbox model: restricted
network, etc. permissions
Distribution JAR, EXE, direct .class Embedded in web pages
files
4. Simple Examples
4.1 Application Example: Calculator
import java.util.Scanner;
public class SimpleCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = sc.nextInt(), b = sc.nextInt();
System.out.println("Sum = " + (a + b));
}
}
Output:
Enter two numbers: 5 7
Sum = 12
●
4.2 Applet Example: Click Counter
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ClickCounterApplet extends Applet implements MouseListener {
int count = 0;
public void init() {
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString("Click count: " + count, 20, 20);
}
public void mouseClicked(MouseEvent e) {
count++;
repaint();
}
// Unused methods:
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
HTML to embed:
<applet code="ClickCounterApplet.class" width="200" height="100"></applet>
●
5. When to Use Which?
● Applications
○ Complex GUIs (using Swing/JavaFX)
○ Console utilities, server programs, background services
● Applets
○ Interactive web content (legacy tech)
○ Simple animations or games inside a web page
Note: Modern browsers no longer support Java applets without plugins; Java Web Start or full
applications are now more common for web-distributed Java.