0% found this document useful (0 votes)
5 views

java_solutions

The document contains multiple Java code snippets demonstrating various programming concepts such as threading, database connectivity, and data structures. It includes examples for printing alphabets, managing city STD codes, handling traffic signals, and performing database operations with PostgreSQL. Additionally, it features HTML and JSP code for user interaction and data display.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java_solutions

The document contains multiple Java code snippets demonstrating various programming concepts such as threading, database connectivity, and data structures. It includes examples for printing alphabets, managing city STD codes, handling traffic signals, and performing database operations with PostgreSQL. Additionally, it features HTML and JSP code for user interaction and data display.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Java Slip Solution

Slip 1A:

(here make file name using AlphabetPrinter)


// slip1A.java
import java.util.*;
import java.io.*;
class slip1A extends Thread {
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.println(c);
try {
Thread.sleep(2000); // 2000 milliseconds = 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class AlphabetPrinter {


public static void main(String[] args) {
// Create an instance of the slip1A class
slip1A alphabetThread = new slip1A();
alphabetThread.start(); // Start the thread
}
}

slip1B:

import java.sql.*;
import java.io.*;
class slip1B(here create database and insert record in it)
{
public static void main(String args[])throws SQLException
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try
{
Class.forName("org.postgresql.Driver");

con=DriverManager.getConnection("jdbc:postgresql:ab","postgres","");
if(con==null)
System.out.println("Connection Failed");
else
{
System.out.println("Connection sucessfull");
stmt=con.createStatement();
rs=stmt.executeQuery("Select * from emp");
while(rs.next())
{
System.out.println("EMP id="+rs.getInt(1));
System.out.println("EMP Name="+rs.getString(2));
System.out.println("EMP
Designation="+rs.getString(3));
System.out.println("EMP salary="+rs.getInt(4));
}
con.close();
}
}
catch(Exception e)
{
System.out.println("ERROR"+e);
}
}
}
slip2A:

import java.util.*;

public class slip2A {


public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of friends: ");


int n = scanner.nextInt();
scanner.nextLine();

LinkedList<String> friendsList = new LinkedList<>();


for (int i = 1; i <= n; i++)
{
System.out.print("Enter the name of friend " + i + ": ");
String friendName = scanner.nextLine();
friendsList.add(friendName);
}
Iterator<String> itr = friendsList.iterator();
System.out.println("\nThe list of friends is:");
while (itr.hasNext()) {
System.out.println(itr.next());
}

scanner.close();
}
}

slip2B
slip2B(not runed)

mport java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class slip2 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html"
PrintWriter out=res.getWriter();
ServletConfig config=getServletConfig();

