JAVA Practicals
JAVA Practicals
int sum = 0;
sum += num;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
(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 {
this.name = name;
this.age = age;
this.jobTitle = jobTitle;
this.salary = salary;
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;
this.dimension1 = dimension1;
this.dimension2 = dimension2;
// Rectangle class
// Constructor
super(length, width);
@Override
void printArea() {
// Triangle class
// Constructor
super(base, height);
@Override
void printArea() {
}
// Circle class
@Override
void printArea() {
// Main class
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
@Override
File: C1.java
import pl.A;
import pl.MyClass;
public class C1 {
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;
this.sharedData = sharedData;
@Override
public void run() {
while (true) {
sharedData.setNumber(number);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("RandomNumberGenerator interrupted");
this.sharedData = sharedData;
@Override
while (true) {
synchronized (sharedData) {
sharedData.clearNumber();
}
class CubeCalculator extends Thread {
this.sharedData = sharedData;
@Override
while (true) {
synchronized (sharedData) {
sharedData.clearNumber();
class SharedData {
this.number = number;
return number;
}
public synchronized void clearNumber() {
number = null;
// Main class
// Create threads
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 CalculatorApp() {
frame = new JFrame("Simple Calculator");
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() {
performOperation('+');
});
subtractButton.addActionListener(new ActionListener() {
performOperation('-');
});
multiplyButton.addActionListener(new ActionListener() {
performOperation('*');
}
});
divideButton.addActionListener(new ActionListener() {
performOperation('/');
});
clearButton.addActionListener(new ActionListener() {
textField.setText("");
resultLabel.setText("Result: ");
});
frame.setVisible(true);
try {
if (operands.length != 2) {
double result = 0;
switch (operation) {
case '+':
case '-':
break;
case '*':
break;
case '/':
if (num2 == 0) {
break;
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 TrafficLightSimulator() {
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
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() {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
});
yellowButton.addActionListener(new ActionListener() {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
});
greenButton.addActionListener(new ActionListener() {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
});
frame.setVisible(true);
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;
bufferedWriter.write(userInput);
bufferedWriter.newLine();
} catch (IOException e) {
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;
loadPhoneBookFromFile("phonebook.txt");
if (isPhoneNumber(input)) {
if (name != null) {
} else {
} else {
if (phoneNumber != null) {
} else {
scanner.close();
String line;
if (record.length == 2) {
phoneBook.put(name, phoneNumber);
phoneBook.put(phoneNumber, name);
}
}
} catch (IOException e) {
e.printStackTrace();
return input.matches("\\d+");
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 MySQLDatabaseHandler() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
e.printStackTrace();
System.out.print(metaData.getColumnName(i) + "\t");
System.out.println("\n-------------------------------");
while (resultSet.next()) {
System.out.print(resultSet.getString(i) + "\t");
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if (connection != null) {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("\nInserting data:");
System.out.println("\nDeleting data:");
dbHandler.closeConnection();
---END---