Java Practical Solutions
Java Practical Solutions
Slip 1
1.Write a Java program to display all the alphabets between ‘A’ to ‘Z’ a er every 2 seconds.
public class Slip1_1 extends Thread{
char c;
public void run(){
for(c = 'A'; c<='Z';c++){
System.out.println(""+c);
try{
Thread.sleep(3000);
}
catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String args[]){
Slip1_1 t = new Slip1_1();
t.start();
}
}
2.Write a Java program to accept the details of Employee (Eno, EName, Designa on,
Salary) from a user and store it into the database. (Use Swing)
import java.sql.*;
SQL->
CREATE TABLE Employee (
Eno INT PRIMARY KEY,
EName VARCHAR(255),
Designation VARCHAR(255),
Salary DECIMAL(10, 2)
);
Slip 4
1.Write a Java program using Runnable interface to blink Text on the frame
import javax.swing.*;
import java.awt.*;
@Override
public void run() {
try {
while (true) {
SwingUtilities.invokeLater(() -> label.setVisible(true));
Thread.sleep(500);
SwingUtilities.invokeLater(() -> label.setVisible(false));
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
frame.setVisible(true);
});
}
}
2.Write a Java program to store city names and their STD codes using an appropriate collec on and
perform following opera ons: i. Add a new city and its code (No duplicates) ii. Remove a city from
the collec on iii. Search for a city name and display the code
import java.util.*;
public CityStdCodes() {
this.cityStdCodes = new HashMap<>();
}
cityStdCodes.searchCity("Paris");
cityStdCodes.searchCity("Berlin");
cityStdCodes.removeCity("London");
cityStdCodes.removeCity("Sydney");
}
}
Slip 6
1. Write a Java program to accept ‘n’ integers from the user and store them in a collec on. Display
them in the sorted order. The collec on should not accept duplicate elements. (Use a suitable
collec on). Search for a par cular element using predefined search method in the Collec on
framework.
import java.util.*;
scanner.close();
}
}
2. Write a java program to simulate traffic signal using threads.
enum SignalState {
RED, YELLOW, GREEN
}
public TrafficSignal() {
this.state = SignalState.RED;
}
@Override
public void run() {
while (true) {
synchronized (signal) {
try {
while (signal.getState() != SignalState.GREEN) {
System.out.println(name + " is waiting at the
signal.");
signal.wait();
}
System.out.println(name + " is crossing the signal.");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
car1.start();
car2.start();
car3.start();
while (true) {
try {
Thread.sleep(5000);
signal.changeState();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Slip 7
1. Write a java program that implements a mul -thread applica on that has three threads. First
thread generates random integer number a er every one second, if the number is even; second
thread computes the square of that number and print it. If the number is odd, the third thread
computes the of cube of that number and print it.
import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger);
c.start();
try {
Thread.sleep(1000);} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class Slip7_1 {
public static void main(String args[])
{
Number n = new Number();
n.start();
}
}
2.Write a java program for the following: i. To create a Product(Pid, Pname, Price) table. ii. Insert at
least five records into the table. iii. Display all the records from a table.
import java.sql.*;
createProductTable(connection);
insertRecords(connection);
displayRecords(connection);
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createProductTable(Connection connection) throws
SQLException
{
String createTableSQL = "CREATE TABLE IF NOT EXISTS Product (" +
"Pid INT ," +
"Pname VARCHAR(255)," +
"Price DECIMAL(10, 2)" +
")";
Statement statement = connection.createStatement();
statement.execute(createTableSQL);
statement.close();
}
Object[][] data = {
{1, "Product A", 10.99},
{2, "Product B", 20.49},
{3, "Product C", 15.79},
{4, "Product D", 30.25},
{5, "Product E", 25.99}
};
preparedStatement.close();
}
resultSet.close();
statement.close();
}
}
SQL->
CREATE TABLE IF NOT EXISTS Product (
Pid INT AUTO_INCREMENT PRIMARY KEY,
Pname VARCHAR(255),
Price DECIMAL(10, 2)
);
2)
INSERT INTO Product (Pid, Pname, Price) VALUES
(1, 'Laptop', 999.99),
(2, 'Mobile Phone', 599.99),
(3, 'Headphones', 99.99),
(4, 'Tablet', 399.99),
(5, 'Smartwatch', 199.99);
Slip 13
1. Write a Java program to display informa on about the database and list all the tables in the
database. (Use DatabaseMetaData).
import java.sql.*;
System.out.println("Database Information:");
System.out.println("Database Name: " +
metaData.getDatabaseProductName());
System.out.println("Database Version: " +
metaData.getDatabaseProductVersion());
System.out.println();
tablesResultSet.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. Write a Java program to show lifecycle (crea on, sleep, and dead) of a thread. Program should
print randomly the name of thread and value of sleep me. The name of the thread should be
hard coded through constructor. The sleep me of a thread will be a random integer in the range 0
to 4999
import java.util.Random;
@Override
public void run() {
System.out.println(threadName + " is created.");
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted while
sleeping.");
}
thread1.start();
thread2.start();
thread3.start();
}
}
Slip 16
1. Write a java program to create a TreeSet, add some colors (String) and print out the content of
TreeSet in ascending order.
import java.util.TreeSet;
2. Write a Java program to accept the details of Teacher (TNo, TName, Subject). Insert at least 5
Records into Teacher Table and display the details of Teacher who is teaching “JAVA” Subject.
(Use PreparedStatement Interface).
import java.sql.*;
insertRecords(connection);
displayJavaTeachers(connection);
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void insertRecords(Connection connection) throws
SQLException {
String insertSQL = "INSERT INTO Teacher (TNo, TName, Subject) VALUES
(?, ?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(insertSQL);
Object[][] data = {
{1, "John Doe", "JAVA"},
{2, "Jane Smith", "C++"},
{3, "Alice Johnson", "JAVA"},
{4, "Bob Brown", "Python"},
{5, "Emily Davis", "JAVA"}
};
preparedStatement.close();
}
resultSet.close();
preparedStatement.close();
}
}
SQL->
import java.util.*;
import java.io.*;
class Slip17_1{
public static void main(String[] args) throws Exception{
int no,element,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
TreeSet ts=new TreeSet();
System.out.println("Enter the of elements :");
no=Integer.parseInt(br.readLine());
for(i=0;i<no;i++){
System.out.println("Enter the element : ");
element=Integer.parseInt(br.readLine());
ts.add(element);
}
System.out.println("The elements in sorted order :"+ts);
System.out.println("Enter element to be serach : ");
element = Integer.parseInt(br.readLine());
if(ts.contains(element))
System.out.println("Element is found");
else
System.out.println("Element is NOT found");
}
}
2. Write a Mul threading program in java to display the number’s between 1 to 100 con nuously
in a TextField by clicking on bu on. (Use Runnable Interface).
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MultiThread extends JFrame implements ActionListener
{
Container cc;
JButton b1,b2;
JTextField t1;
MultiThread()
{
setVisible(true);
setSize(1024,768);
cc=getContentPane();
setLayout(null);
t1=new JTextField(500);
cc.add(t1);
t1.setBounds(10,10,1000,30);
b1=new JButton("start");
cc.add(b1);
b1.setBounds(20,50,100,40);
b1.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
new Mythread();
}
}
class Mythread extends Thread
{
Mythread()
{
start();
}
public void run()
{
for(int i=1;i<=100;i++)
{
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
t1.setText(t1.getText()+""+i+"\n");
}
}
}
public static void main(String arg[])
{
new MultiThread().show();
}
}
Slip 21
1. Write a java program to accept ‘N’ Subject Names from a user store them into LinkedList
Collec on and Display them by using Iterator interface.
import java.util.*;
import java.io.*;
public class Slip21_1
{
public static void main(String args[])throws Exception
{
int n;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
LinkedList li = new LinkedList ();
System.out.println("\nEnter number of Employee : ");
n = Integer.parseInt(br.readLine());
System.out.println("\nEnter name : ");
for(int i = 1; i <= n; i++)
{
li.add(br.readLine());
}
System.out.println("\nLink List Content : ");
Iterator it = li.iterator();
{
System.out.println(it.next());
}
System.out.println("\nReverse order : ");
ListIterator lt = li.listIterator();
while(lt.hasNext())
{
lt.next();
}
while(lt.hasPrevious())
{
System.out.println(lt.previous());
}
}
}
2. 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
synchroniza on)
import java.util.LinkedList;
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC {
System.out.println("Producer produced-"
+ value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
while (list.size() == 0)
wait();
System.out.println("Consumer consumed-"
+ val);
notify();
Thread.sleep(1000);
}
}
}
}
}
Slip 23
1.Write a java program to accept a String from a user and display each vowel from a String a er
every 3 seconds.
import java.io.*;
public class Slip23_1 extends Thread{
String s1;
StringVowels(String s){
s1=s;
start();
}
public void run(){
System.out.println("Vowels are :- ");
for(int i=0;i<s1.length();i++ ){
char ch=s1.charAt(i);
if(ch=='a'|| ch=='e'|| ch=='i'|| ch=='o'|| ch=='u'|| ch=='A'||
ch=='E'|| ch=='I'|| ch=='O'|| ch=='U')
System.out.print(" "+ch);
}
}
public static void main(String args[]) throws Exception{
2. Write a java program to accept ‘N’ student names through command line, store them into
the appropriate Collec on and display them by using Iterator and ListIterator interface.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
ListIterator<String> listIterator =
studentList.listIterator(studentList.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
Slip 29
1. Write a Java program to display informa on about all columns in the DONAR table using
ResultSetMetaData.
import java.util.LinkedList;
public class LinkedListOperations {
public static void main(String[] args) {
linkedList.add(10);
linkedList.add(20);
linkedList.add(30);
linkedList.addFirst(5);
linkedList.removeLast();
2. Write a Java program to create LinkedList of integer objects and perform the following: i.
Add element at first posi on ii. Delete last element iii. Display the size of link list
import java.sql.*;
public class DonarTableInfo {
resultSet.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
SQL->
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
2. Write a Java Program for the implementa on of scrollable ResultSet. Assume Teacher table
with a ributes (TID, TName, Salary) is already created.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
try {
connection =
DriverManager.getConnection("jdbc:mysql://localhost/tyjdbc", "root", "root");
statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
resultSet = statement.executeQuery("SELECT * FROM Teacher");
resultSet.last();
resultSet.beforeFirst();
System.out.println("TID\tTName\tSalary");
while (resultSet.next()) {
int tid = resultSet.getInt("TID");
String tname = resultSet.getString("TName");
double salary = resultSet.getDouble("Salary");
System.out.println(tid + "\t" + tname + "\t" + salary);
}
SQL->