1: Write a program to pass employ name and id number to an applet.
import java.applet.*;
import java.awt.*;
/* <applet code="MyApplet2.class" width = 600 height= 450>
<param name = "t1" value="Hari Prasad"> <param name =
"t2" value ="101">
</applet> */
public class MyApplet2 extends Applet
String n;
String id;
public void init()
n = getParameter("t1");
id = getParameter("t2");
public void paint(Graphics g)
rawString("Name is : "
+ n, 100,100);
g.drawString("Id is:
"+ id, 100,150);
}
Ex2: Write a program to pass two numbers and pass result to an applet.
import java.awt.*;
import java.applet.*;
/*<APPLET code="Pp" width="300"
height="250"> <PARAM name="a" value="5">
<PARAM name="b" value="5">
</APPLET>*/
public class Pp extends Applet
JAVA PROGRAMMING
String str;
int a,b,result;
public void init()
str=getParameter("a");
a=Integer.parseInt(str);
str=getParameter("b");
b=Integer.parseInt(str);
result=a+b;
str=String.valueOf(result);
public void paint(Graphics g)
g.drawString(" Result of Addition is : "+str,0,15);
}
Ex3: Hai.java
import java.applet.*;
import java.awt.*;
/*<Applet code="hai" height="250" width="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>
*/
class hai extends Applet
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message"); if
(inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 55);
Output:
Hai friend how are you…?
Event Handling
EX: // Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
mouseX = 0; // save coordinates
mouseY = 10;
msg
= "Mouse clicked.";
repaint(); }
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
// save
coordinates
mouseX
= 0;
mouseY = 10;
msg = "Mouse entered.";
repaint(); }
// Handle mouse exited.
public void mouseExited(MouseEvent me)
// save
coordinate s mouseX
= 0;
mouseY
10;
msg
= "Mouse exited.";
repaint();
// Handle button pressed.
public void mousePressed(MouseEvent me)
// save coordinates
mouseX =
me.getX();
mouseY =
me.getY(); msg =
"Down"; repaint();
// Handle button released.
public void mouseReleased(MouseEvent me)
1. save
coordinates
mouseX =
me.getX();
mouseY =
me.getY(); msg = "Up";
repaint();
Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
//save coordinates
mouseX = me.getX();
mouseY = me.getY();msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);repaint();
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
Output :-
Mouse clicked.
Moving mouse at 106, 70
Mouse clicked.
Moving mouse at 178, 199
Mouse clicked.
Moving mouse at 218, 107
EX: // Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SimpleKey" width=300height=100> </applet> */
public class SimpleKey extends Applet implements KeyListener
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
public void keyPressed(KeyEvent ke)
showStatus("Key Down");
public void keyReleased(KeyEvent ke) {showStatus("Key Up");
public void keyTyped(KeyEvent ke) {msg += ke.getKeyChar();
repaint();
// Display keystrokes.
public void paint(Graphics g)
g.drawString(msg, X, Y);
}
Output:-
ddddddddddddddddddddddd
Key Up
ddddddddddddddddddddddd
Key Down
Files and Streams
Example: Write a program to read data from the keyboard and
write it to myfile.txt file.
import java.io.*;
class Test{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputstream fout=new FileOutputStream("myfile.txt");
System.out.println("Entertext @ at the end:”);
char ch;
while((ch=(char)dis.read())!=‟@‟)
fout.write(ch);fout.close();
}
}
Output: javac Test.java
Java Test
Example: Write a program to read data from myfile.txt using
FileInputStream and display it on monitor.
import java.io.*;
class ReadFile
{
public static void main(String args[])
{
FileInputStream fin=new FileInputStream("myfile.txt");
System.out.println(“File Contents:”);
int ch;
while((ch=fin.read())!=-1)
{
System.out.println((char)ch);
}
fin.close();
}
}
Output: javac ReadFile.java
java ReadFile
Simple example of AWT by inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible
}
public static void main(String args[]){
First f=new First();
}
}
Simple example of AWT by association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Output:-
Click me
Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ButtonDemo" width=250 height=150>
</applet> */
public class ButtonDemo extends Applet implements
ActionListener
{
String msg = "";
Button yes, no, maybe;
public void init()
{
yes = new Button("Yes");no = new Button("No");
maybe = new Button("Undecided");add(yes);
add(no); add(maybe);
yes.addActionListener(this); no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str =
ae.getActionCommand();
if(str.equals("Yes"))
{
msg = "You pressed Yes.";
}
else if(str.equals("No"))
{
msg = "You pressed No.";
}
else
{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}
}
Output:-
Yes No Undecided
You pressed Yes.
Applet started
Servelet
1-Basic Java Servlet program that demonstrates handling an
HTTP request and generating a response. This example
outputs a "Hello, World!" message.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Define the servlet by extending HttpServlet
public class HelloServlet extends HttpServlet {
// Handles HTTP GET requests
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
// Get the output writer
PrintWriter out = response.getWriter();
// Write the response
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello, World!</h1>");
out.println("<p>This is a simple Java servlet example.</p>");
out.println("</body>");
out.println("</html>");
}
}
Compile the servlet using the servlet API library:
javac -cp <TOMCAT_LIB_PATH>/servlet-api.jar HelloServlet.java
Create a directory structure for your web application:
mywebapp/
├── WEB-INF/
├── classes/
│ ├── HelloServlet.class
└── web.xml
Place the compiled .class file in WEB-INF/classes.
Add the following web.xml file to configure the servlet:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
version="3.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Start your Tomcat server and deploy the mywebapp directory.
Output:
<html>
<head><title>Hello Servlet</title></head>
<body>
<h1>Hello, World!</h1>
<p>This is a simple Java servlet example.</p>
</body>
</html>
2 -Servlet to Display Current Date and Time
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
public class DateTimeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
// Get the output writer
PrintWriter out = response.getWriter();
// Generate current date and time
Date currentDate = new Date();
// Write the response
out.println("<html>");
out.println("<head><title>Current Date and
Time</title></head>");
out.println("<body>");
out.println("<h1>Current Date and Time</h1>");
out.println("<p>" + currentDate + "</p>");
out.println("</body>");
out.println("</html>");
}
}
Output-
<html>
<head><title>Current Date and Time</title></head>
<body>
<h1>Current Date and Time</h1>
<p>Wed Nov 21 15:45:30 IST 2024</p>
</body>
</html>
3. Servlet to Display Form Data
HTML form
Index.html
<form action="form-handler" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<button type="submit">Submit</button>
</form>
Servlet code
.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormHandlerServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
// Get form parameters
String name = request.getParameter("name");
String email = request.getParameter("email");
// Get the output writer
PrintWriter out = response.getWriter();
// Write the response
out.println("<html>");
out.println("<head><title>Form Data</title></head>");
out.println("<body>");
out.println("<h1>Form Data Received</h1>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Email: " + email + "</p>");
out.println("</body>");
out.println("</html>");
}
}
Output:-
After submitting the form with the name John Doe and email
[email protected], the response will be:
<html>
<head><title>Form Data</title></head>
<body>
<h1>Form Data Received</h1>
<p>Name: John Doe</p>
<p>Email: [email protected]</p>
</body>
</html>
File Upload Servlet
HTML
<form action="file-upload" method="post"
enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" id="file" name="file">
<br><br>
<button type="submit">Upload</button>
</form>
Servlet code
.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get the uploaded file part
Part filePart = request.getPart("file");
// Get file name
String fileName = filePart.getSubmittedFileName();
// Save the file to the server
String uploadPath = "C:/uploads"; // Replace with your upload
directory
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
filePart.write(uploadPath + File.separator + fileName);
// Write the response
out.println("<html>");
out.println("<head><title>File Upload</title></head>");
out.println("<body>");
out.println("<h1>File Uploaded Successfully</h1>");
out.println("<p>File Name: " + fileName + "</p>");
out.println("</body>");
out.println("</html>");
}
}
Output:-
<html>
<head><title>File Upload</title></head>
<body>
<h1>File Uploaded Successfully</h1>
<p>File Name: example.txt</p>
</body>
</html>
Servlet with Redirect
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Redirect to another website
response.sendRedirect("https://www.example.com");
}
}
Output;-
When you access the servlet, it redirects the browser to
https://www.example.com.
JDBC
1. JDBC Program to Fetch Data from a Database
Table
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
// JDBC URL, username, and password of MySQL
server
String url = "jdbc:mysql://localhost:3306/testdb"; //
Replace with your database URL
String user = "root"; // Replace with your database
username
String password = "password"; // Replace with your
database password
// SQL query
String query = "SELECT id, name, age FROM users";
// Load the JDBC driver and connect to the database
try (Connection connection =
DriverManager.getConnection(url, user, password);
Statement statement =
connection.createStatement();
ResultSet resultSet =
statement.executeQuery(query)) {
System.out.println("Connected to the database!");
// Process the result set
System.out.println("ID\tName\tAge");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println(id + "\t" + name + "\t" + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Steps to Run the Program
Create a MySQL database testdb (or another database of your
choice).
Create a users table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Insert some sample data
INSERT INTO users (name, age) VALUES ('Alice', 25), ('Bob', 30),
('Charlie', 35);
Add jdbc driver-
Download the MySQL JDBC driver from MySQL Connector/J.
Add the .jar file to your project’s classpath.
Compile the program:
javac -cp .:mysql-connector-java-8.0.34.jar JDBCExample.java
Run the program-
java -cp .:mysql-connector-java-8.0.34.jar JDBCExample
Output:-
Connected to the database!
ID Name Age
1 Alice 25
2 Bob 30
3 Charlie 35
2. JDBC Program to Insert Data
import java.sql.*;
public class JDBCInsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
String insertQuery = "INSERT INTO users (name, age)
VALUES (?, ?)";
try (Connection connection =
DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement =
connection.prepareStatement(insertQuery)) {
System.out.println("Connected to the database!");
// Set parameters and execute the query
preparedStatement.setString(1, "David");
preparedStatement.setInt(2, 40);
int rowsInserted =
preparedStatement.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output
If the program successfully inserts a new record into the
users table:
Connected to the database!
1 row(s) inserted!
3. JDBC Program to Update Data
import java.sql.*;
public class JDBCUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
String updateQuery = "UPDATE users SET age = ? WHERE
name = ?";
try (Connection connection =
DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement =
connection.prepareStatement(updateQuery)) {
System.out.println("Connected to the database!");
// Set parameters and execute the update
preparedStatement.setInt(1, 28);
preparedStatement.setString(2, "Alice");
int rowsUpdated = preparedStatement.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:-
If the age of Alice is updated:
Connected to the database!
1 row(s) updated!
4. JDBC Program to Delete Data
import java.sql.*;
public class JDBCDeleteExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
String deleteQuery = "DELETE FROM users WHERE name = ?";
try (Connection connection =
DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement =
connection.prepareStatement(deleteQuery)) {
System.out.println("Connected to the database!");
// Set parameters and execute the delete
preparedStatement.setString(1, "Charlie");
int rowsDeleted = preparedStatement.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:-
If the record for Charlie is deleted:
Connected to the database!
1 row(s) deleted!