INDEX
List of practical
[Link] Particular Date Sign
1. Write a program to display prime number in java.
2. Write a program to display factorial.
3. Write a program to count the total number of characters in a string.
4. write a program to copy all elements of one array into another
5. Write a program to create a class called vehicle with a method called
drive(). Create a subclass called car that overrides the driven() method to
print "repairing a car".
6. Write a program to create a user defined package.
7. Write a program that throws an expect and catch it using a try catch.
8. Write a program to create and start multiple threads that increment a
shared counter variable concurrently.
9. Write a program to create applet in java.
10. Write a program to create shape and fill color in shape using Applet.
11. Write a program to create a buttons, canvas, checkbox, radio, buttons
using AWT controls.
12. Write a program to compare a given string to the specified character
sequence.
13. Write a program to print the result of removing duplicates from a given
string.
14. Write a java program for handling mouse events and key events.
15. Write a java program that connects to a database using JDBC.
16. Write a java program to connect to a database using JDBC and insert
values into it.
17. Write a java program to connect to a database using JDBC and delete
values from it.
18. Write a java servlet program to handle user form.
19. Write a java servlet application to print the current date and time.
20. Write a java servlet application to demonstrate the session tracking in
servlet.
21. Write a java servlet program to select the record from the database.
22. Write a JSP application to demonstrate the mathematical operation.
1. Write a program to display Prime Number.
public class Prime{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;
m=n/2;
if(n==0||n==1){
[Link](n+" is not prime number");
} else{
for(i=2;i<=m;i++){
if(n%i==0){
[Link](n+" is not prime number");
flag=1;
break;
} }
if(flag==0) { [Link](n+" is prime number"); }
} } }
OUTPUT
1
2. Write a program to display factorial.
public class Factorial {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
factorial *= i;
}
[Link]("Factorial of %d = %d", num, factorial);
} }
OUTPUT
2
3. Write a program to count the total number of
characters in a string.
public class CountCharacter
{
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;
for(int i = 0; i < [Link](); i++) {
if([Link](i) != ' ')
count++;
}
[Link]("Total number of characters in a string: " +
count);
} }
OUTPUT
3
4. Write a program to copy all elements of one array into
another array.
public class CopyArray {
public static void main(String[] args) {
int [] arr1 = new int [] {1, 2, 3, 4, 5};
int arr2[] = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
arr2[i] = arr1[i];
}
[Link]("Elements of original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr1[i] + " ");
}
[Link]();
[Link]("Elements of new array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr2[i] + " ");
}
} }
OUTPUT
4
5. Write a program to create a class called vehicle with a
method called drive(). Create a subclass called car that
overrides the drive() method to print “Repairing a car”.
class Vehicle {
public void drive() {
[Link]("Repairing a vehicle");
}
}
class Car extends Vehicle {
@Override
public void drive() {
[Link]("Repairing a car");
} }
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
[Link]();
[Link]();
}}
OUTPUT
5
6. Write a program to create a user defined package.
package MyPackage;
public class Compare {
int num1, num2;
Compare(int n, int m) {
num1 = n;
num2 = m; }
public void getmax(){
if ( num1 > num2 ) {
[Link]("Maximum value of two numbers is " + num1); }
else {
[Link]("Maximum value of two numbers is " + num2); } }
public static void main(String args[]) {
Compare current[] = new Compare[3];
current[1] = new Compare(5, 10);
current[2] = new Compare(123, 120);
for(int i=1; i < 3 ; i++)
{ current[i].getmax(); } }}
OUTPUT
6
7. Write a program that throws an expection and catch it
using a try catch.
public class ExceptionExample {
public static void main(String[] args) {
try {
throwException();
} catch (Exception e) {
[Link]("Caught an exception: " + [Link]());
[Link]();
} }
private static void throwException() throws Exception {
throw new Exception("This is a custom exception message.");
} }
OUTPUT
7
8. Write a program to create and start multiple threads
that increment a shared counter variable concurrently.
public class Counter {
private int count = 0;
public synchronized void increment() {
count++; }
public int getCount() {
return count; } }
public class Counter {
private int count = 0;
public synchronized void increment() {
count++; }
public int getCount() {
return count;
}}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
int numThreads = 6;
int incrementsPerThread = 10000;
IncrementThread[] threads = new IncrementThread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new IncrementThread(counter, incrementsPerThread);
threads[i].start(); }
try {
8
for (IncrementThread thread: threads) {
[Link]();
}}
catch (InterruptedException e) {
[Link](); }
[Link]("Final count: " + [Link]());
}}
OUTPUT
9
9. Write a program to create applet in java.
import [Link];
import [Link];
public class SimpleApplet extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
[Link]("Hello, this is a simple Java applet!", 20, 20);
}}
<html>
<body>
<applet code="[Link]" width="300" height="200"></applet>
</body>
</html>
OUTPUT
10
10. Write a program to create shape and fill color in
shape using Applet
import [Link].*;
import [Link].*;
public class Shapes extends Applet
{
public void init()
{
setBackground([Link]);
}
public void paint(Graphics g)
{
[Link]([Link]);
[Link]("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
[Link](x,y,4);
[Link]([Link]);
[Link](x,y,4);
[Link]([Link]);
[Link]("Pentagon",225,200);
x=new int[]{200,250,300,300,250,200};
y=new int[]{100,50,100,150,150,100};
[Link](x,y,6);
[Link]([Link]);
[Link](x,y,6);
[Link]([Link]);
[Link]("Circle",400,200);
[Link](350,50,125,125);
[Link]([Link]);
[Link](350,50,125,125);
[Link]([Link]);
[Link]("Oval",100,380);
[Link](50,250,150,100);
[Link]([Link]);
11
[Link](50,250,150,100);
[Link]([Link]);
[Link]("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
[Link](x,y,4);
[Link]([Link]);
[Link](x,y,4);
[Link]([Link]);
[Link]("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
[Link](x,y,3);
[Link]([Link]);
[Link](x,y,3);
}
}
OUTPUT
12
11. Write a program to create a buttons, canvas, radio
checkbox, buttons using AWT controls.
import [Link].*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
[Link](100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
13
12. Write a program to compare a given string to the
specified character sequence.
public class StringComparison {
public static void main(String[] args)
{
String inputString = "Hello, World!";
String targetSequence = "Hello";
boolean result = compareStrings(inputString, targetSequence);
[Link]("Is the given string equal to the specified sequence? " +
result);
}
private static boolean compareStrings(String inputString, String
targetSequence) {
return [Link](targetSequence);
} }
OUTPUT
15
13. Write a program to print the result of removing
duplicates from a given string.
public class RemoveDuplicates
{ public static void main(String[] args)
{
String inputString = "programming";
[Link]("Original String: " + inputString);
String result = removeDuplicates(inputString);
[Link]("String after removing duplicates: " + result);
}
private static String removeDuplicates(String input)
{ StringBuilder result = new StringBuilder();
boolean[] visited = new boolean[256]; // Assuming ASCII characters
for (int i = 0; i < [Link](); i++)
{
char currentChar = [Link](i);
if (!visited[currentChar])
{
[Link](currentChar);
visited[currentChar] = true;
}}
return [Link]();
}}
OUTPUT
16
14. Write a java program for handling mouse events and
key events.
import [Link].*;
import [Link].*;
import [Link].*;
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);
}
public void mouseClicked(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = [Link]();
17
mouseY = [Link]();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = [Link]();
mouseY = [Link]();
msg = "Up";
repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = [Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}
public void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
} }
OUTPUT
18
15. Write a java program that connects to a database
using JDBC.
package [Link];
import [Link].*;
public class Sample_JDBC_Program {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
String QUERY = "select * from employee_details";
[Link]("[Link]");
try(Connection conn =
[Link]("jdbc:oracle:thin:system/pass123@localhost
:1521:XE"))
{
Statement statemnt1 = [Link]();
ResultSet rs1 = [Link](QUERY);
{
while([Link]())
{
int empNum = [Link]("empNum");
String lastName = [Link]("lastName");
String firstName = [Link]("firstName");
String email = [Link]("email");
String deptNum = [Link]("deptNum");
String salary = [Link]("salary");
[Link](empNum + "," +lastName+ "," +firstName+","
+email +","+deptNum +"," +salary);
}
}
}
catch (SQLException e) {
[Link]();
}
} }
19
16. Write a java program to connect to a database using
JDBC and insert values into it.
import [Link];
import [Link];
import [Link];
public class Candidate {
public static int add(String firstName,String lastName,Date dob, String
email, String phone) {
int id = 0;
String sql = "INSERT INTO
candidates(first_name,last_name,dob,phone,email) VALUES(?,?,?,?,?)";
try (var conn = [Link]();
var stmt = [Link](sql,
Statement.RETURN_GENERATED_KEYS)) {
[Link](1, firstName);
[Link](2, lastName);
[Link](3, dob);
[Link](4, phone);
[Link](5, email);
int rowAffected = [Link]();
if(rowAffected == 1)
{ var rs = [Link]();
if([Link]()){
id = [Link](1); } }
} catch (SQLException e) {
[Link](); }
return id;
} }
OUTPUT
21
17. Write a java program to connect to a database using
JDBC and delete values from it.
import [Link];
import [Link];
import [Link];
public class JDBCTest {
public static void main(String args[]){
Connection conn = null;
Statement statement = null;
String query = "delete EMPLOYEE " +
"where EMPLOYEE_ID = 1 ";
try{
conn = [Link]();
statement = [Link]();
[Link](query);
[Link]();
[Link]();
[Link]("Record deleted successfully.");
}catch(Exception e){
[Link]();
}
}
}
OUTPUT
22
18. Write a java servlet program to handle user form.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LoginServlet extends HttpServlet
{
@Override
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
[Link]("text/html");
String username=[Link]("username");
String password=[Link]("password");
PrintWriter writer = [Link]();
String message="Username is : "+ username + "<br/> Password is :" +
password ;
[Link](message);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form name="logonform" action="LoginServlet" method="POST">
Username: <input type="text" name="username"/>
<br/>
23
Password:<input type="password" name="password"/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
OUTPUT
24
19. Write a java servlet application to print the current
date and time.
import [Link].*;
import [Link].*;
public class GFG {
public static void main(String args[])
SimpleDateFormat formatDate = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss z");
Date date = new Date();
[Link]([Link]("IST"));
[Link]([Link](date));
OUTPUT
25
20. Write a java servlet application to demonstrate the
session tracking in servlet.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class SessionDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
HttpSession session = [Link](true);
Date createTime = new Date([Link]());
Date lastAccessTime = new Date([Link]());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("Surendra");
if ([Link]())
{
title = "Welcome to my website";
[Link](userIDKey, userID);
}
else
{
visitCount = (Integer)[Link](visitCountKey);
visitCount = visitCount + 1;
userID = (String)[Link](userIDKey);
}
[Link](visitCountKey, visitCount);
[Link]("text/html");
26
PrintWriter out = [Link]();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
[Link](docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#e5f7c0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#eadf8c\">\n" +
"<th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + [Link]() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
27
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>SessionDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT
28
21. Write a java servlet program to select the record
from the database.
<%@ page import="[Link].*"%>
<%@ page import="[Link].*"%>
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<%!
Connection con;
PreparedStatement ps;
public void jspInit()
{
try
{
[Link]("[Link]");
con =
[Link]("jdbc:oracle:thin:@localhost:1521:XE",
"local", "test");
ps = [Link]("select * from Employees");
}
catch(Exception ex)
{
[Link]();
} }
%>
<%
ResultSet rs = [Link]();
[Link]("<table border=1 >");
[Link]("<tr style='background-color:#ffffb3; color:red'>");
[Link]("<th>Emp Id</th>");
[Link]("<th> Age(Year)</th>");
[Link]("<th>First Name</th>");
29
[Link]("<th>Last Name</th>");
[Link]("</tr>");
while([Link]())
{
[Link]("<tr style='background-color:#b3ffd9;'>");
[Link]("<td>"+[Link](1)+"</td>");
[Link]("<td>"+[Link](2)+"</td>");
[Link]("<td>"+[Link](3)+"</td>");
[Link]("<td>"+[Link](4)+"</td");
[Link]("</tr>");
}
[Link]("</table>");
[Link]();
%>
</body>
</html>
[Link]
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/[Link]</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT
30
22. Write a JSP application to demonstrate the
mathematical operation.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body style="background-color: lightblue">
<h2>Arithmetic Operations with EL !</h2>
<table border="2">
<thead>
<tr>
<th>Operation</th>
<th>EL Expression</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Digit</td>
<td>\${8}</td>
<td>${8}</td>
</tr>
<tr>
<td>Addition</td>
<td>\${4+4}</td>
<td>${4+4}</td>
</tr>
<tr>
<td>Addition</td>
<td>\${5.5+4.5}</td>
<td>${5.5+4.5}</td>
</tr>
31
<tr>
<td>Subtraction</td>
<td>\${15-5}</td>
<td>${15-5}</td>
</tr>
<tr>
<td>Division</td>
<td>\${20/4}</td>
<td>${20/4}</td>
</tr>
<tr>
<td>Multiplication</td>
<td>\${2*4}</td>
<td>${2*4}</td>
</tr>
<tr>
<td>Modulus</td>
<td>\${21%4}</td>
<td>${21%4}</td>
</tr>
</tbody>
</table>
</body>
</html>
OUTPUT
32