Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Name-Abhay Kumar Course-MCA Roll No-03

Q1. Write a java code to create Thread and show the working of yield() and sleep() methods?

public class ThreadDemo {


public static void main(String[] args) {
// Creating two threads
Thread thread1 = new MyThread("Thread 1");
Thread thread2 = new MyThread("Thread 2");

// Starting the threads


thread1.start();
thread2.start();
}
}

class MyThread extends Thread {


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

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " - Count: " + i);

// Using yield() method


Thread.yield();

// Using sleep() method


try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

Q2. Write a java code to implement thread synchronization?

public class ThreadSynchronizationDemo {


public static void main(String[] args) {
Counter counter = new Counter();
// Creating multiple threads
Thread thread1 = new IncrementThread(counter);
Thread thread2 = new IncrementThread(counter);
// Starting the threads
thread1.start();
thread2.start();
// Waiting for the threads to finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Printing the final count
System.out.println("Final count: " + counter.getCount());
}
}

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}
public int getCount() {
return count;
}
}
class IncrementThread extends Thread {
private Counter counter;

public IncrementThread(Counter counter) {


this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
Output:
Name-Abhay Kumar Course-MCA Roll No-03

3.Write a java program to wait main thread till child thread completes its execution using join
and sleep methods?

public class ThreadJoinSleepDemo {


public static void main(String[] args) {
Thread childThread = new ChildThread();
childThread.start();

try {
childThread.join(); // Wait for the child thread to complete
System.out.println("Child thread has completed.");
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Main thread continues its execution.");


}
}

class ChildThread extends Thread {


public void run() {
try {
System.out.println("Child thread is executing.");
Thread.sleep(3000); // Simulating some work in the child thread
System.out.println("Child thread has completed its execution.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output :
Name-Abhay Kumar Course-MCA Roll No-03

4. Write a java program to wait child thread till main thread completes its execution using join
and sleep methods?

public class ThreadJoinSleepDemo {


public static void main(String[] args) {
Thread childThread = new ChildThread();
childThread.start();

try {
// Sleep for some time in the main thread
Thread.sleep(3000);
System.out.println("Main thread has completed its execution.");
} catch (InterruptedException e) {
e.printStackTrace();
}

try {
childThread.join(); // Wait for the child thread to complete
System.out.println("Child thread has completed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class ChildThread extends Thread {


public void run() {
System.out.println("Child thread is waiting for the main thread to complete.");
try {
// Waiting for the completion of the main thread
Thread.currentThread().join();
System.out.println("Child thread has resumed its execution.");
System.out.println("Child thread has completed its execution.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

5. Write a java program to implement multithreading using Runnable interface


Assume Student table in Myql/oracle database and implement the following programs
Program to fetch student details from the database using multithreading:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class FetchStudentDetails implements Runnable {


public void run() {
try {
// Database connection setup
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
Statement statement = connection.createStatement();

// Fetch student details query


String query = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(query);

// Process and display student details


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Student ID: " + id + ", Name: " + name + ", Age: " + age);
}

// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


FetchStudentDetails fetchStudentDetails = new FetchStudentDetails();
Thread thread = new Thread(fetchStudentDetails);
thread.start();
}
}
Name-Abhay Kumar Course-MCA Roll No-03

Output:

Program to insert a new student into the database using multithreading:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertStudent implements Runnable {


public void run() {
try {
// Database connection setup
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
Statement statement = connection.createStatement();

// Insert student query


String query = "INSERT INTO student (name, age) VALUES ('John Doe', 20)";
statement.executeUpdate(query);

System.out.println("New student inserted successfully.");

// Close resources
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
InsertStudent insertStudent = new InsertStudent();
Thread thread = new Thread(insertStudent);
thread.start();
}
}
Output:
Name-Abhay Kumar Course-MCA Roll No-03

Program to update a student's age in the database using multithreading:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdateStudentAge implements Runnable {


public void run() {
try {
// Database connection setup
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
Statement statement = connection.createStatement();

// Update student age query


String query = "UPDATE student SET age = 21 WHERE id = 1";
statement.executeUpdate(query);

System.out.println("Student age updated successfully.");

// Close resources
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


UpdateStudentAge updateStudentAge = new UpdateStudentAge();
Thread thread = new Thread(updateStudentAge);
thread.start();
}
}

Output :
Name-Abhay Kumar Course-MCA Roll No-03

6. Write a JDBC program to insert data into Student table using Statement interface ?

import java.sql.*;

public class InsertDataUsingStatement {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// SQL query to insert data


String sql = "INSERT INTO Student (id, name, age) VALUES (1, 'John Doe', 20)";

// Execute the SQL query


stmt.executeUpdate(sql);
System.out.println("Data inserted successfully.");

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
Name-Abhay Kumar Course-MCA Roll No-03

se.printStackTrace();
}
}
}
}
Output:
Name-Abhay Kumar Course-MCA Roll No-03

7. Write a JDBC program to fetch all the rows from Student table using Statement interface?

import java.sql.*;

public class FetchDataUsingStatement {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// SQL query to fetch data


String sql = "SELECT * FROM Student";

// Execute the SQL query


ResultSet rs = stmt.executeQuery(sql);

// Process the result set


while (rs.next()) {
// Retrieve data by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");

// Display the data


System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("--------------------");
}

// Close the result set


rs.close();
Name-Abhay Kumar Course-MCA Roll No-03

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

8. Write a JDBC program to fetch specific row Student table using Statement interface and
absolute() method?

import java.sql.*;

public class FetchSpecificRowUsingStatement {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// SQL query to fetch specific row


String sql = "SELECT * FROM Student";

// Execute the SQL query


ResultSet rs = stmt.executeQuery(sql);

// Move the cursor to the third row


if (rs.absolute(3)) {
// Retrieve data by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");

// Display the data


System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
} else {
System.out.println("No record found at the specified position.");
}

// Close the result set


rs.close();
Name-Abhay Kumar Course-MCA Roll No-03

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

9. Write a JDBC program to insert multiple records in Student table using PreparedStatement
interface and Scanner class ?

import java.sql.*;

public class FetchSpecificRowUsingStatement {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// SQL query to fetch specific row


String sql = "SELECT * FROM Student";

// Execute the SQL query


ResultSet rs = stmt.executeQuery(sql);

// Move the cursor to the third row


if (rs.absolute(3)) {
// Retrieve data by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");

// Display the data


System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
} else {
System.out.println("No record found at the specified position.");
}

// Close the result set


rs.close();
Name-Abhay Kumar Course-MCA Roll No-03

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

10 . Write a JDBC program to perform following operation in Student table


i -insert
ii- update row
iii delete row
using bath update

import java.sql.*;

public class BatchUpdateOperations {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// Set auto-commit to false


conn.setAutoCommit(false);

// Insert operation
String insertSql = "INSERT INTO Student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
insertStmt.setInt(1, 1);
insertStmt.setString(2, "John Doe");
insertStmt.setInt(3, 20);
insertStmt.addBatch();

// Update operation
String updateSql = "UPDATE Student SET age = ? WHERE id = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
updateStmt.setInt(1, 25);
updateStmt.setInt(2, 1);
updateStmt.addBatch();

// Delete operation
String deleteSql = "DELETE FROM Student WHERE id = ?";
Name-Abhay Kumar Course-MCA Roll No-03

PreparedStatement deleteStmt = conn.prepareStatement(deleteSql);


deleteStmt.setInt(1, 1);
deleteStmt.addBatch();

// Execute batch updates


int[] insertResult = insertStmt.executeBatch();
int[] updateResult = updateStmt.executeBatch();
int[] deleteResult = deleteStmt.executeBatch();

// Commit the transaction


conn.commit();

// Print the result


System.out.println("Insert: " + insertResult.length + " row(s) affected.");
System.out.println("Update: " + updateResult.length + " row(s) affected.");
System.out.println("Delete: " + deleteResult.length + " row(s) affected.");

} catch (SQLException se) {


// Rollback the transaction
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Rollback the transaction
if (conn != null) {
try {
conn.rollback();
} catch (SQLException se) {
se.printStackTrace();
}
}
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
Name-Abhay Kumar Course-MCA Roll No-03

}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

11. Write a JDBC program demonstrate transaction management?

import java.sql.*;

public class TransactionManagementDemo {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Set auto-commit to false


conn.setAutoCommit(false);

// Create a statement
stmt = conn.createStatement();

// Perform database operations within a transaction


try {
// Insert operation
String insertSql = "INSERT INTO Student (id, name, age) VALUES (1, 'John Doe', 20)";
stmt.executeUpdate(insertSql);

// Update operation
String updateSql = "UPDATE Student SET age = 25 WHERE id = 1";
stmt.executeUpdate(updateSql);

// Delete operation
String deleteSql = "DELETE FROM Student WHERE id = 1";
stmt.executeUpdate(deleteSql);

// Commit the transaction


conn.commit();

System.out.println("Transaction completed successfully.");


} catch (SQLException se) {
// Rollback the transaction
conn.rollback();
Name-Abhay Kumar Course-MCA Roll No-03

System.out.println("Transaction rolled back due to an error.");


se.printStackTrace();
}

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

12. Create a stored procedure getName(IN,OUT) invoke the procedure using Callable
Statement?

import java.sql.*;

public class StoredProcedureDemo {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
CallableStatement cstmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a CallableStatement
String sql = "{CALL getName(?, ?)}";
cstmt = conn.prepareCall(sql);

// Set the input parameter


int id = 1;
cstmt.setInt(1, id);

// Register the output parameter


cstmt.registerOutParameter(2, Types.VARCHAR);

// Execute the stored procedure


cstmt.execute();

// Retrieve the output parameter value


String name = cstmt.getString(2);

// Display the result


System.out.println("Name for ID " + id + ": " + name);

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
Name-Abhay Kumar Course-MCA Roll No-03

} finally {
// Close resources
try {
if (cstmt != null)
cstmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output :
Name-Abhay Kumar Course-MCA Roll No-03

13. Create a stored procedure updateMarks(IN,IN) invoke the procedure using Callable
Statement?

import java.sql.*;

public class StoredProcedureDemo {


// JDBC driver and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";

// Database credentials
static final String USER = "your_username";
static final String PASS = "your_password";

public static void main(String[] args) {


Connection conn = null;
CallableStatement cstmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a CallableStatement
String sql = "{CALL updateMarks(?, ?)}";
cstmt = conn.prepareCall(sql);

// Set the input parameters


int studentId = 1;
int newMarks = 85;
cstmt.setInt(1, studentId);
cstmt.setInt(2, newMarks);

// Execute the stored procedure


cstmt.execute();

// Display the result


System.out.println("Marks updated successfully for student ID: " + studentId);

} catch (SQLException se) {


// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (cstmt != null)
Name-Abhay Kumar Course-MCA Roll No-03

cstmt.close();
} catch (SQLException se2) {
} // Nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
Output :
Name-Abhay Kumar Course-MCA Roll No-03

14. Create a GUI application to calculate addition and subtraction using swing application?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CalculatorApp extends JFrame implements ActionListener {


private JTextField number1Field, number2Field, resultField;
private JButton addButton, subtractButton;

public CalculatorApp() {
// Set up the JFrame
setTitle("Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4, 2));

// Create the input fields


JLabel number1Label = new JLabel("Number 1:");
number1Field = new JTextField();
JLabel number2Label = new JLabel("Number 2:");
number2Field = new JTextField();
JLabel resultLabel = new JLabel("Result:");
resultField = new JTextField();
resultField.setEditable(false);

// Create the buttons


addButton = new JButton("Add");
subtractButton = new JButton("Subtract");

// Add components to the JFrame


add(number1Label);
add(number1Field);
add(number2Label);
add(number2Field);
add(resultLabel);
add(resultField);
add(addButton);
add(subtractButton);

// Add action listeners to the buttons


addButton.addActionListener(this);
subtractButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
calculateResult(Operation.ADD);
} else if (e.getSource() == subtractButton) {
calculateResult(Operation.SUBTRACT);
Name-Abhay Kumar Course-MCA Roll No-03

}
}
private void calculateResult(Operation operation) {
String number1Text = number1Field.getText();
String number2Text = number2Field.getText();

try {
int number1 = Integer.parseInt(number1Text);
int number2 = Integer.parseInt(number2Text);
int result = 0;

switch (operation) {
case ADD:
result = number1 + number2;
break;
case SUBTRACT:
result = number1 - number2;
break;
}
resultField.setText(Integer.toString(result));

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this, "Invalid input! Please enter valid integers.");
}
}
enum Operation {
ADD,
SUBTRACT
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CalculatorApp app = new CalculatorApp();
app.setVisible(true);
}
});
}
}
Name-Abhay Kumar Course-MCA Roll No-03

Output:
Name-Abhay Kumar Course-MCA Roll No-03

15. Create a GUI application to calculate the number of words and character in JTextArea?

import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}

Output:

import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
Name-Abhay Kumar Course-MCA Roll No-03

l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}

Output :
Name-Abhay Kumar Course-MCA Roll No-03

16. Create a GUI application to demonstrate JRadioButton

import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

17. Create a GUI application to demonstrate MouseListener ?

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
Name-Abhay Kumar Course-MCA Roll No-03

18.Assume login table having username and password fields in mysql / sql. Create a Login
application using swing components. On click login button data from textfield must be matched
from login table and if data matched then print valid user in Jlabel otherwise print invalid user?
Name-Abhay Kumar Course-MCA Roll No-03

19. Write a java program that will return the first half of the string, if the length of the string is
even and return null if the length is odd?

public class StringHalfProgram {


public static String getFirstHalf(String str) {
int length = str.length();
if (length % 2 == 0) {
return str.substring(0, length / 2);
} else {
return null;
}
}

public static void main(String[] args) {


String input1 = "Hello";
String result1 = getFirstHalf(input1);
System.out.println("First half of '" + input1 + "': " + result1);

String input2 = "World";


String result2 = getFirstHalf(input2);
System.out.println("First half of '" + input2 + "': " + result2);
}
}

Output:
Name-Abhay Kumar Course-MCA Roll No-03

20. Write a java program that will concatenate 2 String and return the result. The result should
be in lowercase?
Note: If the concatenation creates a double-char, then one of the character need to be omitted.

public class StringConcatenationProgram {


public static String concatenateStrings(String str1, String str2) {
String result = str1 + str2;

if (result.length() > 1 && result.charAt(0) == result.charAt(1)) {


result = result.substring(1);
}

return result.toLowerCase();
}

public static void main(String[] args) {


String input1 = "Hello";
String input2 = "World";
String result = concatenateStrings(input1, input2);
System.out.println("Input 1: " + input1);
System.out.println("Input 2: " + input2);
System.out.println("Concatenated String: " + result);
}
}

Output :
Name-Abhay Kumar Course-MCA Roll No-03

21. Given a string and return a string made of ‘n’ copies of the first 2 chars of the original string
where ‘n’ is the length of the string?
Example: Demo
o/p DeDeDeDe

public class StringCopiesProgram {


public static String repeatFirstTwoChars(String str) {
if (str.length() < 2) {
return str;
}

String firstTwoChars = str.substring(0, 2);


StringBuilder result = new StringBuilder();

for (int i = 0; i < str.length(); i++) {


result.append(firstTwoChars);
}

return result.toString();
}

public static void main(String[] args) {


String input = "Demo";
String result = repeatFirstTwoChars(input);
System.out.println("Input: " + input);
System.out.println("Output: " + result);
}
}

Output:

You might also like