out.println("Server Name:"+req.getServerName());
out.println("Server Port:"+req.getServerPort());
out.println("Client IP Address:"+req.getRemoteHost())
out.println("Header info:"+req.getHeader("user-
out.println("context getServer Info:"+config.getServletName()
}
}

slip3A

<%@ page language="java" import="java.util.*" %>

<%@ page language="java" import="java.sql.*" %>


<html>
<head>
<title>PATIENT DETAILS</title>
</head>
<body>
<%
Class.forName("org.postgresql.
out.println("Diver loaded");

Connection c=DriverManager.getConnection(
out.println("Connection created");
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from patient");

out.println("<html><body>");
out.println("<h1>PATIENT DETAILS</h1>");
out.println("<table border='1'>");
out.println("<tr><th>patient no</th><th>pname</th><th>

while(rs.next())
{

out.println("<tr>");
out.println("<td>"+ rs.getInt(1) +"</td>");
out.println("<td>"+ rs.getString(2) +"</td>");
out.println ("<td>"+ rs.getString(3) +"</td>");
out.println("<td>"+ rs.getInt(4) +"</td>");
out.println("<td>"+ rs.getString(5) +"</td>");
out.println("</tr>");

}
%>
</body>
</html>

slip3B:

import java.util.*;
class slip28B {
public static void main(String args[]) {
int n;
String element;
Scanner sc = new Scanner(System.in);

LinkedList<String> a1 = new LinkedList<>();

System.out.println("Enter the number of elements:");


n = sc.nextInt();
sc.nextLine();

for (int i = 1; i <= n; i++) {


System.out.println("Enter a string element:");
element = sc.nextLine();
a1.add(element);
}
System.out.println("Enter a string to add at the beginning:");
String firstElement = sc.nextLine();
a1.addFirst(firstElement);
System.out.println("After adding at the beginning: " + a1);

if (!a1.isEmpty()) {
a1.removeLast();
System.out.println("After deleting the last element: " + a1);
} else {
System.out.println("The list is empty, no element to delete.");
}
System.out.println("Displaying the list in reverse order:");
ListIterator<String> iterator = a1.listIterator(a1.size()); // Start at the end
of the list
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
}
slip4A

slip4B

import java.util.*;

public class slip4B {


public static void main(String[] args) {
// Corrected the Hashtable declaration with proper generics
Hashtable<String, Integer> cityTable = new Hashtable<>();
Scanner sc = new Scanner(System.in);

while (true) {
System.out.println("\n*** City STD Code Manager ***");
System.out.println("1. Add a new city and its code");
System.out.println("2. Remove a city");
System.out.println("3. Search for a city");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
int choice = sc.nextInt();
sc.nextLine(); // To consume the leftover newline character from
nextInt()

switch (choice) {
case 1:
System.out.print("Enter city name: ");
String city = sc.nextLine();
System.out.print("Enter STD code: ");
int code = sc.nextInt();
if (cityTable.containsKey(city)) {
System.out.println("City exists");
} else {
cityTable.put(city, code);
System.out.println("City successfully added");
}
break;
case 2:
System.out.print("Enter the city name to remove: ");
String cityToRemove = sc.nextLine();
if (cityTable.containsKey(cityToRemove)) {
cityTable.remove(cityToRemove);
System.out.println("City removed successfully.");
} else {
System.out.println("City not found!");
}
break;
case 3:
System.out.print("Enter the city name to search: ");
String cityToSearch = sc.nextLine();
if (cityTable.containsKey(cityToSearch)) {
System.out.println("STD Code for " + cityToSearch + " is: " +
cityTable.get(cityToSearch));
} else {
System.out.println("City not found!");
}
break;
case 4:
System.out.println(cityTable);
break;
case 5:
System.out.println("Exit");
sc.close();
return;
default:
System.out.println("Invalid choice");
}
}
}
}

slip5A

import java.util.*;
import java.util.Hashtable;
class slip5A
{
public static void main(String[] args)
{
int i;
Hashtable<Long,String> hashtable=new
Hashtable<Long,String>();
System.out.println("ENTER THE NO OF ENTRIES");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(i=0;i<n;i++)
{
System.out.println("ENTER THE NUMBER:");
long number=sc.nextLong();
System.out.println("ENTER THE NAME:");
String name=sc.next();
hashtable.put(number,name);
}
Enumeration<Long> keys = hashtable.keys();
while (keys.hasMoreElements())
{
long key = keys.nextElement();
System.out.println(key +": " + hashtable.get(key));
}
}
}

slip6A
import java.util.*;
class slip6A
{
public static void main(String args[])
{
int n,j;
Scanner sc=new Scanner(System.in);

System.out.println("enter Number");
n=sc.nextInt();
Set <Integer>ts=new TreeSet<Integer>();
for( int i=0;i<n;i++)
{
System.out.println("enter interger value");
j=sc.nextInt();
ts.add(j);
}
System.out.println("members from Treeset="+ts);
}
}

slip6B:

class TrafficSignal implements Runnable {


private String signalName;

public TrafficSignal(String signalName) {


this.signalName = signalName;
}

@Override
public void run() {
while (true) {
try {
// Green Light (3 seconds)
System.out.println(signalName + " Signal is GREEN");
Thread.sleep(3000); // Green for 3 seconds

// Yellow Light (2 seconds)


System.out.println(signalName + " Signal is YELLOW");
Thread.sleep(2000); // Yellow for 2 seconds

// Red Light (5 seconds)


System.out.println(signalName + " Signal is RED");
Thread.sleep(5000); // Red for 5 seconds

} catch (InterruptedException e) {
System.out.println(signalName + " Signal interrupted");
}
}
}
}

public class slip6B {


public static void main(String[] args) {
// Create two traffic signals (e.g., one for north-south and one for east-
west)
Thread signal1 = new Thread(new TrafficSignal("North-South"));
Thread signal2 = new Thread(new TrafficSignal("East-West"));

// Start the signals in separate threads


signal1.start();
signal2.start();
}
}

slip7A:

import java.util.*;
class Square extends Thread
{
int x;
Square(int n)
{
x=n;
}
public void run()
{
System.out.println("Square="+x*x);
}

class Cube extends Thread


{
int x;

Cube(int n)
{
x=n;
}
public void run()
{
System.out.println("Cube="+x*x*x);
}

class Number extends Thread{


public void run()
{
Random r=new Random();
for(int i=0;i<10;i++)
{
int x=r.nextInt(100);
if(x%2==0)
{
System.out.println("Number Even="+x);
Square sq=new Square(x);
sq.start();
}
else
{
System.out.println("Number Odd="+x);
Cube cb=new Cube(x);
cb.start();
}
}
}
}

class slip7A
{
public static void main(String args[])
{
Number obj=new Number();
obj.start();
}}

slip7B:

import java.util.*;
import java.io.*;
import java.sql.*;

class slip7B {
public static void main(String args[]) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {

Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql:ab", "postgres",
"");
if (con == null)
System.out.println("Connection failed");
else {
System.out.println("Connection successful");
stmt = con.createStatement();

rs = stmt.executeQuery("SELECT * FROM product");


while (rs.next()) {
System.out.println("Product ID = " + rs.getInt(1));
System.out.println("Product Name = " + rs.getString(2));
System.out.println("Product Price = " + rs.getInt(3));
System.out.println("----------------------------------------");
}
con.close();
}
} catch (Exception e) {
System.out.println("ERROR: " + e);
}
}
}

slip8A:

class MyThread extends Thread


{
String message;
int n;
MyThread(String message,int n)
{
this.message=message;
this.n=n;
}
public void run()
{
try
{
for(int i=1;i<=n;i++)
{
System.out.println(message+"-"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie){}
}
}
public class slip8A
{
public static void main(String args[])
{
MyThread t1=new MyThread("COVID19",10);
MyThread t2=new MyThread("LOCKDOWN2020",20);
MyThread t3=new MyThread("VACCINATED2021",30);
System.out.println(t1);
t1.start();
System.out.println(t2);
t2.start();
System.out.println(t3);
t3.start();
}
}
slip8B:

jsp:
%@ page language="java" import="java.util.*"%>
<%
int num=Integer.parseInt(request.getParameter("num"));
int flag=0;
out.println("<html><body>");
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}
if(flag==0)
out.println("<h1 style='color:red'>Prime</h1>");
else
out.println("<h1 style='color:red'>Not a
Prime</h1>");
out.println("</html></body>");
%>

html file:

<html>
<head><title>Prime number or not</title></head>
<body>
<form action="slip8jsp.jsp" method="post">
Enter a number<input type="text" name="num"><br>
<input type="Submit" value="Submit">
</form>
</body>
</html>

slip11A:(not runed)
html file

<!DOCTYPE html>
<html>
<head>
<title>Customer Search</title>
</head>
<body>
<h2>Search Customer Details</h2>
<form action="slip11A" method="get">
<label for="customerNumber">Enter Customer
Number:</label>
<input type="text" id="customerNumber"
name="customerNumber" required>
<br><br>
<input type="submit" value="Search">
</form>
<div id="result"></div>
</body>
</html>

servlet file:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class slip11A extends HttpServlet
{
public void service(HttpServletRequest
req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
out.println("<html>");
out.println("<body>");
Class.forName("org.postgresql.Driver");
out.println("<h1>Driver loaded</h1>");

Connection
c=DriverManager.getConnection("jdbc:postgresql:ab","pos
tgres","");
out.println("<h1>Connection created</h1>");

Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from
customer");
while(rs.next())
{

out.print("<h3>"+rs.getInt(1)+"-"+rs.getString(2)+"</h3
>");
out.println("<br>");
}
}
catch(Exception e)
{
out.println("ERROR"+e);
}
out.println("<h1>HI!Manisha</h1>");
out.println("</body>");
out.println("</html>");
}
}

slip11B:

import java.sql.*;
public class slip11B{
public static void main(String[] args) {
try {

Class.forName("org.postgresql.Driver");

Connection conn =
DriverManager.getConnection("jdbc:postgresql:ab",
"postgres", "");

Statement stmt = null;


stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select *
from donor");

ResultSetMetaData rsmd = rs.getMetaData();


System.out.println("\t---");

int count = rsmd.getColumnCount();


System.out.println("\t No. of Columns: " +
rsmd.getColumnCount());
System.out.println("\t------");
for (int i = 1; i <= count; i++)
{
System.out.println("\t\tColumn No : " +
i);
System.out.println("\t\tColumn Name : "
+ rsmd.getColumnName(i));
System.out.println("\t\tColumn Type : "
+ rsmd.getColumnTypeName(i));
System.out.println("\t\tColumn Display
Size : " + rsmd.getColumnDisplaySize(i));
System.out.println();
} // for
System.out.println("\t-----");

rs.close();
stmt.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}

slip 12A:
<!DOCTYPE html>
<html>
<head>
<title>PERFECT NUMBER</title>
</head>
<body>
<form action="perfect.jsp" method="post">
Enter Number :<input type="text" name="num">
<input type="submit" value="Submit" name="s1">
</form>
</body>
</html>

Perfect.jsp file:
<%@ page import="java.util.*" %>

<%
if(request.getParameter("s1")!=null)
{
Integer num,a,i,sum = 0;

num = Integer.parseInt(request.getParameter("num"));
a = num;

for(i=1;i<a;i++)
{
if(a%i==0)
{
sum=sum + i;
}
}
if(sum==a)
{
out.println(+num+ "is a perfect number");
}
else
{
out.println(+num+ "is not a perfect number");
}
}
%>

slip12B :
import java.sql.*;
import java.io.*;
class slip12B
{
public static void main(String args[])throws
SQLException
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try
{
Class.forName("org.postgresql.Driver");

con=DriverManager.getConnection("jdbc:postgresql:ab","p
ostgres","");
if(con==null)
System.out.println("Connection is failed");
else
System.out.println("Connection is Successful");
stmt=con.createStatement();
String query4="Insert into Project
values(105,'OnlineBookshope','MarketProduct','Incomple'
)";
stmt.executeUpdate(query4);

}
catch(Exception e)
{
System.out.println("Error"+e);
}

}
}

slip13A:

import java.util.*;
import java.sql.*;
class slip13A
{
public static void main(String args[])
{
Connection con;
Statement st;

try
{
Class.forName("org.postgresql.Driver");

con=DriverManager.getConnection("jdbc:postgresql:ab","p
ostgres","");
st=con.createStatement();
DatabaseMetaData db=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=db.getTables(null,null,null,table);
while(rs.next())
{
System.out.println(rs.getString(3));
}

System.out.println("JDBC Driver
Name:"+db.getDriverName());
System.out.println("JDBC Driver Version
Name:"+db.getDriverVersion());
System.out.println("DB Product
Version:"+db.getDatabaseProductVersion());
System.out.println("Product
Name:"+db.getDatabaseProductName());
System.out.println("User Name:"+db.getUserName());
}
catch(Exception e)
{
System.out.println("Error!"+e);
}
}
}

slip13B:

class MyThread extends Thread {


public MyThread(String s) {
super(s);
}

public void run() {


System.out.println(getName() + " thread
created.");
while (true) {
System.out.println(this);
int s = (int)(Math.random() * 5000);
System.out.println(getName() + " is
sleeping for: " + s + " msec");
try {
Thread.sleep(s);
} catch (InterruptedException e) {
System.out.println(getName() + " was
interrupted.");
break;
}
}
}
}

class slip13B{
public static void main(String args[]) {
MyThread t1 = new MyThread("Shradha"), t2 = new
MyThread("Pooja");
t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main thread
interrupted.");
}

System.out.println(t1.getName() + " thread


dead.");
System.out.println(t2.getName() + " thread
dead.");
}
}

slip15A:

class slip15A extends Thread {


public void run() {
System.out.println("Running thread name is: " +
Thread.currentThread().getName());
System.out.println("Running thread priority is:
" + Thread.currentThread().getPriority());
}
public static void main(String args[]) {
slip15A m1 = new slip15A(); // Create a thread
of type slip15A
slip15A m2 = new slip15A(); // Create another
thread of type slip15A

m1.setPriority(Thread.MIN_PRIORITY); // Set m1
to minimum priority
m2.setPriority(Thread.MAX_PRIORITY); // Set m2
to maximum priority

m1.start(); // Start m1
m2.start(); // Start m2
}
}

slip15B :

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class slip15B extends HttpServlet
{
public void service(HttpServletRequest
req,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter out=null;
try{
res.setContentType("text/html");
out=res.getWriter();
Cookie c[]=req.getCookies();
if(c==null)
{
out.println("Welcome for cookie demo");
Cookie c1=new Cookie("count",Integer.toString(1));
res.addCookie(c1);
}
else{
for(int i=0;i<c.length;i++)
{
String name=c[i].getName();
String val=c[i].getValue();
out.println("Name="+name+"val="+val);
if(name.equals("count"))
{
int n=Integer.parseInt(val)+1;
c[i].setValue(Integer.toString(n));
out.println("page access for"+n+"times");
res.addCookie(c[i]);
}
}
}
out.close();
}catch(Exception e)
{
out.println("Error"+e);
}
}
}

slip16A:

import java.util.Set;
import java.util.TreeSet;

public class slip16A {


public static void main(String args[]) {
// TreeSet of Strings (for colors)
Set<String> ts = new TreeSet<String>();
ts.add("pink");
ts.add("green");
ts.add("blue");
ts.add("black");
ts.add("gray");
System.out.println("Members from TreeSet
(Strings): " + ts);

// TreeSet of Integers (specify Integer type to


avoid raw type warning)
Set<Integer> ts2 = new TreeSet<Integer>(); //
Specified the type Integer
ts2.add(1);
ts2.add(2);
ts2.add(3);
ts2.add(4);
ts2.add(2); // Duplicate value, will not be
added to the TreeSet
System.out.println("Members from TreeSet
(Integers): " + ts2);
}
}

slip16B(having some error)

import java.util.*;
import java.sql.*;

class slip16B {
public static void main(String args[]) {
int tno;
String tname, subject;
Scanner sc = new Scanner(System.in);
PreparedStatement ps1 = null, ps2 = null;
Connection con = null;
ResultSet rs = null;

try {
// Load the PostgreSQL driver
Class.forName("org.postgresql.Driver");
// Connect to the database (replace with
your actual database details)
con =
DriverManager.getConnection("jdbc:postgresql:ab",
"postgres", "");

if (con == null)
System.out.println("Connection
Failed");
else
System.out.println("Connection
Successful");

// Prepare statement for inserting teacher


details
ps1 = con.prepareStatement("INSERT INTO
teacher (tno, tname, subject) VALUES (?, ?, ?)");

// Insert 5 teacher records into the


teacher table
for (int i = 1; i <= 5; i++) {
System.out.println("Enter Teacher " + i
+ " Details:");
System.out.print("Enter Teacher ID
(tno): ");
tno = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Teacher Name
(tname): ");
tname = sc.nextLine();
System.out.print("Enter Subject: ");
subject = sc.nextLine();

// Insert data into the teacher table


using PreparedStatement
ps1.setInt(1, tno);
ps1.setString(2, tname);
ps1.setString(3, subject);
ps1.executeUpdate();
}

System.out.println("\nTeacher details have


been inserted.");

// Query teachers who are teaching Java


String query = "SELECT tno, tname, subject
FROM teacher WHERE subject = ?";
ps2 = con.prepareStatement(query);
ps2.setString(1, "Java");
rs = ps2.executeQuery();

// Check if any rows are returned


if (!rs.next()) {
System.out.println("No teachers found
who are teaching Java.");
} else {
System.out.println("\nTeachers who are
teaching Java:");
do {
tno = rs.getInt("tno");
tname = rs.getString("tname");
subject = rs.getString("subject");

System.out.println("Teacher ID: " +


tno);
System.out.println("Teacher Name: "
+ tname);
System.out.println("Subject: " +
subject);

System.out.println("-------------------------");
} while (rs.next());
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close all resources
if (ps1 != null) ps1.close();
if (ps2 != null) ps2.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

slip17A:

import java.util.*;
class slip17A
{
public static void main(String args[])
{
int n,j;
Scanner sc=new Scanner(System.in);

System.out.println("enter Number");
n=sc.nextInt();
Set <Integer>ts=new TreeSet<Integer>();
for( int i=0;i<n;i++)
{
System.out.println("enter interger value");
j=sc.nextInt();
ts.add(j);
}
System.out.println("members from Treeset="+ts);
}
}

slip17B:
class slip17B implements Runnable {
@Override
public void run() {
int i = 1;
while (true) {
System.out.println(i);
i++;
if (i > 100) {
i = 1;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ContinuousNumberDisplay {


public static void main(String[] args) {
slip17B task = new slip17B();
Thread thread = new Thread(task);

thread.start();
}
}

slip18A:
import java.util.*;

class slip18B extends Thread {


String name;
slip18B(String name)
{
this.name = name;
}
public void run() {
int count = 0;
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c
== 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c
== 'O' || c == 'U') {
count++;
System.out.println(c); // Print each
vowel
}
}
System.out.println("NUMBER OF VOWELS: " +
count); // Print the total count of vowels
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
System.out.println("ENTER YOUR NAME:");
String name = sc.next();

slip18B v = new slip18B(name);


v.start();
}
}

slip18B:

import java.util.*;

public class slip18A {

public static void main(String[] args)


{
LinkedList<Integer> numbers = new
LinkedList<>();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers:


");
int n = scanner.nextInt();

System.out.println("Enter " + n + "


integers:");
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
numbers.add(number);
}

System.out.println("Negative numbers in the


list are:");
for (int number : numbers) {
if (number < 0) {
System.out.println(number);
}
}
scanner.close();
}
}

slip19B:

slip20A:

<html>
<body>
<form method=get action="NumberWord.jsp">
Enter Any Number : <input type=text name=num><br><br>
<input type=submit value="Display">
</form>
<body>
</html>

NumberWord.jsp

<html>
<body>
<font color=red>
<%! int i,n;
String s1;
%>
<% s1=request.getParameter("num");
n=s1.length();
i=0;
do
{
char ch=s1.charAt(i);
switch(ch)
{
case '0': out.println("Zero ");break;
case '1': out.println("One ");break;
case '2': out.println("Two ");break;
case '3': out.println("Three ");break;
case '4': out.println("Four ");break;
case '5': out.println("Five ");break;
case '6': out.println("Six ");break;
case '7': out.println("Seven ");break;
case '8': out.println("Eight ");break;
case '9': out.println("Nine ");break;
}
i++;
}while(i<n);
%>
</font>
</body>
</html>
slip21A:

import java.util.*;
public class slip21A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of subjects:
");
int n = scanner.nextInt();
scanner.nextLine();

LinkedList<String> subjectList = new


LinkedList<>();

for (int i = 0; i < n; i++) {


System.out.print("Enter the name of subject
" + (i + 1) + ": ");
String subject = scanner.nextLine();
subjectList.add(subject);
}

Iterator<String> iterator =
subjectList.iterator();
System.out.println("\nSubjects list:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
scanner.close();
}
}

slip23A:

import java.util.*;

class slip18B extends Thread {


String name;
slip18B(String name)
{
this.name = name;
}
public void run() {
int count = 0;
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);

if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||


c == 'A' || c == 'E' || c == 'I' || c
== 'O' || c == 'U') {
count++;
System.out.println(c); // Print each
vowel
}
}
System.out.println("NUMBER OF VOWELS: " +
count); // Print the total count of vowels
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
System.out.println("ENTER YOUR NAME:");
String name = sc.next();

slip18B v = new slip18B(name);


v.start();
}
}

slip23B :

import java.util.*;

public class slip23B {

public static void main(String args[]) {


int n = 0;
Scanner scanner = new Scanner(System.in);
if (args.length > 0) {
try {
n = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Please provide a
valid number for the number of students.");
return;
}
} else {
System.out.print("Please provide the number
of students: ");
n = scanner.nextInt();
}
if (n <= 0) {
System.out.println("The number of students
must be a positive number.");
return;
}

ArrayList<String> studentNames = new


ArrayList<>();
if (args.length > 1) {
if (args.length - 1 < n) {
System.out.println("Please provide
exactly " + n + " student names.");
return;
}
Collections.addAll(studentNames,
Arrays.copyOfRange(args, 1, args.length));
} else {
for (int i = 0; i < n; i++) {
System.out.print("Enter name of student
" + (i + 1) + ": ");
studentNames.add(scanner.next());
}
}
System.out.println("\nUsing Iterator:");
studentNames.iterator().forEachRemaining(System.out::pr
intln);

System.out.println("\nUsing ListIterator:");

studentNames.listIterator().forEachRemaining(System.out
::println);

scanner.close();
}
}

slip27B:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet("/slip27B") // Use this annotation to map


the servlet
public class slip27B extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();

// Get the current session object, create one


if necessary
HttpSession session = req.getSession();
out.println("Session Timer<br>");

// Display the previous timeout


out.println("The previous timeout was " +
session.getMaxInactiveInterval());
out.println("<br>");

// Set the new timeout


session.setMaxInactiveInterval(2 * 60 * 60); //
two hours

// Display the new timeout


out.println("The newly assigned timeout is " +
session.getMaxInactiveInterval());

out.close();
}
}

slip28A :

import java.util.*;
class slip28B extends Thread
{
public void run()
{
System.out.println("running thread name
is :"+Thread.currentThread().getName());
}
public static void main(String args[])
{
slip28B m1= new slip28B();
// m1.setName("Thread1");
m1.start();
}
}

slip29A:(repeated)

slip29B:
import java.util.*;

class slip28B{
public static void main(String args[]) {
int n, element;
Scanner sc = new Scanner(System.in);

LinkedList<Integer> a1 = new LinkedList<>();

System.out.println("Enter the number of


elements:");
n = sc.nextInt();

for (int i = 1; i <= n; i++) {


System.out.println("Enter an integer
element:");
element = sc.nextInt();
a1.add(element);
}

System.out.println("Enter an integer to add at


the beginning:");
int firstElement = sc.nextInt();
a1.addFirst(firstElement);
System.out.println("After adding at the
beginning: " + a1);

if (!a1.isEmpty()) {
a1.removeLast();
System.out.println("After deleting the last
element: " + a1);
} else {
System.out.println("The list is empty, no
element to delete.");
}

System.out.println("Size of the linked list: "


+ a1.size());
}
}

slip30B:(repeated in slip 16)

You might also like