Time: 3 Hours
1.Write a program using swing to accept values in two textboxes and display the
results of mathematical operations in third text box. Use four buttons add,
subtract, multiply and divide.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorApplet extends JApplet {
// Declare components
private JTextField text1, text2, resultField;
private JButton addButton, subtractButton, multiplyButton, divideButton;
public void init() {
// Set layout
setLayout(new FlowLayout());
// Create components
text1 = new JTextField(10);
text2 = new JTextField(10);
resultField = new JTextField(15);
resultField.setEditable(false);
addButton = new JButton("Add");
subtractButton = new JButton("Subtract");
multiplyButton = new JButton("Multiply");
divideButton = new JButton("Divide");
// Add components to the applet
add(new JLabel("Enter first number:"));
add(text1);
add(new JLabel("Enter second number:"));
add(text2);
add(new JLabel("Result:"));
add(resultField);
Time: 3 Hours
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
// Add ActionListener for the Add button
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation("add");
}
});
// Add ActionListener for the Subtract button
subtractButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation("subtract");
}
});
// Add ActionListener for the Multiply button
multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation("multiply");
}
});
// Add ActionListener for the Divide button
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation("divide");
}
});
}
private void performOperation(String operation) {
try {
// Get the numbers from the text fields
double num1 = Double.parseDouble(text1.getText());
double num2 = Double.parseDouble(text2.getText());
double result = 0;
Time: 3 Hours
// Perform the selected operation
if (operation.equals("add")) {
result = num1 + num2;
} else if (operation.equals("subtract")) {
result = num1 - num2;
} else if (operation.equals("multiply")) {
result = num1 * num2;
} else if (operation.equals("divide")) {
if (num2 != 0) {
result = num1 / num2;
} else {
resultField.setText("Error: Div by 0");
return;
}
}
// Display the result
resultField.setText(String.valueOf(result));
} catch (NumberFormatException e) {
resultField.setText("Invalid input");
}
}
}
2.Create a class called Matrix which contains a two dimensional integer array,
m, n (order of the matrix) as data members. Include the following member
functions
• To read the matrix
• To display the matrix
• To find the transpose of the matrix.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Time: 3 Hours
class Matrix {
private int[][] matrix; // Two-dimensional array for matrix
private int rows, cols; // Rows and columns of the matrix
// Constructor to initialize matrix order
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
matrix = new int[rows][cols];
}
// Function to read the matrix
public void readMatrix() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements of the matrix (" + rows + "x" + cols + "):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Element [" + i + "][" + j + "]: ");
matrix[i][j] = Integer.parseInt(reader.readLine());
}
}
}
// Function to display the matrix
public void displayMatrix() {
System.out.println("Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// Function to find and display the transpose of the matrix
public void transposeMatrix() {
System.out.println("Transpose of the Matrix:");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
Time: 3 Hours
}
}
// Main method to test the functionality
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Read matrix order from the user
System.out.print("Enter the number of rows: ");
int rows = Integer.parseInt(reader.readLine());
System.out.print("Enter the number of columns: ");
int cols = Integer.parseInt(reader.readLine());
// Create a Matrix object
Matrix matrix = new Matrix(rows, cols);
// Read, display, and transpose the matrix
matrix.readMatrix();
matrix.displayMatrix();
matrix.transposeMatrix();
}
}
3.Write an applet program to display the national flag of India.
import java.applet.Applet;
import java.awt.*;
public class IndianFlagApplet extends Applet {
public void paint(Graphics g) {
// Set the dimensions of the flag
int x = 50, y = 50; // Top-left corner of the flag
int width = 300, height = 60; // Width and height of each stripe
// Draw the saffron stripe
Time: 3 Hours
g.setColor(Color.ORANGE);
g.fillRect(x, y, width, height);
// Draw the white stripe
g.setColor(Color.WHITE);
g.fillRect(x, y + height, width, height);
// Draw the green stripe
g.setColor(Color.GREEN);
g.fillRect(x, y + 2 * height, width, height);
// Draw the Ashoka Chakra
int chakraX = x + width / 2 - height / 4; // Centered horizontally
int chakraY = y + height + height / 4; // Centered in the white stripe
int chakraRadius = height / 2; // Diameter of the Ashoka Chakra
g.setColor(Color.BLUE);
g.drawOval(chakraX, chakraY, chakraRadius, chakraRadius);
// Draw spokes of the Ashoka Chakra
int spokes = 24;
double angleStep = 2 * Math.PI / spokes;
int centerX = chakraX + chakraRadius / 2;
int centerY = chakraY + chakraRadius / 2;
for (int i = 0; i < spokes; i++) {
double angle = i * angleStep;
int x1 = (int) (centerX + Math.cos(angle) * (chakraRadius / 4));
int y1 = (int) (centerY + Math.sin(angle) * (chakraRadius / 4));
int x2 = (int) (centerX + Math.cos(angle) * (chakraRadius / 2));
int y2 = (int) (centerY + Math.sin(angle) * (chakraRadius / 2));
g.drawLine(x1, y1, x2, y2);
Time: 3 Hours
}
}
}
OR
import java.applet.Applet;
import java.awt.*;
public class IndianFlagApplet extends Applet {
public void paint(Graphics g) {
int x = 50, y = 50; // Top-left corner of the flag
int width = 300, height = 60; // Width and height of each stripe
// Draw the saffron stripe
g.setColor(Color.ORANGE);
g.fillRect(x, y, width, height);
// Draw the white stripe
g.setColor(Color.WHITE);
g.fillRect(x, y + height, width, height);
// Draw the green stripe
g.setColor(Color.GREEN);
g.fillRect(x, y + 2 * height, width, height);
// Draw the Ashoka Chakra (simplified as a blue circle)
int chakraX = x + width / 2 - height / 4;
int chakraY = y + height + height / 4;
int chakraRadius = height / 2;
g.setColor(Color.BLUE);
Time: 3 Hours
g.drawOval(chakraX, chakraY, chakraRadius, chakraRadius);
}
}
4.Create a class Student with attributes roll no, name, age and course. If age of
student is not in between 15 and 21 then generate user-defined exception
“AgeNotWithinRangeException”. If name contains numbers or special symbols
raise exception “NameNotValidException”. Define the two exception classes.
// Custom exception for age out of range
class AgeNotWithinRangeException extends Exception {
public AgeNotWithinRangeException(String message) {
super(message);
}
}
// Custom exception for invalid name
class NameNotValidException extends Exception {
public NameNotValidException(String message) {
super(message);
}
}
class Student {
int rollNo;
String name;
int age;
String course;
// Constructor
public Student(int rollNo, String name, int age, String course) throws
AgeNotWithinRangeException, NameNotValidException {
this.rollNo = rollNo;
this.name = name;
this.age = age;
Time: 3 Hours
this.course = course;
if (age < 15 || age > 21) {
throw new AgeNotWithinRangeException("Age should be between 15 and 21.");
}
if (!name.matches("^[a-zA-Z\\s]+$")) {
throw new NameNotValidException("Name should not contain numbers or special
characters.");
}
}
// Method to display student details
public void display() {
System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
public static void main(String[] args) {
try {
Student student1 = new Student(1, "John Doe", 20, "Computer Science");
student1.display();
Student student2 = new Student(2, "Jane123", 22, "Mechanical Engineering");
} catch (AgeNotWithinRangeException | NameNotValidException e) {
System.out.println(e.getMessage());
}
}
}
5.Write a java program to accept a number then check whether a given number is even
or odd and display the result in the second textbox?
import javax.swing.*;
import java.awt.event.*;
public class EvenOddCheckGUI {
public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Even or Odd Checker");
Time: 3 Hours
// Create components
JTextField inputField = new JTextField();
JTextField resultField = new JTextField();
JButton checkButton = new JButton("Check");
// Set positions and sizes for components
inputField.setBounds(50, 30, 150, 30);
checkButton.setBounds(50, 70, 100, 30);
resultField.setBounds(50, 110, 150, 30);
// Make the result field non-editable
resultField.setEditable(false);
// Add components to frame
frame.add(inputField);
frame.add(checkButton);
frame.add(resultField);
// Frame settings
frame.setSize(250, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Action for button click (no method override)
checkButton.addActionListener(e -> {
try {
// Get number from input field
int number = Integer.parseInt(inputField.getText());
// Check if the number is even or odd
if (number % 2 == 0) {
resultField.setText("Even");
} else {
resultField.setText("Odd");
}
} catch (NumberFormatException ex) {
resultField.setText("Invalid input");
}
});
Time: 3 Hours
}
}
6.Program to create a package named shapes and define abstract class Shape inside it.
The Shape class should have an abstract method getArea(). Define two subclasses
Rectangle and Circle that extend the Shape class and implement the getArea() method.
Create a class FindArea in a different package and use the Rectangle and Circle classes
to find the areas of a rectangle and a circle.
Shape.java
package shapes;
public abstract class Shape {
// Abstract method to be implemented by subclasses
public abstract double getArea();
}
Rectangle.java
package shapes;
public class Rectangle extends Shape {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementing the getArea() method
public double getArea() {
return length * width;
}
}
Time: 3 Hours
Circle.java
package shapes;
public class Circle extends Shape {
private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Implementing the getArea() method
public double getArea() {
return Math.PI * radius * radius;
}
}
FindArea.java
package areaCalculator;
import shapes.Rectangle;
import shapes.Circle;
public class FindArea {
public static void main(String[] args) {
// Create a Rectangle object with length 5 and width 3
Rectangle rectangle = new Rectangle(5, 3);
System.out.println("Area of Rectangle: " + rectangle.getArea());
// Create a Circle object with radius 7
Circle circle = new Circle(7);
System.out.println("Area of Circle: " + circle.getArea());
}
}
7. Write an applet program to draw different shapes?
import java.applet.Applet;
Time: 3 Hours
import java.awt.Graphics;
import java.awt.Color;
public class ShapeApplet extends Applet {
// The paint method to draw shapes
public void paint(Graphics g) {
// Set color to blue and draw a rectangle
g.setColor(Color.BLUE);
g.drawRect(50, 50, 150, 100); // (x, y, width, height)
// Set color to green and fill a rectangle
g.setColor(Color.GREEN);
g.fillRect(50, 200, 150, 100);
// Set color to red and draw an oval
g.setColor(Color.RED);
g.drawOval(250, 50, 150, 100); // (x, y, width, height)
// Set color to yellow and fill an oval
g.setColor(Color.YELLOW);
g.fillOval(250, 200, 150, 100);
// Set color to black and draw a line
g.setColor(Color.BLACK);
g.drawLine(50, 350, 400, 350); // (x1, y1, x2, y2)
// Set color to purple and draw a polygon (triangle in this case)
g.setColor(Color.PURPLE);
int[] xPoints = {100, 150, 200}; // X coordinates of the triangle
int[] yPoints = {400, 350, 400}; // Y coordinates of the triangle
Time: 3 Hours
g.drawPolygon(xPoints, yPoints, 3); // Draw triangle
g.fillPolygon(xPoints, yPoints, 3); // Fill triangle with color
}
}
8.A bank maintains two kinds of accounts - Savings Account and Current Account. The
savings account provides compound interest, deposit and withdrawal facilities. The
current account only provides deposit and withdrawal facilities. Current account holders
should also maintain a minimum balance. If balance falls below this level, a service charge
is imposed. Create a class Account that stores customer name, account number and type
of account. From this derive the classes Curr-acct and Sav-acct.
Include the necessary methods in order to achieve the following tasks.
a. Accept deposit from a customer and update the balance
b. Display the balance.
c. Compute interest and add to balance.
d. Permit withdrawal and update the balance ( Check for the minimum
balance, impose penalty if necessary).
import java.io.*;
abstract class Account {
protected String customerName;
protected int accountNumber;
protected double balance;
public Account(String name, int accNo, double balance) {
customerName = name;
accountNumber = accNo;
this.balance = balance;
}
// Accept deposit from a customer and update balance
public void deposit(double amount) {
balance += amount;
}
// Display the balance
public void displayBalance() {
System.out.println("Balance: " + balance);
}
Time: 3 Hours
// Method to permit withdrawal (handled in child classes directly)
public void withdraw(double amount) {
// Default method does nothing, as withdrawal is handled in child classes
}
}
class CurrAcct extends Account {
private static final double MIN_BALANCE = 1000;
private static final double SERVICE_CHARGE = 50;
public CurrAcct(String name, int accNo, double balance) {
super(name, accNo, balance);
}
// Permit withdrawal and impose penalty if necessary
public void withdraw(double amount) {
if (balance - amount < MIN_BALANCE) {
balance -= SERVICE_CHARGE; // Impose service charge
System.out.println("Service charge imposed. Your balance after charge: " + balance);
} else {
balance -= amount; // Regular withdrawal
}
}
}
class SavAcct extends Account {
private static final double INTEREST_RATE = 0.05;
public SavAcct(String name, int accNo, double balance) {
super(name, accNo, balance);
}
// Compute interest and add to balance
public void addInterest() {
balance += balance * INTEREST_RATE;
}
// Permit withdrawal
public void withdraw(double amount) {
balance -= amount;
Time: 3 Hours
}
}
public class BankSystem {
public static void main(String[] args) {
try {
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter Customer Name: ");
String name = input.readLine();
System.out.print("Enter Account Number: ");
int accNo = Integer.parseInt(input.readLine());
System.out.print("Enter Account Type (1 for Current, 2 for Savings): ");
int type = Integer.parseInt(input.readLine());
System.out.print("Enter Initial Balance: ");
double balance = Double.parseDouble(input.readLine());
Account account;
// Create account based on user input
if (type == 1) {
account = new CurrAcct(name, accNo, balance);
} else {
account = new SavAcct(name, accNo, balance);
}
// Menu for the bank system
while (true) {
System.out.println("\nChoose an option:");
System.out.println("1. Deposit");
System.out.println("2. Display Balance");
System.out.println("3. Withdraw");
System.out.println("4. Add Interest (for Savings Account)");
System.out.println("5. Exit");
int option = Integer.parseInt(input.readLine());
switch (option) {
Time: 3 Hours
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = Double.parseDouble(input.readLine());
account.deposit(depositAmount);
break;
case 2:
account.displayBalance();
break;
case 3:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = Double.parseDouble(input.readLine());
account.withdraw(withdrawAmount); // Withdrawal handled directly in child
class
account.displayBalance();
break;
case 4:
if (account instanceof SavAcct) {
((SavAcct) account).addInterest();
account.displayBalance();
} else {
System.out.println("Interest can only be added to a Savings Account.");
}
break;
case 5:
System.out.println("Thank you for using the bank system.");
return;
default:
System.out.println("Invalid option, please try again.");
}
}
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
}
Time: 3 Hours
9.Write a swing program to accept a value in a textbox then reverse that number and
display the result in the second textbox?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ReverseNumberApplet extends JApplet implements ActionListener {
JLabel label1, label2;
JTextField textField1, textField2;
JButton reverseButton;
public void init() {
// Initialize components
label1 = new JLabel("Enter Number:");
label1.setBounds(30, 30, 100, 30);
textField1 = new JTextField();
textField1.setBounds(150, 30, 150, 30);
label2 = new JLabel("Reversed Number:");
label2.setBounds(30, 80, 120, 30);
textField2 = new JTextField();
textField2.setBounds(150, 80, 150, 30);
textField2.setEditable(false); // Make it non-editable for result
reverseButton = new JButton("Reverse");
Time: 3 Hours
reverseButton.setBounds(100, 130, 100, 30);
reverseButton.addActionListener(this);
// Set layout to null for absolute positioning
setLayout(null);
// Add components to applet
add(label1);
add(textField1);
add(label2);
add(textField2);
add(reverseButton);
// Action performed when the button is clicked
public void actionPerformed(ActionEvent e) {
String input = textField1.getText(); // Get text from first textbox
String reversed = new StringBuilder(input).reverse().toString(); // Reverse the string
textField2.setText(reversed); // Set the reversed string in the second textbox
10. Create an interface Department containing attributes deptName and deptHead.it
as an abstract method showData() for printing the attribute. Create a class Hostel
containing hostelname, hostellocation and noofrooms and also have methods
readData() and printData() for reading and printing the details. Then write
another class named Student extending the Hostel class and implementing the
Time: 3 Hours
Department interface. This class contains which contains the attributes studname,
regno, electivesub and avgmark and use readData() and showData() for reading
and printing the details.
import java.io.*;
interface Department {
String deptName = "Computer Science"; // Department name
String deptHead = "Dr. Smith"; // Department head
void showData(); // Abstract method to display department data
}
class Hostel {
String hostelName, hostelLocation;
int noOfRooms;
// Method to read hostel data
void readData() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Hostel Name: ");
hostelName = br.readLine();
System.out.print("Enter Hostel Location: ");
hostelLocation = br.readLine();
System.out.print("Enter Number of Rooms: ");
noOfRooms = Integer.parseInt(br.readLine());
}
// Method to display hostel data
void printData() {
System.out.println("Hostel Name: " + hostelName);
System.out.println("Hostel Location: " + hostelLocation);
System.out.println("Number of Rooms: " + noOfRooms);
}
}
class Student extends Hostel implements Department {
String studName, regNo, electiveSub;
double avgMark;
// Method to read student details and hostel data
void readData() throws IOException {
Time: 3 Hours
super.readData(); // Calling superclass method
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Student Name: ");
studName = br.readLine();
System.out.print("Enter Register Number: ");
regNo = br.readLine();
System.out.print("Enter Elective Subject: ");
electiveSub = br.readLine();
System.out.print("Enter Average Marks: ");
avgMark = Double.parseDouble(br.readLine());
}
// Method to display all details, including department data
public void showData() {
printData(); // Calling superclass method to print hostel data
System.out.println("Student Name: " + studName);
System.out.println("Register Number: " + regNo);
System.out.println("Elective Subject: " + electiveSub);
System.out.println("Average Marks: " + avgMark);
System.out.println("Department Name: " + deptName);
System.out.println("Department Head: " + deptHead);
}
}
public class Main {
public static void main(String[] args) {
try {
Student student = new Student(); // Create Student object
student.readData(); // Reading student and hostel data
student.showData(); // Displaying all the data
} catch (IOException e) {
System.out.println("Error reading data: " + e.getMessage());
}
}
}