JAVA PROGRAM's
1. Write a java program to read ‘N’ names of your friends, store it into HashSet and
display them in ascending order.
import [Link].*;
public class FriendNames {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Read number of friends
[Link]("Enter number of friends: ");
int n = [Link]();
[Link](); // consume newline
// HashSet to store names
HashSet<String> names = new HashSet<>();
// Read names
[Link]("Enter friend names:");
for (int i = 0; i < n; i++) {
String name = [Link]();
[Link](name);
}
// TreeSet to sort names in ascending order
TreeSet<String> sortedNames = new TreeSet<>(names);
// Display sorted names
[Link]("\nFriends names in ascending order:");
for (String name : sortedNames) {
[Link](name);
}
[Link]();
}
}
2. Write a Java program to accept ‘n’ integers from the user and store them in a collection.
Display them in the sorted order. The collection should not accept duplicate elements. (Use a
suitable collection). Search for a particular element using predefined search method in the
Collection framework.
import [Link];
import [Link];
public class SortedCollectionExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
TreeSet<Integer> numbers = new TreeSet<>();
[Link]("Enter number of elements: ");
int n = [Link]();
[Link]("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
[Link]([Link]()); // duplicates automatically ignored
}
// Display sorted elements
[Link]("Sorted elements (No duplicates):");
[Link](numbers);
// Searching an element
[Link]("Enter element to search: ");
int searchElement = [Link]();
if ([Link](searchElement)) {
[Link]("Element found in the collection.");
} else {
[Link]("Element not found in the collection.");
}
[Link]();
}
}
[Link] a java program to simulate traffic signal using threads.
class TrafficSignal extends Thread
{
public void run()
{
try
{
while(true)
🔴
{
[Link](" RED Light - STOP");
[Link](3000); // 3 seconds
🟡
[Link](" YELLOW Light - READY");
[Link](2000); // 2 seconds
🟢
[Link](" GREEN Light - GO");
[Link](3000); // 3 seconds
}
}
catch(InterruptedException e)
{
[Link](e);
}
}
}
public class TrafficSignalDemo
{
public static void main(String[] args)
{
TrafficSignal t = new TrafficSignal();
[Link]();
}
}
[Link] a program to display name and priority of the thread.
package mypackage;
public class MyThread extends Thread {
public void run() {
[Link]("Thread Name: " + getName());
[Link]("Thread Priority: " + getPriority());
}
public static void main(String[] args) {
// Main thread details
Thread mainThread = [Link]();
[Link]("Main Thread Name: " + [Link]());
[Link]("Main Thread Priority: " + [Link]());
[Link]("-------------------------");
MyThread t = new MyThread();
[Link]("MyCustomThread");
[Link](7);
[Link]();
}
}
5. Design a servlet that provides information about a HTTP request from a client, such as
IP-Address and browser type. The servlet also provides information about the server on
which the servlet is running, such as the operating system type, and the names of
currently loaded servlets.
package com.sleep2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/info")
public class RequestInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Client Information</h2>");
[Link]("IP Address: " + [Link]() + "<br>");
[Link]("Browser: " + [Link]("User-Agent") + "<br>");
ServletContext context = getServletContext();
[Link]("<h2>Server Information</h2>");
[Link]("OS: " + [Link]("[Link]") + "<br>");
[Link]("<h2>Loaded Servlets</h2>");
Enumeration<String> names = [Link]();
while ([Link]()) {
[Link]([Link]() + "<br>");
}
}
}
----------------------------------------------------------------------------------------------------------
webApp [Link]
<web-app xmlns="[Link]
version="3.1">
<servlet>
<servlet-name>RequestInfoServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestInfoServlet</servlet-name>
<url-pattern>/info</url-pattern>
</servlet-mapping>
</web-app>
6. Write a Java program to display all the alphabets between ‘A’ to ‘Z’ after every 2 seconds.*/
public class AlphabetDelay {
public static void main(String[] args) {
for (char ch = 'A'; ch <= 'Z'; ch++) {
[Link](ch);
try {
[Link](2000); // 2000 milliseconds = 2 seconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}
7. Write a java program for the implementation of synchronization*
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
[Link](n + " x " + i + " = " + (n * i));
try {
[Link](400);
} catch (Exception e) {
[Link](e);
}
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
[Link](5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
public void run() {
[Link](10);
}
}
public class SynchronizationDemo {
public static void main(String[] args) {
Table obj = new Table(); // one shared object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
8.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/VisitCounter")
public class VisitCounter extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Cookie[] cookies = [Link]();
int visitCount = 0;
boolean isNewUser = true;
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("visitCount")) {
visitCount = [Link]([Link]());
visitCount++;
isNewUser = false;
}
}
}
if (isNewUser) {
visitCount = 1;
[Link]("<h2>Welcome! You are visiting this page for the first time.</h2>");
} else {
[Link]("<h2>Welcome Back!</h2>");
[Link]("<h3>You have visited this page " + visitCount + " times.</h3>");
}
Cookie visitCookie = new Cookie("visitCount", [Link](visitCount));
[Link](60 * 60 * 24);
[Link](visitCookie);
[Link]();
}
}
9. Write a SERVLET program in java to accept details of student (SeatNo, Stud_Name,
Class, Total_Marks). Calculate percentage and grade obtained and display details on
page.
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
@WebServlet("/StudentResult")
public class StudentResult extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
// Get form values
String seatNo = [Link]("seatno");
String name = [Link]("name");
String sclass = [Link]("class");
int marks = [Link]([Link]("marks"));
// Calculate percentage (assuming total = 500)
double percentage = (marks / 500.0) * 100;
// Calculate grade
String grade;
if (percentage >= 75)
grade = "A";
else if (percentage >= 60)
grade = "B";
else if (percentage >= 50)
grade = "C";
else if (percentage >= 40)
grade = "D";
else
grade = "Fail";
// Output
[Link]("<html><body>");
[Link]("<h2>Student Result</h2>");
[Link]("Seat No: " + seatNo + "<br>");
[Link]("Name: " + name + "<br>");
[Link]("Class: " + sclass + "<br>");
[Link]("Total Marks: " + marks + "<br>");
[Link]("Percentage: " + percentage + "%<br>");
[Link]("Grade: " + grade + "<br>");
[Link]("</body></html>");
}
}
--------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>Student Form</title>
</head>
<body>
<h2>Student Details Form</h2>
<form action="StudentResult" method="post">
Seat No: <input type="text" name="seatno"><br><br>
Student Name: <input type="text" name="name"><br><br>
Class: <input type="text" name="class"><br><br>
Total Marks: <input type="text" name="marks"><br><br>
<input type="submit" value="Calculate Result">
</form>
</body>
</html>
10. Write a java program to solve producer consumer problem in which a producer
produces a value and consumer consume the value before producer generate the next
value. (Hint: use thread synchronization)
class SharedResource {
private int data;
private boolean hasValue = false;
// Produce method
public synchronized void produce(int value) {
try {
// wait if value not yet consumed
while (hasValue) {
wait();
}
data = value;
[Link]("Produced: " + data);
hasValue = true;
notify(); // notify consumer
} catch (InterruptedException e) {
[Link]();
}
}
// Consume method
public synchronized void consume() {
try {
// wait if no value produced yet
while (!hasValue) {
wait();
}
[Link]("Consumed: " + data);
hasValue = false;
notify(); // notify producer
} catch (InterruptedException e) {
[Link]();
}
}
}
// Producer Thread
class Producer extends Thread {
SharedResource resource;
Producer(SharedResource r) {
resource = r;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
try {
[Link](500);
} catch (Exception e) {}
}
}
}
// Consumer Thread
class Consumer extends Thread {
SharedResource resource;
Consumer(SharedResource r) {
resource = r;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
try {
[Link](500);
} catch (Exception e) {}
}
}
}
// Main Class
public class ProducerConsumerDemo {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Producer p = new Producer(resource);
Consumer c = new Consumer(resource);
[Link]();
[Link]();
}
}
11. Write a JSP script to accept a String from a user and display it in reverse order.
Create Dynamic Web Project
Click File → New → Dynamic Web Project
Project name: ReverseJSP
Target runtime: Select Tomcat
Click Finish
Create HTML Form
Expand (src/main/webapp)
Right click on webapp → New → HTML File
Name it: [Link]
<!DOCTYPE html>
<html>
<body>
<h2>Enter a String</h2>
<form action="[Link]" method="post">
Enter Text:
<input type="text" name="txt">
<input type="submit" value="Reverse">
</form>
</body>
</html>
Create JSP File
Right click Webapp
Click New → JSP File
Name: [Link]
<%@ page language="java" %>
<html>
<body>
<h2>Reversed Output</h2>
<%
String str = [Link]("txt");
if(str != null) {
String rev = "";
for(int i = [Link]()-1; i >= 0; i--) {
rev = rev + [Link](i);
[Link]("Original String: " + str + "<br>");
[Link]("Reversed String: " + rev);
%>
</body>
</html>
[Link] a java program to accept a String from a user and display each vowel from a
String after every 3 seconds.
[15 M]
import [Link];
public class VowelDelayDisplay {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Accept string from user
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Vowels in the string (with 3 sec delay):");
// Convert to lowercase to simplify checking
str = [Link]();
// Loop through each character
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
// Check if character is vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
[Link](ch);
try {
// Delay of 3 seconds (3000 milliseconds)
[Link](3000);
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
[Link]();
}
}
13. Write a java program to accept ‘N’ student names through command line, store them
into the appropriate Collection and display them by using Iterator and ListIterator
interface.
import [Link].*;
public class StudentCollectionDemo {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please pass student names as command line arguments.");
return;
}
ArrayList<String> students = new ArrayList<>();
for (String name : args) {
[Link](name);
}
[Link]("Using Iterator:");
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
[Link]("\nUsing ListIterator (Forward):");
ListIterator<String> litr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
[Link]("\nUsing ListIterator (Backward):");
while ([Link]()) {
[Link]([Link]());
}
}
}
--------------------------------------------
Pass Command Line Arguments in Eclipse
Right-click file → Run As → Run Configurations
Select Java Application
Click your class name
Open Arguments tab
In Program arguments, type student names:
Click Run
--------------------------------------------
Output Appears in Console
Example output:
Using Iterator:
Amit
Neha
Rahul
Pooja
Using ListIterator (Forward):
Amit
Neha
Rahul
Pooja
14.
<!DOCTYPE html>
<html>
<body>
<form action="StudentServlet" method="post">
Seat No:
<input type="text" name="seatno"><br><br>
Name:
<input type="text" name="name"><br><br>
Class:
<input type="text" name="class"><br><br>
Marks:
<input type="text" name="marks"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
15.
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 1. Read data from HTML form
String seat = [Link]("seatno");
String name = [Link]("name");
String cls = [Link]("class");
String marks = [Link]("marks");
// 2. Convert data if needed
int m = [Link](marks);
double percentage = m;
// 3. Send response
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Student Details</h2>");
[Link]("Seat No: " + seat + "<br>");
[Link]("Name: " + name + "<br>");
[Link]("Class: " + cls + "<br>");
[Link]("Percentage: " + percentage);
}
}
16.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentDisplayServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
try {
// 1. Load Driver
[Link]("[Link]");
// 2. Connection
Connection con = [Link](
"jdbc:postgresql://localhost:5432/college",
"postgres",
"password");
// 3. Statement
Statement st = [Link]();
// 4. Execute Query
ResultSet rs = [Link]("SELECT * FROM student");
// 5. Display Data
[Link]("<h2>Student Records</h2>");
[Link]("<table border='1'>");
while([Link]()) {
[Link]("<tr>");
[Link]("<td>"+[Link]("seatno")+"</td>");
[Link]("<td>"+[Link]("name")+"</td>");
[Link]("<td>"+[Link]("class")+"</td>");
[Link]("<td>"+[Link]("marks")+"</td>");
[Link]("</tr>");
}
[Link]("</table>");
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}
17. Write a java program to display name of currently executing Thread in multithreading.
package mypackage;
class MyThread extends Thread {
public void run() {
// Getting the currently executing thread
Thread t = [Link]();
// Display thread name
[Link]("Currently Executing Thread: " + [Link]());
}
public class CurrentThreadDemo {
public static void main(String[] args) {
// Creating thread objects
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
// Setting custom names (optional)
[Link]("First Thread");
[Link]("Second Thread");
// Starting threads
[Link]();
[Link]();
// Display main thread name
[Link]("Main Thread: " + [Link]().getName());
}
[Link] a Multithreading program in java to display the number’s between 1 to 100
continuously in a TextField by clicking on button. (Use Runnable Interface).
package mypackage;
import [Link].*;
import [Link].*;
import [Link].*;
public class NumberThread extends JFrame implements Runnable, ActionListener {
JTextField t1;
JButton b1;
Thread t;
public NumberThread() {
setLayout(new FlowLayout());
t1 = new JTextField(15);
b1 = new JButton("Start");
add(t1);
add(b1);
[Link](this);
setSize(300, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Runnable method
public void run() {
try {
for (int i = 1; i <= 100; i++) {
[Link]([Link](i));
[Link](200); // delay of 200 milliseconds
} catch (Exception e) {
[Link](e);
// Button click event
public void actionPerformed(ActionEvent e) {
t = new Thread(this); // creating thread
[Link](); // starting thread
public static void main(String[] args) {
new NumberThread();
19. Write a SERVLET application to accept username and password, search them into
database, if found then display appropriate message on the browser otherwise display
error message.
step-1 Create database and table in pgAdmin
CREATE DATABASE studentdb;
step-2 Create Users Table
CREATE TABLE users (
username VARCHAR(50),
password VARCHAR(50)
);
step-3 Verify Data
SELECT * FROM users;
Expected output:
admin 1234
student 1111
add jar file
postgresql-42.7.9
src->WEB-INF->lib folder
------------------------------------------------------------------------------------------------------
Servlet Code - [Link]
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String uname = [Link]("username");
String pass = [Link]("password");
try {
// Load Driver
[Link]("[Link]");
// Connect DB
Connection con = [Link](
"jdbc:postgresql://localhost:5432/studentdb",
"postgres",
"1234"
);
// Query
PreparedStatement ps = [Link](
"SELECT * FROM users WHERE username=? AND password=?"
);
[Link](1, uname);
[Link](2, pass);
ResultSet rs = [Link]();
if ([Link]()) {
[Link]("<h2>Login Successful</h2>");
[Link]("<h3>Welcome " + uname + "</h3>");
} else {
[Link]("<h2>Invalid Login</h2>");
}
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}
---------------------------------------------------------------------------------------------------------
create [Link]
<!DOCTYPE html>
<html>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
----------------------------------------------------------------------------------------------------------
CREATE TABLE users(
username VARCHAR(50),
password VARCHAR(50)
);
INSERT INTO users VALUES('admin','1234');
INSERT INTO users VALUES('megha','pass123');