Program Statement(A): write a program to check switch-case using character datatype.
Code:
class Switch
{
public static void main(String args[])
{
int day=4;
switch(day)
{
case 1:System.out.println("Sunday");
break;
case 2:System.out.println("Monday");
break;
case 3:System.out.println("Tuesday");
break;
case 4:System.out.println("Wednesday");
break;
case 5:System.out.println("Thursday");
break;
case 6:System.out.println("Friday");
break;
case 7:System.out.println("Saturday");
break;
default:System.out.println("Wrong choice!");
break;
}
}
}
Output:
Program Statement(B): Write a program to show the use of all methods of String class.
Code:
class Main
{
public static void main(String args[])
{
String s="Sy";
String s1="Welcome to JPR";
System.out.println(s);
System.out.println(s1);
System.out.println(s1.length());
System.out.println(s1.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s1.startsWith("W"));
System.out.println(s.endsWith("z"));
System.out.println(s1.charAt(2));
System.out.println(s1.substring(1,5));
System.out.println(s1.concat(s));
}
}
Output:
Program Statement(C): Write a program add the two 2*2 matrices.
Code:
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2},
{3, 4}
};
int[][] matrix2 = {
{5, 6},
{7, 8}
};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Sum of the two 2x2 matrices is:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Program Statement(D): Write a program to use different methods of Vector class.
Code:
import java.util.Vector;
public class Example {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Saurabh");
vector.add("Rahul");
vector.add("Mayank");
vector.add("Prabjot");
System.out.println("Added Elements: " + vector);
vector.add(1, "Ankit");
System.out.println("Added Element at index 1 : " + vector);
vector.set(2, "Abhishek");
System.out.println("Update Element at index 2 : " + vector);
vector.remove("Ankit");
System.out.println("Remove Ankit from list : " + vector);
vector.remove(1);
System.out.println("Remove element at index 1 : " + vector);
for (int i = 0; i < vector.size(); i++) {
System.out.println(i + " = " + vector.get(i));
}
System.out.println(vector);
System.out.println(vector);
System.out.println(vector);
System.out.println(vector);
}
}
Output:
Program Statement(E): Develop a program for all the mathematical operations. Use the
constructor for value acceptance.
Code:
import java.util.Scanner;
class MathOperations {
private double num1;
private double num2;
public MathOperations(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
public void performOperations() {
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 * num2));
if (num2 != 0) {
System.out.println("Division: " + (num1 / num2));
System.out.println("Modulus: " + (num1 % num2));
} else {
System.out.println("Division by zero is not allowed.");
System.out.println("Modulus by zero is not allowed.");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double number1 = input.nextDouble();
System.out.print("Enter second number: ");
double number2 = input.nextDouble();
MathOperations calculator = new MathOperations(number1, number2);
calculator.performOperations();
}
}
Output:
Program Statement(F): Develop a program for Hierarchical inheritance.
Code:
class Animal
{
void eat()
{
System.out.println("Eating..");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking..");
}
}
class BabyDog extends Animal
{
void weep()
{
System.out.println("Weeping..");
}
}
public class Main1
{
public static void main(String[] args)
{
BabyDog d1 = new BabyDog();
d1.weep();
d1.eat();
Dog d2 = new Dog();
d2.bark();
}
}
Output:
Program Statement(G): Develop a program to find area of rectangle and circle using
interfaces.
Code:
interface Area
{
double calculateArea();
}
class Rectangle implements Area
{
double length;
double width;
public Rectangle(double length, double width)
{
this.length=length;
this.width=width;
}
public double calculateArea()
{
return length*width;
}
}
class Circle implements Area
{
double radius;
public Circle(double radius)
{
this.radius=radius;
}
public double calculateArea()
{
return Math.PI*radius*radius;
}
}
public class Main
{
public static void main(String[] args)
{
Rectangle rectangle=new Rectangle(5, 4);
Circle circle=new Circle(7);
System.out.println("Area of Rectangle:" + rectangle.calculateArea());
System.out.println("Area of Circle:" + circle. calculateArea());
}
}
Output:
Program Statement(H): Develop a program which consists of the package named
Calculator with a class named Calculate and methods named as add to add two integer
numbers, sub to substract 2 integers & mul to multiply 2 integers. Import Calculator package
in another program (class named Demo) to add, substract & multiply two numbers.
Code:
// In the package file (e.g., Calculator.java within the let_me_calculate directory)
package let_me_calculate;
public class Calculate {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
public int mul(int a, int b) {
return a * b;
}
}
// In another program file (e.g., Demo.java in the same or a different directory)
import let_me_calculate.Calculate;
public class Demo {
public static void main(String[] args) {
Calculate calc = new Calculate();
int num1 = 20;
int num2 = 10;
int sum = calc.add(num1, num2);
int difference = calc.sub(num1, num2);
int product = calc.mul(num1, num2);
System.out.println("First Number: " + num1);
System.out.println("Second Number: " + num2);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
}
}
Output:
Program Statement(I): Develop a program for synchronization.For that create 2 threads as
even & odd & do the synchronization
Code:
class SharedResource {
private boolean isOddTurn = false;
public synchronized void printEven(int num) {
while (isOddTurn) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Even Thread: " + num);
isOddTurn = true;
notify();
}
public synchronized void printOdd(int num) {
while (!isOddTurn) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Odd Thread: " + num);
isOddTurn = false;
notify();
}
}
class EvenThread extends Thread {
private SharedResource resource;
private int start = 2;
public EvenThread(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 5; i++) {
resource.printEven(start);
start += 2;
}
}
}
class OddThread extends Thread {
private SharedResource resource;
private int start = 1;
public OddThread(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 5; i++) {
resource.printOdd(start);
start += 2;
}
}
}
public class SynchronizationDemo {
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
EvenThread evenThread = new EvenThread(sharedResource);
OddThread oddThread = new OddThread(sharedResource);
evenThread.start();
oddThread.start();
}
}
Output:
Program Statement(J): Create three threads and run these threads according to setPriority()
& getPriority().
Code:
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class ThreadPriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
Thread thread3 = new Thread(new MyRunnable(), "Thread 3");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);
System.out.println("Thread 1 priority: " + thread1.getPriority());
System.out.println("Thread 2 priority: " + thread2.getPriority());
System.out.println("Thread 3 priority: " + thread3.getPriority());
thread1.start();
thread2.start();
thread3.start();
}
}
Program Statement(K):Define an exception called “AuthenticationFailureException” that is
thrown when the password is not matches to “Ycp@123”. Write a program that uses this
exceptions.
Code:
import java.util.Scanner;
class AuthenticationFailureException extends Exception
{
public AuthenticationFailureException(String message)
{
super(message);
}
}
public class AuthenticationSystem
{
private static final String CORRECT_PASSWORD="Ycp@123";
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your password:");
String enteredPassword=sc.nextLine();
try
{
if(!enteredPassword.equals(CORRECT_PASSWORD))
{
throw new
AuthenticationFailureException("Authentication
Failure:Incorrect password");
}
else
{
System.out.println("Authentication Successful!");
}
}
catch(AuthenticationFailureException e)
{
System.out.println(e.getMessage());
}
finally
{
sc.close();
}
}
}
Output:
Program Statement(L): Develop a program for user-defined exception
“UnderAgeException” that is thrown when a person is under 18 & not eligible for
voting.
Code:
class UnderAgeException extends Exception {
public UnderAgeException(String message) {
super(message);
}
}
public class VotingEligibility {
public static void checkVotingEligibility(int age) throws UnderAgeException {
if (age < 18) {
throw new UnderAgeException("Person is under 18 and not eligible to
vote.");
} else {
System.out.println("Person is eligible to vote.");
}
}
public static void main(String[] args) {
try {
checkVotingEligibility(17);
} catch (UnderAgeException e) {
System.out.println(e.getMessage());
}
try {
checkVotingEligibility(20);
} catch (UnderAgeException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Program Statement(M): Develop program to select multiple names of newspapers &
show selected names on window. (use List)
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class NewspaperSelectionApp
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Select Newspapers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new BorderLayout());
String[] newspapers = {"The Times", "The Guardian", "The Daily Mail", "The Independent",
"The Sun", "The Telegraph"};
JList<String> newspaperList = new JList<>(newspapers);
newspaperList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTIO
N);
JScrollPane listScrollPane = new JScrollPane(newspaperList);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton showSelectionButton = new JButton("Show Selected Newspapers");
showSelectionButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
java.util.List<String> selectedNewspapers = newspaperList.getSelectedValuesList();
String message = "Selected Newspapers: \n";
if (selectedNewspapers.isEmpty())
{
message += "No newspapers selected.";
}
else
{
for (String newspaper : selectedNewspapers)
{
message += newspaper + "\n";
}
}
JOptionPane.showMessageDialog(frame, message, "Selected Newspapers",
JOptionPane.INFORMATION_MESSAGE);
}
});
panel.add(showSelectionButton, BorderLayout.NORTH);
panel.add(listScrollPane, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
}
}
Output:
Program Statement(N): Write a program which creates Menu of 3 different colors and
display
Code:
import java.awt.*;
import java.awt.event.*;
public class ColorMenuExample extends Frame implements ActionListener
{
public ColorMenuExample()
{
MenuBar menuBar = new MenuBar();
Menu colorMenu = new Menu("Colors");
MenuItem red = new MenuItem("Red");
MenuItem green = new MenuItem("Green");
MenuItem blue = new MenuItem("Blue");
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
colorMenu.add(red);
colorMenu.add(green);
colorMenu.add(blue);
menuBar.add(colorMenu);
setMenuBar(menuBar);
setTitle("Color Menu Example");
setSize(400, 300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
@Override
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
switch (command)
{
case "Red":
setBackground(Color.RED);
break;
case "Green":
setBackground(Color.GREEN);
break;
case "Blue":
setBackground(Color.BLUE);
break;
}
}
public static void main(String[] args)
{
ColorMenuExample colorMenuExample = new ColorMenuExample();
}
}
Output:
Program Statement(O): Develop a program for calculator which show add, sub, mul & div
functions.
Code:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("=================");
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("\nChoose an operation:");
System.out.println("1 - Addition (+)");
System.out.println("2 - Subtraction (-)");
System.out.println("3 - Multiplication (*)");
System.out.println("4 - Division (/)");
System.out.print("Enter your choice (1-4): ");
int choice = scanner.nextInt();
double result;
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
result = num1 / num2;
System.out.println("Result: " + result);
}
break;
default:
System.out.println("Invalid choice. Please select from 1 to 4.");
}
scanner.close();
}
}
Output:
Program Statement(P): Write a Java Program to create a table of Name of Student,
Percentage and Grade of 10 students using JTable.
Code:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Tables
{
Tables()
{
JFrame f=new JFrame();
f.setTitle("JTable Example");
String[][] data=
{
{"1","Anushka Patil","91%","A"},
{"2","Riya Patil","92%","A"},
{"3","Samiksha Patil","86%","A"},
{"4","Tanmayi Patil","89%","A"},
{"5","Pratiksha Pujari","85%","A"},
{"6","Pallavi Shinde","90%","A"},
{"7","Payal Shinde","89%","A"},
{"8","Shrutika Soude","89%","A"},
{"9","Swati Soude","80%","A"},
{"10","Sanika Mali","77%","B"}
};
String[] columnNames={"Sr.No","Student_Name","Percentage","Grade"};
JTable t=new JTable(data,columnNames);
t.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(t);
f.add(sp);
f.setSize(500,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Tables();
}
}
Output:
Program Statement(Q): Write an AWT program perform the addition of two numbers.
(Take 3 labels, 3 textboxes and a button. When click on button it shows the result in textbox)
Code:
import java.awt.*;
import java.awt.event.*;
public class AdditionCalculator extends Frame
{
TextField num1Field, num2Field, resultField;
Button addButton;
public AdditionCalculator()
{
setTitle("Addition Calculator");
setSize(300, 200);
setLayout(new FlowLayout());
Label num1Label = new Label("Number 1:");
Label num2Label = new Label("Number 2:");
Label resultLabel = new Label("Result:");
num1Field = new TextField(10);
num2Field = new TextField(10);
resultField = new TextField(10);
resultField.setEditable(false);
addButton = new Button("Add");
addButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 + num2;
resultField.setText(String.valueOf(result));
}
catch (NumberFormatException ex)
{
resultField.setText("Invalid Input");
}
}
});
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(addButton);
add(resultLabel);
add(resultField);
setVisible(true);
}
public static void main(String[] args)
{
new AdditionCalculator();
}
}
Output:
Program Statement(R): Develop a program using InetAddress class which uses different
methods.
Code:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
public class InetAddressExample12 {
public static void main(String[] args) {
String host = "www.google.com";
try {
InetAddress address = InetAddress.getByName(host);
System.out.println("Hostname: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
boolean reachable = address.isReachable(5000);
System.out.println("Is Reachable: " + reachable);
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
}
}
Output:
Program Statement(S): Write a program using URL class to retrieve the host,protocol,port
and file of URL http://www.msbte.org.in
Code:
import java.net.MalformedURLException;
import java.net.URL;
public class URLInfo
{
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.msbte.org.in");
System.out.println("Protocol:"+url.getProtocol());
System.out.println("Host:"+url.getHost());
System.out.println("Port:"+url.getPort());
System.out.println("File:"+url.getPath());
}
catch(MalformedURLException e)
{
System.out.println("An error occurred:"+e.getMessage());
}
}
}
Output:
Program Statement(T): Write a program using Socket and SeverSocket to create Chat
application.
Code:
Client side:-
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientExample
{
public static void main(String[] args)
{
String message;
Scanner sc=new Scanner(System.in);
try
{
Socket socket=new Socket("localhost",5000);
System.out.println("Connected with Server");
System.out.println("Enter a message:");
message=sc.nextLine();
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
dout.writeUTF(message);
dout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Server Side:-
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerExample
{
public static void main(String[] args)
{
try
{
ServerSocket s=new ServerSocket(5000);
System.out.println("Waiting for client connection....");
Socket socket=s.accept();
System.out.println("client connected....");
DataInputStream dis=new DataInputStream(socket.getInputStream());
String message=(String)dis.readUTF();
System.out.println("Client message:"+message);
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output:
Program Statement(U): Develop a program to update a record in database table
Source Code:
import java.sql.*;
import java.util.Scanner;
public class UpdateEmployeeSalary {
private static final String DB_URL = "jdbc:mysql://localhost:3306/newdb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "riya@3227#vp;";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter ID to update: ");
int idToUpdate = scanner.nextInt();
System.out.print("Enter new salary: ");
double newSalary = scanner.nextDouble();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
String updateSql = "UPDATE employees SET salary = " + newSalary + "
WHERE id = " + idToUpdate;
int updatedRows = stmt.executeUpdate(updateSql);
if (updatedRows > 0) {
System.out.println("Updated ID " + idToUpdate + " with salary " +
newSalary);
String selectSql = "SELECT id, name, salary FROM employees";
rs = stmt.executeQuery(selectSql);
System.out.println("\nEmployee Table:");
while (rs.next()) {
System.out.println(rs.getInt("id") + ", " + rs.getString("name") + ", " +
rs.getDouble("salary"));
}
} else {
System.out.println("No employee found with ID " + idToUpdate);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) {}
try { if (stmt != null) stmt.close(); } catch (SQLException e) {}
try { if (conn != null) conn.close(); } catch (SQLException e) {}
scanner.close();
}
}
}
Output:
Program Statement(V): Write program to retrieve data from database table
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrieveEmployeeData {
private static final String DB_URL = "jdbc:mysql://localhost:3306/newdb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "riya@3227#vp;";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
System.out.println("Connected to the database!");
String sql = "SELECT id, name, salary FROM employees";
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
System.out.println("Employee Data:");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double salary = resultSet.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name + ", Salary: " + salary);
}
} catch (SQLException e) {
System.err.println("Error retrieving data: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
e.printStackTrace();
}
}
}
}
Output:
Program Statement(W): Develop a program to insert the record to the database using
preparedStatement.
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class InsertEmployeePreparedStatement {
private static final String DB_URL = "jdbc:mysql://localhost:3306/newdb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "riya@3227#vp;";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
Scanner scanner = new Scanner(System.in);
try {
connection = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
String sql = "INSERT INTO employees (id, name, salary) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
System.out.print("Enter employee ID: ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter employee name: ");
String name = scanner.nextLine();
System.out.print("Enter employee salary: ");
double salary = scanner.nextDouble();
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setDouble(3, salary);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new employee has been inserted successfully!");
} else {
System.out.println("Failed to insert the employee.");
}
} catch (SQLException e) {
System.err.println("Error inserting data: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
e.printStackTrace();
}
}
scanner.close();
}
}
Output: