Java File
Java File
List of practical
OUTPUT
1
2. Write a program to display factorial.
OUTPUT
2
3. Write a program to count the total number of
characters in a string.
OUTPUT
3
4. Write a program to copy all elements of one array into
another array.
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() {
System.out.println("Repairing a vehicle");
}
}
class Car extends Vehicle {
@Override
public void drive() {
System.out.println("Repairing a car");
} }
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
vehicle.drive();
car.drive();
}}
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 ) {
System.out.println("Maximum value of two numbers is " + num1); }
else {
System.out.println("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.
OUTPUT
7
8. Write a program to create and start multiple threads
that increment a shared counter variable concurrently.
OUTPUT
9
9. Write a program to create applet in java.
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawString("Hello, this is a simple Java applet!", 20, 20);
}}
<html>
<body>
<applet code="SimpleApplet.class" width="300" height="200"></applet>
</body>
</html>
OUTPUT
10
10. Write a program to create shape and fill color in
shape using Applet
import java.applet.*;
import java.awt.*;
public class Shapes extends Applet
{
public void init()
{
setBackground(Color.white);
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
g.setColor(Color.black);
g.drawString("Pentagon",225,200);
x=new int[]{200,250,300,300,250,200};
y=new int[]{100,50,100,150,150,100};
g.drawPolygon(x,y,6);
g.setColor(Color.yellow);
g.fillPolygon(x,y,6);
g.setColor(Color.black);
g.drawString("Circle",400,200);
g.drawOval(350,50,125,125);
g.setColor(Color.yellow);
g.fillOval(350,50,125,125);
g.setColor(Color.black);
g.drawString("Oval",100,380);
g.drawOval(50,250,150,100);
g.setColor(Color.yellow);
11
g.fillOval(50,250,150,100);
g.setColor(Color.black);
g.drawString("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
g.setColor(Color.black);
g.drawString("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
g.drawPolygon(x,y,3);
g.setColor(Color.yellow);
g.fillPolygon(x,y,3);
}
}
OUTPUT
12
11. Write a program to create a buttons, canvas, radio
checkbox, buttons using AWT controls.
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(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);
System.out.println("Is the given string equal to the specified sequence? " +
result);
}
private static boolean compareStrings(String inputString, String
targetSequence) {
return inputString.equals(targetSequence);
} }
OUTPUT
15
13. Write a program to print the result of removing
duplicates from a given string.
OUTPUT
16
14. Write a java program for handling mouse events and
key events.
import java.awt.*;
import java.awt.event.*;
import java.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);
}
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 = me.getX();
17
mouseY = me.getY();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
} }
OUTPUT
18
15. Write a java program that connects to a database
using JDBC.
package com.STH.JDBC;
import java.sql.*;
public class Sample_JDBC_Program {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
String QUERY = "select * from employee_details";
Class.forName("oracle.jdbc.driver.OracleDriver");
try(Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:system/pass123@localhost
:1521:XE"))
{
Statement statemnt1 = conn.createStatement();
ResultSet rs1 = statemnt1.executeQuery(QUERY);
{
while(rs1.next())
{
int empNum = rs1.getInt("empNum");
String lastName = rs1.getString("lastName");
String firstName = rs1.getString("firstName");
String email = rs1.getString("email");
String deptNum = rs1.getString("deptNum");
String salary = rs1.getString("salary");
System.out.println(empNum + "," +lastName+ "," +firstName+","
+email +","+deptNum +"," +salary);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
} }
19
16. Write a java program to connect to a database using
JDBC and insert values into it.
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Statement;
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 = MySQLConnection.connect();
var stmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setDate(3, dob);
stmt.setString(4, phone);
stmt.setString(5, email);
int rowAffected = stmt.executeUpdate();
if(rowAffected == 1)
{ var rs = stmt.getGeneratedKeys();
if(rs.next()){
id = rs.getInt(1); } }
} catch (SQLException e) {
e.printStackTrace(); }
return id;
} }
OUTPUT
21
17. Write a java program to connect to a database using
JDBC and delete values from it.
import java.sql.Connection;
import java.sql.Statement;
import com.w3spoint.util.JDBCUtil;
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 = JDBCUtil.getConnection();
statement = conn.createStatement();
statement.executeUpdate(query);
statement.close();
conn.close();
System.out.println("Record deleted successfully.");
}catch(Exception e){
e.printStackTrace();
}
}
}
OUTPUT
22
18. Write a java servlet program to handle user form.
package com.servlet.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet
{
@Override
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html");
String username=request.getParameter("username");
String password=request.getParameter("password");
PrintWriter writer = response.getWriter();
String message="Username is : "+ username + "<br/> Password is :" +
password ;
writer.println(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 java.text.*;
import java.util.*;
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(formatDate.format(date));
OUTPUT
25
20. Write a java servlet application to demonstrate the
session tracking in servlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class SessionDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
HttpSession session = request.getSession(true);
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
26
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(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>" + session.getId() + "</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="java.sql.*"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<%!
Connection con;
PreparedStatement ps;
public void jspInit()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"local", "test");
ps = con.prepareStatement("select * from Employees");
}
catch(Exception ex)
{
ex.printStackTrace();
} }
%>
<%
ResultSet rs = ps.executeQuery();
out.println("<table border=1 >");
out.println("<tr style='background-color:#ffffb3; color:red'>");
out.println("<th>Emp Id</th>");
out.println("<th> Age(Year)</th>");
out.println("<th>First Name</th>");
29
out.println("<th>Last Name</th>");
out.println("</tr>");
while(rs.next())
{
out.println("<tr style='background-color:#b3ffd9;'>");
out.println("<td>"+rs.getInt(1)+"</td>");
out.println("<td>"+rs.getInt(2)+"</td>");
out.println("<td>"+rs.getString(3)+"</td>");
out.println("<td>"+rs.getString(4)+"</td");
out.println("</tr>");
}
out.println("</table>");
rs.close();
%>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/JspDB.jsp</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