Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

JAVA Practicals

Uploaded by

roohibashir454
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JAVA Practicals

Uploaded by

roohibashir454
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

(1) Write a program in java to find the sum of two numbers.

Create and initializes


an int array, calculate and display the average of its values in average method.

public class SimpleProgram {

public static double average(int[] numbers) {

int sum = 0;

for (int num : numbers) {

sum += num;

return (double) sum / numbers.length;

public static void main(String[] args) {

int num1 = 10;

int num2 = 20;

int sum = num1 + num2;

System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

int[] array = {5, 10, 15, 20, 25};

double avg = average(array);

System.out.println("Average of the array values is: " + avg);

(2) Write a Program in java to implement inheritance. Create a class called Employee
whose objects are records for an employee. This class will be a derived class of the class
Person.

class Person {

private String name;

private int age;


public Person(String name, int age) {

this.name = name;

this.age = age;

public void displayPersonDetails() {

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

System.out.println("Age: " + age);

class Employee extends Person {

private String jobTitle;

private double salary;

public Employee(String name, int age, String jobTitle, double salary) {

super(name, age); // Call the constructor of the base class

this.jobTitle = jobTitle;

this.salary = salary;

public void displayEmployeeDetails() {

displayPersonDetails(); // Call the method from the base class

System.out.println("Job Title: " + jobTitle);

System.out.println("Salary: $" + salary);

public class InheritanceExample {

public static void main(String[] args) {

Employee emp = new Employee("Ali", 30, "Software Engineer", 75000);

emp.displayEmployeeDetails();

(3) Write a Java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). Provide three classes named
Rectangle, Triangle, and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print
Area () that prints the area of the given shape.
abstract class Shape {

int dimension1;

int dimension2;

public Shape(int dimension1, int dimension2) {

this.dimension1 = dimension1;

this.dimension2 = dimension2;

abstract void printArea();

// Rectangle class

class Rectangle extends Shape {

// Constructor

public Rectangle(int length, int width) {

super(length, width);

@Override

void printArea() {

int area = dimension1 * dimension2;

System.out.println("Rectangle Area: " + area);

// Triangle class

class Triangle extends Shape {

// Constructor

public Triangle(int base, int height) {

super(base, height);

@Override

void printArea() {

double area = 0.5 * dimension1 * dimension2;

System.out.println("Triangle Area: " + area);

}
// Circle class

class Circle extends Shape {

public Circle(int radius) {

super(radius, 0); // Only one dimension is needed for a circle

@Override

void printArea() {

double area = Math.PI * dimension1 * dimension1; // πr²

System.out.println("Circle Area: " + area);

// Main class

public class ShapeTest {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle(10, 5);

Triangle triangle = new Triangle(6, 8);

Circle circle = new Circle(7);

rectangle.printArea();

triangle.printArea();

circle.printArea();

(4) Write a program to create interface A. In this interface we have two method meth1
and meth2. Implements this interface in another class named MyClass. Create a
package named pl and implement
this package in c1 class.
File: pl/A.java

package pl;

public interface A {

void meth1();

void meth2();

File: pl/MyClass.java

package pl;
public class MyClass implements A {

@Override

public void meth1() {

System.out.println("Method meth1 implemented in MyClass.");

@Override

public void meth2() {

System.out.println("Method meth2 implemented in MyClass.");

File: C1.java

import pl.A;

import pl.MyClass;

public class C1 {

public static void main(String[] args) {

A obj = new MyClass();

obj.meth1();

obj.meth2();

(5) Write a Java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.

import java.util.Random;

class RandomNumberGenerator extends Thread {

private SharedData sharedData;

public RandomNumberGenerator(SharedData sharedData) {

this.sharedData = sharedData;

@Override
public void run() {

Random random = new Random();

while (true) {

int number = random.nextInt(100);

sharedData.setNumber(number);

System.out.println("Generated Number: " + number);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("RandomNumberGenerator interrupted");

class SquareCalculator extends Thread {

private SharedData sharedData;

public SquareCalculator(SharedData sharedData) {

this.sharedData = sharedData;

@Override

public void run() {

while (true) {

synchronized (sharedData) {

if (sharedData.hasNumber() && sharedData.getNumber() % 2 == 0) {

int number = sharedData.getNumber();

System.out.println("Square of " + number + " is: " + (number * number));

sharedData.clearNumber();

}
class CubeCalculator extends Thread {

private SharedData sharedData;

public CubeCalculator(SharedData sharedData) {

this.sharedData = sharedData;

@Override

public void run() {

while (true) {

synchronized (sharedData) {

if (sharedData.hasNumber() && sharedData.getNumber() % 2 != 0) {

int number = sharedData.getNumber();

System.out.println("Cube of " + number + " is: " + (number * number * number));

sharedData.clearNumber();

class SharedData {

private Integer number;

public synchronized void setNumber(int number) {

this.number = number;

public synchronized int getNumber() {

return number;

public synchronized boolean hasNumber() {

return number != null;

}
public synchronized void clearNumber() {

number = null;

// Main class

public class MultiThreadApp {

public static void main(String[] args) {

SharedData sharedData = new SharedData();

// Create threads

RandomNumberGenerator randomNumberGenerator = new RandomNumberGenerator(sharedData);

SquareCalculator squareCalculator = new SquareCalculator(sharedData);

CubeCalculator cubeCalculator = new CubeCalculator(sharedData);

randomNumberGenerator.start();

squareCalculator.start();

cubeCalculator.start();

(6) Write a Java program that creates a user interface to perform various
mathematical operations. Use exception handling for handling various errors.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.text.DecimalFormat;

public class CalculatorApp {

private JFrame frame;

private JTextField textField;

private JButton addButton, subtractButton, multiplyButton, divideButton, clearButton;

private JLabel resultLabel;

public CalculatorApp() {
frame = new JFrame("Simple Calculator");

textField = new JTextField(20);

addButton = new JButton("+");

subtractButton = new JButton("-");

multiplyButton = new JButton("*");

divideButton = new JButton("/");

clearButton = new JButton("Clear");

resultLabel = new JLabel("Result: ");

frame.setLayout(new FlowLayout());

frame.setSize(250, 250);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(textField);

frame.add(addButton);

frame.add(subtractButton);

frame.add(multiplyButton);

frame.add(divideButton);

frame.add(clearButton);

frame.add(resultLabel);

addButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

performOperation('+');

});

subtractButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

performOperation('-');

});

multiplyButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

performOperation('*');

}
});

divideButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

performOperation('/');

});

clearButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

textField.setText("");

resultLabel.setText("Result: ");

});

frame.setVisible(true);

// Method to perform the mathematical operation

private void performOperation(char operation) {

try {

String input = textField.getText();

String[] operands = input.split(" ");

if (operands.length != 2) {

throw new IllegalArgumentException("Please enter two numbers separated by a space.");

double num1 = Double.parseDouble(operands[0]);

double num2 = Double.parseDouble(operands[1]);

double result = 0;

switch (operation) {

case '+':

result = num1 + num2;


break;

case '-':

result = num1 - num2;

break;

case '*':

result = num1 * num2;

break;

case '/':

if (num2 == 0) {

throw new ArithmeticException("Cannot divide by zero.");

result = num1 / num2;

break;

DecimalFormat df = new DecimalFormat("0.00");

resultLabel.setText("Result: " + df.format(result));

} catch (NumberFormatException ex) {

resultLabel.setText("Error: Invalid input. Please enter valid numbers.");

} catch (IllegalArgumentException | ArithmeticException ex) {

resultLabel.setText("Error: " + ex.getMessage());

} catch (Exception ex) {

resultLabel.setText("Unexpected error: " + ex.getMessage());

public static void main(String[] args) {

// Create the GUI application

new CalculatorApp();

(7) Write a Java program that simulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with “Stop” or “Ready” or “Go” should appear above the buttons
in selected color.
import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class TrafficLightSimulator {

private JFrame frame;

private JRadioButton redButton, yellowButton, greenButton;

private ButtonGroup buttonGroup;

private JLabel messageLabel;

public TrafficLightSimulator() {

frame = new JFrame("Traffic Light Simulator");

redButton = new JRadioButton("Red");

yellowButton = new JRadioButton("Yellow");

greenButton = new JRadioButton("Green");

buttonGroup = new ButtonGroup();

buttonGroup.add(redButton);

buttonGroup.add(yellowButton);

buttonGroup.add(greenButton);

messageLabel = new JLabel("Select a light");

messageLabel.setFont(new Font("Arial", Font.BOLD, 16));

messageLabel.setHorizontalAlignment(SwingConstants.CENTER);

frame.setLayout(new FlowLayout());

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(messageLabel);

frame.add(redButton);

frame.add(yellowButton);

frame.add(greenButton);

redButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);

});

yellowButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

messageLabel.setText("Ready");

messageLabel.setForeground(Color.YELLOW);

});

greenButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

messageLabel.setText("Go");

messageLabel.setForeground(Color.GREEN);

});

// Display the frame

frame.setVisible(true);

public static void main(String[] args) {

// Create an instance of the TrafficLightSimulator class

new TrafficLightSimulator();

(8) Write a program to get the input from the user and store it into file.

import java.io.*;

import java.util.Scanner;

public class StoreInputToFile {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the data to store in the file:");

String userInput = scanner.nextLine();

File file = new File("user_input.txt");

try (FileWriter writer = new FileWriter(file, true);

BufferedWriter bufferedWriter = new BufferedWriter(writer)) {

// Write the user input to the file

bufferedWriter.write(userInput);

bufferedWriter.newLine();

System.out.println("Data has been written to the file successfully!");

} catch (IOException e) {

System.out.println("An error occurred while writing to the file.");

e.printStackTrace();

} finally {

scanner.close();

(9) Write a Java program that loads names and phone numbers from a text file where the data
is organized as one line per record and each field in a record are separated by a tab (\t). It
takes
a name or phone number as input and prints the corresponding other value from the hash
table.
import java.io.*;

import java.util.HashMap;

import java.util.Scanner;

public class PhoneBook {

private static HashMap<String, String> phoneBook = new HashMap<>();


public static void main(String[] args) {

loadPhoneBookFromFile("phonebook.txt");

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a name or phone number:");

String input = scanner.nextLine();

if (isPhoneNumber(input)) {

String name = phoneBook.get(input);

if (name != null) {

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

} else {

System.out.println("No record found for the given phone number.");

} else {

String phoneNumber = getPhoneNumberFromName(input);

if (phoneNumber != null) {

System.out.println("Phone Number: " + phoneNumber);

} else {

System.out.println("No record found for the given name.");

scanner.close();

private static void loadPhoneBookFromFile(String filename) {

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {

String line;

while ((line = reader.readLine()) != null) {

String[] record = line.split("\t");

if (record.length == 2) {

String name = record[0].trim();

String phoneNumber = record[1].trim();

// Store name and phone number in the HashMap

phoneBook.put(name, phoneNumber);

phoneBook.put(phoneNumber, name);

}
}

} catch (IOException e) {

System.out.println("Error reading the file.");

e.printStackTrace();

private static boolean isPhoneNumber(String input) {

return input.matches("\\d+");

private static String getPhoneNumberFromName(String name) {

return phoneBook.get(name);

(10) Create a class to connect to the MySQL database and perform queries, inserts and
deletes. It also
prints the metadata (table name, column names) of a query result.
import java.sql.*;

public class MySQLDatabaseHandler {

private static final String URL = "jdbc:mysql://localhost:3306/your_database_name";

private static final String USER = "your_username";

private static final String PASSWORD = "your_password";

private Connection connection;

public MySQLDatabaseHandler() {

try {

// Load the MySQL JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection

connection = DriverManager.getConnection(URL, USER, PASSWORD);

System.out.println("Database connection established successfully!");


} catch (Exception e) {

System.out.println("Error connecting to the database.");

e.printStackTrace();

public void executeQuery(String query) {

try (Statement statement = connection.createStatement();

ResultSet resultSet = statement.executeQuery(query)) {

ResultSetMetaData metaData = resultSet.getMetaData();

int columnCount = metaData.getColumnCount();

System.out.println("Query Result Metadata:");

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

System.out.print(metaData.getColumnName(i) + "\t");

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

while (resultSet.next()) {

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

System.out.print(resultSet.getString(i) + "\t");

System.out.println();

} catch (SQLException e) {

System.out.println("Error executing the query.");

e.printStackTrace();

public void executeUpdate(String query) {

try (Statement statement = connection.createStatement()) {

int rowsAffected = statement.executeUpdate(query);

System.out.println("Rows affected: " + rowsAffected);

} catch (SQLException e) {

System.out.println("Error executing update.");

e.printStackTrace();

}
}

public void closeConnection() {

try {

if (connection != null) {

connection.close();

System.out.println("Database connection closed.");

} catch (SQLException e) {

System.out.println("Error closing the connection.");

e.printStackTrace();

public static void main(String[] args) {

MySQLDatabaseHandler dbHandler = new MySQLDatabaseHandler();

System.out.println("\nExecuting SELECT query:");

dbHandler.executeQuery("SELECT * FROM your_table_name");

System.out.println("\nInserting data:");

dbHandler.executeUpdate("INSERT INTO your_table_name (column1, column2) VALUES ('value1', 'value2')");

System.out.println("\nDeleting data:");

dbHandler.executeUpdate("DELETE FROM your_table_name WHERE column1 = 'value1'");

dbHandler.closeConnection();

---END---

You might also like