Java Assingment
Java Assingment
Que 31. Assume that the bank maintains two kinds of account. One called Saving Account
and the other is Current Account. The saving account provides compound interest and
withdrawal facility but no cheque book facility. The current account provides cheque book
facility and withdrawal facility but no interest. Current account holders should also maintains
a minimum balance and if the balance falls below this level, a service charge is imposed.
Create a class Account that stores customer name, account number, and the type of account.
From this derive the class curr_acct and sav_acct to make them more specific to their
requirement. Include the necessary methods in order to achieve the following task.
• Accept deposit from customer and update the balance.
• Display the balance.
• Permit withdrawal and compute the balance.
• Check for minimum balance, impose penalty if necessary and update the balance.
Display all the desired information.
Code:
import java.util.Scanner;
class Account {
private String customerName;
private int accountNumber;
protected double balance;
protected String accountType;
// Constructor
public Account(String customerName, int accountNumber, double balance, String
accountType) {
this.customerName = customerName;
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
23FS20MCA00051
ABHINAV CHAUHAN
// Constructor
public SavingsAccount(String customerName, int accountNumber, double balance, double
interestRate) {
super(customerName, accountNumber, balance, "Savings");
this.interestRate = interestRate;
}
// Constructor
public CurrentAccount(String customerName, int accountNumber, double balance, double
minimumBalance, double penalty) {
super(customerName, accountNumber, balance, "Current");
this.minimumBalance = minimumBalance;
this.penalty = penalty;
}
23FS20MCA00051
ABHINAV CHAUHAN
// Display balances
System.out.println("\nSavings Account:");
savingsAccount.displayBalance();
System.out.println("\nCurrent Account:");
currentAccount.displayBalance();
scanner.close();
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Que 33. Assume that the publishing company markets print books and digital books. Create a
class named Publication with data members named title, price and authors name. from
Publication class derive two classes named Books and Ebooks. The Book class adds a page
count data member named pcount while Ebook adds data member playing time name ptime.
Each of the classes must have member functions getdata() to read class specific data from
keyboard and displaydata() to output the class specific data to the computer screen. Write a
Program to test these classes.
Code:
import java.util.Scanner;
class Publication {
String title;
double price;
String authorName;
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 34: Assume that a shape interface contains the data members PI and functions area () and
perimeter (). Implement these two methods according to type of shape like circle, rectangle
and square classes.
Code:
interface Shape {
double PI = 3.14159; // Constant PI
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
23FS20MCA00051
ABHINAV CHAUHAN
// Constructor
public Square(double side) {
this.side = side;
}
System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.area());
System.out.println("Perimeter: " + rectangle.perimeter());
System.out.println("\nSquare:");
System.out.println("Area: " + square.area());
System.out.println("Perimeter: " + square.perimeter());
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 35: Assume that binary interface contains the method: binary to decimal, decimal to
binary, two’s complement and binary addition. Create the appropriate classes to implement
these methods.
Code:
interface Binary {
// Method to convert binary to decimal
int binaryToDecimal(String binary);
23FS20MCA00051
ABHINAV CHAUHAN
return sum.toString();
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 36: Write a program to display the use of all access modifiers with the help of two
packages.
Code:
package package_1;
void defaultMethod() {
System.out.println("This is a default method in Package 1");
}
package package2;
import package_1.PublicClass;
23FS20MCA00051
ABHINAV CHAUHAN
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 37: Design a package to contain the class student and another package that contains the
interface sports. Write a program to display the Rollno, Paper1, Paper2 and total score of the
candidates.
Code:
// Package containing the Student class
package studentPackage;
// Constructor
public Student(int rollNo, int paper1, int paper2) {
this.rollNo = rollNo;
this.paper1 = paper1;
this.paper2 = paper2;
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
Que 38: Write a program to show the use of simple try/catch statement.
Code:
public class LAB_38 {
public static void main(String[] args) {
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 39: Write a program to show the use of nested try/catch statements.
Code:
public class LAB_39 {
public static void main(String[] args) {
try {
// Inner try block
System.out.println("Inner try block starts");
23FS20MCA00051
ABHINAV CHAUHAN
System.out.println("Program completed.");
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 40: Write a program to show the use of “throw”, “throws” and “finally” keyword.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 41: Write a program to create a custom exception. Show its use with the help o java
program.
Code:
// Custom exception class
class CustomException extends Exception {
// Constructor
public CustomException(String message) {
super(message);
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 42: Write a program to read two integer number and calculate the division of these two
numbers, throw an exception when wrong type of data is keyed in. and also maintain a try
block to detect and throw exception if condition “divide by zero” occurs.
Code:
import java.util.Scanner;
// Custom exception class for invalid input data
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
try {
// Read two integer numbers
System.out.print("Enter first number: ");
int num1 = readInteger(scanner);
// Perform division
int result = divide(num1, num2);
System.out.println("Result of division: " + result);
} catch (InvalidInputException e) {
// Catch block for invalid input data
System.out.println("Invalid input: " + e.getMessage());
} catch (ArithmeticException e) {
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 43: Define an exception called “NoMatchException” that is thrown when a string is not
equal to “India”. Write a program that uses this exception.
Code:
// Custom exception class NoMatchException
class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message);
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 44: Write a program to copy characters from one file into another using character
streams
Code:
import java.io.*;
try {
// Create FileReader and FileWriter objects
FileReader fileReader = new FileReader(inputFile);
FileWriter fileWriter = new FileWriter(outputFile);
// Close streams
bufferedReader.close();
bufferedWriter.close();
23FS20MCA00051
ABHINAV CHAUHAN
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
try {
// Create FileOutputStream object
FileOutputStream outputStream = new FileOutputStream(filePath);
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 46: Write a program to read bytes from file by using program no 47.
Code:
import java.io.*;
// File path
String filePath = "output.txt";
try {
// Create FileInputStream object
FileInputStream inputStream = new FileInputStream(filePath);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Que 47: Write a program to create a sequential file that could store details of five students.
Details include id, name, class, semester, three subject marks. Compute and print students
information and their total marks.
Code:
import java.io.*;
// Close FileWriter
fileWriter.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Method to read student details from file, compute total marks, and print information
public static void readFromFile(String filePath) {
try {
// Create FileReader object
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] details = line.split(",");
int id = Integer.parseInt(details[0]);
23FS20MCA00051
ABHINAV CHAUHAN
// Close FileReader
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Read student details from file, compute total marks, and print information
readFromFile(filePath);
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 48: Write a program to show reading and writing with random access file. At the same
time append some text to a file.
Code:
import java.io.*;
23FS20MCA00051
ABHINAV CHAUHAN
randomAccessFile.writeDouble(85.5);
// Close RandomAccessFile
randomAccessFile.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Close RandomAccessFile
randomAccessFile.close();
23FS20MCA00051
ABHINAV CHAUHAN
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Close FileWriter
fileWriter.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
// Initialization method
public void init() {
// Get the value of the "message" parameter
message = getParameter("message");
// Paint method
public void paint(Graphics g) {
g.drawString(message, 50, 50);
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 51: Write a program to perform the arithmetic operations by using interactive inputs to
an applet.
Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package applet.programs;
/**
*
* @author DS
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
// Initialization method
public void init() {
// Initialize TextFields
num1Field = new TextField(10);
num2Field = new TextField(10);
23FS20MCA00051
ABHINAV CHAUHAN
// Initialize Labels
num1Label = new Label("Enter first number:");
num2Label = new Label("Enter second number:");
resultLabel = new Label("");
// Initialize Buttons
addButton = new Button("Add");
subtractButton = new Button("Subtract");
multiplyButton = new Button("Multiply");
divideButton = new Button("Divide");
// ActionListener method
public void actionPerformed(ActionEvent e) {
// Get input values from TextFields
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
23FS20MCA00051
ABHINAV CHAUHAN
double result = 0;
// Display result
resultLabel.setText("Result: " + result);
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 52: Write a program to draw various shapes (at least 5) using methods of graphics class.
Code:
import java.applet.Applet;
import java.awt.*;
// Paint method
public void paint(Graphics g) {
// Draw a rectangle
g.setColor(Color.blue);
g.fillRect(50, 50, 100, 50);
// Draw an oval
g.setColor(Color.red);
g.fillOval(200, 50, 100, 50);
// Draw a line
g.setColor(Color.green);
g.drawLine(50, 150, 150, 150);
// Draw a polygon
int[] xPoints = {250, 300, 350};
int[] yPoints = {200, 150, 200};
int nPoints = 3;
g.setColor(Color.orange);
g.fillPolygon(xPoints, yPoints, nPoints);
// Draw an arc
g.setColor(Color.magenta);
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Turnover
110 150 135 200 210 185
(Rs. Crores)
Code:
import java.applet.Applet;
import java.awt.*;
// Initialization method
public void init() {
setBackground(Color.white);
}
// Paint method
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
23FS20MCA00051
ABHINAV CHAUHAN
// Draw x-axis
g.drawLine(startX, height - 50, startX + chartWidth, height - 50);
// Draw y-axis
g.drawLine(startX, height - 50, startX, 50);
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 54: Write an applet program to insert image, audio and video data.
Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package applet.programs;
/**
*
* @author DS
*/
import java.applet.*;
import java.awt.*;
import java.net.*;
// Load image
try {
URL imageURL = new URL(getDocumentBase(), "../images/image.jpg");
image = getImage(imageURL);
mediaTracker.addImage(image, 0);
} catch (MalformedURLException e) {
e.printStackTrace();
}
23FS20MCA00051
ABHINAV CHAUHAN
// Load audio
try {
URL audioURL = new URL(getDocumentBase(), "../sound/audio.wav");
audioClip = getAudioClip(audioURL);
mediaTracker.addImage(image, 1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
// Play audio
if (mediaTracker.checkID(1)) {
audioClip.play();
}
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Que 55: Write a program to illustrate the use of multithreading. Also set priorities for
threads.
Code:
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Que 56: Write a program that connects to a server by using a socket and sends a greeting,
and then waits for a response.
Code:
import java.io.*;
import java.net.*;
try {
// Connect to the server
Socket socket = new Socket(serverAddress, port);
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 57: Write a program to create server application that uses the Socket class to listen for
clients on a port number specified by a command-line argument:
Code:
import java.io.*;
import java.net.*;
while (true) {
// Wait for a client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
23FS20MCA00051
ABHINAV CHAUHAN
23FS20MCA00051
ABHINAV CHAUHAN
Que 58: Write a program to show the use of methods of the ArrayList and LinkedList classes.
Code:
import java.util.ArrayList;
import java.util.LinkedList;
// Create a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
23FS20MCA00051
ABHINAV CHAUHAN
System.out.println(gameConsole);
}
System.out.println("\nModified LinkedList:");
for (String gameConsole : linkedList) {
System.out.println(gameConsole);
}
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 59: Write a program to show how Vector class can be used.
Code:
import java.util.Vector;
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 60: Write a program to search an element in a collection using binarySearch method.
Code:
import java.util.ArrayList;
import java.util.Collections;
// Element to search
int target = 30;
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051