ABHINAV CHAUHAN
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;
}
// Method to accept deposit from customer and update balance
public void deposit(double amount) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
}
// Method to display balance
public void displayBalance() {
System.out.println("Account Balance: $" + balance);
}
// Method to withdraw amount
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
23FS20MCA00051
ABHINAV CHAUHAN
System.out.println("Withdrawal of $" + amount + " successful.");
} else {
System.out.println("Insufficient balance.");
}
}
// Method to check for minimum balance and impose penalty if necessary
public void checkMinimumBalance(double minimumBalance, double penalty) {
if (balance < minimumBalance) {
balance -= penalty;
System.out.println("Minimum balance penalty charged. Remaining balance: $" +
balance);
}
}
}
class SavingsAccount extends Account {
private double interestRate;
// Constructor
public SavingsAccount(String customerName, int accountNumber, double balance, double
interestRate) {
super(customerName, accountNumber, balance, "Savings");
this.interestRate = interestRate;
}
// Method to calculate compound interest
public void calculateInterest() {
balance += (balance * interestRate / 100);
System.out.println("Compound interest calculated. Updated balance: $" + balance);
}
}
class CurrentAccount extends Account {
public double minimumBalance;
public double penalty;
// Constructor
public CurrentAccount(String customerName, int accountNumber, double balance, double
minimumBalance, double penalty) {
super(customerName, accountNumber, balance, "Current");
this.minimumBalance = minimumBalance;
this.penalty = penalty;
}
// Method to check for minimum balance and impose penalty if necessary
@Override
23FS20MCA00051
ABHINAV CHAUHAN
public void checkMinimumBalance(double minimumBalance, double penalty) {
if (balance < minimumBalance) {
balance -= penalty;
System.out.println("Minimum balance penalty charged. Remaining balance: $" +
balance);
}
}
}
public class Lab_31 {
public static void main(String[] args) {
System.out.println("Name : Abhinav Chauhan");
System.out.println("Reg. No. : 23FS20MCA00051");
Scanner scanner = new Scanner(System.in);
// Create Savings Account
SavingsAccount savingsAccount = new SavingsAccount("John", 123456, 5000, 5);
// Create Current Account
CurrentAccount currentAccount = new CurrentAccount("Alice", 987654, 3000, 2000,
50);
// Deposit to Savings Account
savingsAccount.deposit(2000);
// Withdraw from Current Account
currentAccount.withdraw(1000);
// Check minimum balance for Current Account
currentAccount.checkMinimumBalance(currentAccount.minimumBalance,
currentAccount.penalty);
// 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
Que 32. Write a program to show the use of super.
Code:
class Parent {
int parentData;
// Constructor of Parent class
public Parent(int parentData) {
this.parentData = parentData;
System.out.println("Parent class constructor called.");
}
// Method of Parent class
public void displayParentData() {
System.out.println("Parent Data: " + parentData);
}
}
class Child extends Parent {
int childData;
// Constructor of Child class
public Child(int parentData, int childData) {
super(parentData); // Calling parent class constructor using super
this.childData = childData;
System.out.println("Child class constructor called.");
}
// Method of Child class
public void displayChildData() {
System.out.println("Child Data: " + childData);
}
// Method overriding Parent class method
@Override
public void displayParentData() {
super.displayParentData(); // Calling parent class method using super
System.out.println("Overridden method in Child class.");
}
}
public class LAB_32 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Create an object of Child class
Child childObj = new Child(10, 20);
23FS20MCA00051
ABHINAV CHAUHAN
// Call methods of Child class
childObj.displayParentData();
childObj.displayChildData();
}
}Output:
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;
// Method to read publication data from keyboard
public void getData() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter publication title: ");
title = scanner.nextLine();
System.out.println("Enter publication price: ");
price = scanner.nextDouble();
scanner.nextLine(); // Consume newline character
System.out.println("Enter author's name: ");
authorName = scanner.nextLine();
}
// Method to display publication data
public void displayData() {
System.out.println("Title: " + title);
System.out.println("Price: $" + price);
System.out.println("Author's Name: " + authorName);
}
}
class Book extends Publication {
int pageCount;
// Method to read book data from keyboard
@Override
public void getData() {
super.getData();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter page count: ");
pageCount = scanner.nextInt();
}
23FS20MCA00051
ABHINAV CHAUHAN
// Method to display book data
@Override
public void displayData() {
super.displayData();
System.out.println("Page Count: " + pageCount);
}
}
class Ebook extends Publication {
int playingTime;
// Method to read ebook data from keyboard
@Override
public void getData() {
super.getData();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter playing time (in minutes): ");
playingTime = scanner.nextInt();
}
// Method to display ebook data
@Override
public void displayData() {
super.displayData();
System.out.println("Playing Time: " + playingTime + " minutes");
}
}
public class LAB_33 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Test Book class
System.out.println("Enter details for a book:");
Book book = new Book();
book.getData();
System.out.println("\nBook details:");
book.displayData();
// Test Ebook class
System.out.println("\nEnter details for an ebook:");
Ebook ebook = new Ebook();
ebook.getData();
System.out.println("\nEbook details:");
ebook.displayData();
scanner.close();
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
double area(); // Method to calculate area
double perimeter(); // Method to calculate perimeter
}
class Circle implements Shape {
private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Implementing interface method to calculate area of circle
public double area() {
return PI * radius * radius;
}
// Implementing interface method to calculate perimeter of circle
public double perimeter() {
return 2 * PI * radius;
}
}
class Rectangle implements Shape {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementing interface method to calculate area of rectangle
public double area() {
return length * width;
}
// Implementing interface method to calculate perimeter of rectangle
23FS20MCA00051
ABHINAV CHAUHAN
public double perimeter() {
return 2 * (length + width);
}
}
class Square implements Shape {
private double side;
// Constructor
public Square(double side) {
this.side = side;
}
// Implementing interface method to calculate area of square
public double area() {
return side * side;
}
// Implementing interface method to calculate perimeter of square
public double perimeter() {
return 4 * side;
}
}
public class LAB_34 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Creating objects of Circle, Rectangle, and Square classes
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
Square square = new Square(3);
// Displaying area and perimeter of each shape
System.out.println("Circle:");
System.out.println("Area: " + circle.area());
System.out.println("Perimeter: " + circle.perimeter());
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);
// Method to convert decimal to binary
String decimalToBinary(int decimal);
// Method to compute two's complement
String twosComplement(String binary);
// Method to perform binary addition
String binaryAddition(String binary1, String binary2);
}
public class LAB_35 implements Binary {
// Method to convert binary to decimal
public int binaryToDecimal(String binary) {
return Integer.parseInt(binary, 2);
}
// Method to convert decimal to binary
public String decimalToBinary(int decimal) {
return Integer.toBinaryString(decimal);
}
// Method to compute two's complement
public String twosComplement(String binary) {
StringBuilder complement = new StringBuilder();
for (char bit : binary.toCharArray()) {
complement.append((bit == '0') ? '1' : '0');
}
return complement.toString();
}
// Method to perform binary addition
public String binaryAddition(String binary1, String binary2) {
int carry = 0;
StringBuilder sum = new StringBuilder();
int i = binary1.length() - 1;
int j = binary2.length() - 1;
while (i >= 0 || j >= 0 || carry > 0) {
23FS20MCA00051
ABHINAV CHAUHAN
int bit1 = (i >= 0) ? binary1.charAt(i--) - '0' : 0;
int bit2 = (j >= 0) ? binary2.charAt(j--) - '0' : 0;
int currentSum = bit1 + bit2 + carry;
sum.insert(0, currentSum % 2);
carry = currentSum / 2;
}
return sum.toString();
}
public static void main(String[] args) {
LAB_35 obj = new LAB_35();
// Test binary to decimal conversion
String binary = "1010";
int decimal = obj.binaryToDecimal(binary);
System.out.println("Binary: " + binary + " Decimal: " + decimal);
// Test decimal to binary conversion
int number = 10;
String binaryString = obj.decimalToBinary(number);
System.out.println("Decimal: " + number + " Binary: " + binaryString);
// Test two's complement
String originalBinary = "1010";
String complement = obj.twosComplement(originalBinary);
System.out.println("Original Binary: " + originalBinary + " Two's Complement: " +
complement);
// Test binary addition
String binary1 = "101";
String binary2 = "110";
String sum = obj.binaryAddition(binary1, binary2);
System.out.println("Binary Addition: " + binary1 + " + " + binary2 + " = " + sum);
}
}
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;
public class PublicClass {
public void publicMethod() {
System.out.println("This is a public method in Package 1");
}
protected void protectedMethod() {
System.out.println("This is a protected method in Package 1");
}
void defaultMethod() {
System.out.println("This is a default method in Package 1");
}
private void privateMethod() {
System.out.println("This is a private method in Package 1");
}
}
package package2;
import package_1.PublicClass;
public class LAB_36 {
public static void main(String[] args) {
System.out.println("Name : Abhinav Chauhan");
System.out.println("Reg. No. : 23FS20MCA00051");
PublicClass obj = new PublicClass();
obj.publicMethod();
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;
public class Student {
private int rollNo;
private int paper1;
private int paper2;
// Constructor
public Student(int rollNo, int paper1, int paper2) {
this.rollNo = rollNo;
this.paper1 = paper1;
this.paper2 = paper2;
}
// Method to calculate total score
public int calculateTotalScore() {
return paper1 + paper2;
}
// Method to display student details
public void displayDetails() {
System.out.println("Roll No: " + rollNo);
System.out.println("Paper 1 Score: " + paper1);
System.out.println("Paper 2 Score: " + paper2);
System.out.println("Total Score: " + calculateTotalScore());
}
}
// Package containing the Sports interface
package sportsPackage;
23FS20MCA00051
ABHINAV CHAUHAN
public interface Sports {
// Method to get sports score
int getSportsScore();
}
// Main program to display student details
import studentPackage.Student;
import sportsPackage.Sports;
public class LAB_37 implements Sports {
// Implementing method from Sports interface
public int getSportsScore() {
// Assuming some sports score
return 80;
}
public static void main(String[] args) {
System.out.println("Name : Abhinav Chauhan");
System.out.println("Reg. No. : 23FS20MCA00051");
// Create a Student object
Student student = new Student(101, 75, 85);
// Create an object of LAB_37 to access sports score
LAB_37 obj = new LAB_37();
// Display student details
student.displayDetails();
// Display sports score
System.out.println("Sports Score: " + obj.getSportsScore());
}
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) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result); // This line won't be executed if an exception
occurs
} catch (ArithmeticException e) {
// Catch block to handle the exception
System.out.println("Exception caught: " + e.getMessage());
}
// This line will be executed regardless of whether an exception occurred or not
System.out.println("Program completed.");
}
// Method that may throw an exception
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
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) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
try {
// Outer try block
System.out.println("Outer try block starts");
try {
// Inner try block
System.out.println("Inner try block starts");
// Division by zero, will throw ArithmeticException
int result = divide(10, 0);
System.out.println("Result: " + result); // This line won't be executed if an
exception occurs
System.out.println("Inner try block ends");
} catch (ArithmeticException e) {
// Catch block for inner try block
System.out.println("Inner catch block: " + e.getMessage());
}
// This line will be executed after the inner try-catch block
System.out.println("Outer try block ends");
} catch (Exception e) {
// Catch block for outer try block
System.out.println("Outer catch block: " + e.getMessage());
}
// This line will be executed regardless of whether an exception occurred or not
23FS20MCA00051
ABHINAV CHAUHAN
System.out.println("Program completed.");
}
// Method that may throw an ArithmeticException
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
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;
public class LAB_40 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
try {
// Calling a method that throws an exception
readFromFile("nonexistentfile.txt");
} catch (IOException e) {
// Catching the exception thrown by readFromFile method
System.out.println("Exception caught: " + e.getMessage());
} finally {
// Finally block executes regardless of whether an exception occurred or not
System.out.println("Finally block executed");
}
}
// Method that throws an IOException
public static void readFromFile(String fileName) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Catching and re-throwing the exception
throw e;
} finally {
// Closing the BufferedReader in finally block to ensure it is always closed
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignoring IOException while closing the reader
}
}
}
}
}
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);
}
}
public class LAB_41 {
// Method that may throw the custom exception
public static void checkNumber(int number) throws CustomException {
if (number < 0) {
throw new CustomException("Number cannot be negative");
} else {
System.out.println("Number is valid: " + number);
}
}
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
try {
// Calling a method that may throw the custom exception
checkNumber(-5);
} catch (CustomException e) {
// Catching the custom exception
System.out.println("Custom Exception caught: " + e.getMessage());
}
}
}
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);
}
}
public class LAB_42 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
Scanner scanner = new Scanner(System.in);
try {
// Read two integer numbers
System.out.print("Enter first number: ");
int num1 = readInteger(scanner);
System.out.print("Enter second number: ");
int num2 = 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
// Catch block for division by zero
System.out.println("Division by zero: " + e.getMessage());
} finally {
// Close the scanner
scanner.close();
}
}
// Method to read integer input from the user
public static int readInteger(Scanner scanner) throws InvalidInputException {
if (scanner.hasNextInt()) {
return scanner.nextInt();
} else {
throw new InvalidInputException("Input is not an integer");
}
}
// Method to perform division
public static int divide(int num1, int num2) {
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return num1 / num2;
}
}
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);
}
}
public class LAB_43 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
try {
// Test string
String country = "USA";
// Check if the string is equal to "India"
if (!country.equals("India")) {
// If not equal, throw NoMatchException
throw new NoMatchException("String does not match 'India'");
} else {
// If equal, display message
System.out.println("String matches 'India'");
}
} catch (NoMatchException e) {
// Catch block for NoMatchException
System.out.println("NoMatchException caught: " + e.getMessage());
}
}
}
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.*;
public class LAB_44 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Input and output file paths
String inputFile = "src/input.txt";
String outputFile = "output.txt";
try {
// Create FileReader and FileWriter objects
FileReader fileReader = new FileReader(inputFile);
FileWriter fileWriter = new FileWriter(outputFile);
// Create BufferedReader and BufferedWriter objects
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// Read from input file and write to output file
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine(); // Write newline character
}
// Close streams
bufferedReader.close();
bufferedWriter.close();
System.out.println("File copied successfully.");
23FS20MCA00051
ABHINAV CHAUHAN
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 45: Write a program to write bytes to a file.
Code:
import java.io.*;
public class LAB_45 {
public static void main(String[] args) {
// File path
String filePath = "output.txt";
// Bytes to write to the file
byte[] bytesToWrite = {65, 66, 67, 68, 69}; // ASCII values for A, B, C, D, E
try {
// Create FileOutputStream object
FileOutputStream outputStream = new FileOutputStream(filePath);
// Write bytes to the file
outputStream.write(bytesToWrite);
// Close the stream
outputStream.close();
System.out.println("Bytes written to the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
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.*;
public class LAB_46 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// File path
String filePath = "output.txt";
try {
// Create FileInputStream object
FileInputStream inputStream = new FileInputStream(filePath);
// Read bytes from the file
int byteRead;
while ((byteRead = inputStream.read()) != -1) {
System.out.print((char) byteRead); // Convert byte to char and print
}
// Close the stream
inputStream.close();
} 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.*;
public class LAB_47 {
// Method to write student details to file
public static void writeToFile(String filePath) {
try {
// Create FileWriter object
FileWriter fileWriter = new FileWriter(filePath);
// Write student details to file
String[] students = {
"101,John,10,A,80,75,85",
"102,Alice,10,B,70,65,80",
"103,Smith,11,A,85,80,90",
"104,Emily,11,B,75,70,80",
"105,David,12,A,90,85,95"
};
for (String student : students) {
fileWriter.write(student + "\n");
}
// Close FileWriter
fileWriter.close();
System.out.println("Student details written to file successfully.");
} 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
String name = details[1];
int classNo = Integer.parseInt(details[2]);
String semester = details[3];
int marks1 = Integer.parseInt(details[4]);
int marks2 = Integer.parseInt(details[5]);
int marks3 = Integer.parseInt(details[6]);
// Compute total marks
int totalMarks = marks1 + marks2 + marks3;
// Print student information and total marks
System.out.println("Student ID: " + id);
System.out.println("Name: " + name);
System.out.println("Class: " + classNo);
System.out.println("Semester: " + semester);
System.out.println("Subject 1 Marks: " + marks1);
System.out.println("Subject 2 Marks: " + marks2);
System.out.println("Subject 3 Marks: " + marks3);
System.out.println("Total Marks: " + totalMarks);
System.out.println();
}
// Close FileReader
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// File path
String filePath = "students.txt";
// Write student details to file
writeToFile(filePath);
// 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.*;
public class LAB_48 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// File path
String filePath = "random_access.txt";
// Write data to random access file
writeToFile(filePath);
// Read data from random access file
readFromFile(filePath);
// Append text to the file
appendToFile(filePath, "This text is appended to the file.");
// Read data from file after appending
readFromFile(filePath);
}
// Method to write data to random access file
public static void writeToFile(String filePath) {
try {
// Create RandomAccessFile object with read-write mode
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");
// Write data to the file
randomAccessFile.writeUTF("John");
randomAccessFile.writeInt(25);
23FS20MCA00051
ABHINAV CHAUHAN
randomAccessFile.writeDouble(85.5);
// Close RandomAccessFile
randomAccessFile.close();
System.out.println("Data written to random access file successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Method to read data from random access file
public static void readFromFile(String filePath) {
try {
// Create RandomAccessFile object with read-only mode
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
// Move file pointer to the beginning of the file
randomAccessFile.seek(0);
// Read data from the file
String name = randomAccessFile.readUTF();
int age = randomAccessFile.readInt();
double marks = randomAccessFile.readDouble();
// Print data read from the file
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Marks: " + marks);
// Close RandomAccessFile
randomAccessFile.close();
23FS20MCA00051
ABHINAV CHAUHAN
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Method to append text to a file
public static void appendToFile(String filePath, String text) {
try {
// Create FileWriter object in append mode
FileWriter fileWriter = new FileWriter(filePath, true);
// Write text to the file
fileWriter.write("\n" + text);
// Close FileWriter
fileWriter.close();
System.out.println("Text appended to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 49: Write an applet program to print Hello.
Code:
import java.applet.Applet;
import java.awt.*;
public class LAB_49 extends Applet {
public void paint(Graphics g) {
g.drawString("Hello", 50, 50);
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 50: Write an applet program to print Hello by passing parameter.
Code:
import java.applet.Applet;
import java.awt.*;
public class LAB_50 extends Applet {
// Parameter variable
String message;
// Initialization method
public void init() {
// Get the value of the "message" parameter
message = getParameter("message");
// If parameter is not provided, set default message
if (message == null) {
message = "Hello";
}
}
// 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.*;
public class LAB_51 extends Applet implements ActionListener {
// TextFields for input
TextField num1Field, num2Field;
// Labels for TextFields
Label num1Label, num2Label, resultLabel;
// Buttons for arithmetic operations
Button addButton, subtractButton, multiplyButton, divideButton;
// 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");
// Add ActionListener to buttons
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
// Add components to the applet
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
add(resultLabel);
}
// 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;
// Perform arithmetic operation based on button clicked
if (e.getSource() == addButton) {
result = num1 + num2;
} else if (e.getSource() == subtractButton) {
result = num1 - num2;
} else if (e.getSource() == multiplyButton) {
result = num1 * num2;
} else if (e.getSource() == divideButton) {
if (num2 != 0) {
result = num1 / num2;
} else {
resultLabel.setText("Cannot divide by zero");
return;
}
}
// 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.*;
public class LAB_52 extends Applet {
// Initialization method
public void init() {
setBackground(Color.white);
}
// 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
g.fillArc(200, 200, 100, 100, 90, 180);
}
}
Output:
23FS20MCA00051
ABHINAV CHAUHAN
Que 53: Write an applet program to draw bar charts.
Year 2009 2010 2011 2012 2013 2014
Turnover
110 150 135 200 210 185
(Rs. Crores)
Code:
import java.applet.Applet;
import java.awt.*;
public class LAB_53 extends Applet {
// Data for the bar chart
String[] years = {"2009", "2010", "2011", "2012", "2013", "2014"};
int[] turnover = {110, 150, 135, 200, 210, 185};
// Initialization method
public void init() {
setBackground(Color.white);
}
// Paint method
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
// Define bar chart dimensions
int barWidth = 50;
int gap = 20;
int startX = 50;
int startY = 50;
int chartWidth = (barWidth + gap) * years.length;
int maxTurnover = getMax(turnover);
int scale = (height - 100) / maxTurnover;
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);
// Draw bars and labels
for (int i = 0; i < years.length; i++) {
// Draw bar
int barHeight = turnover[i] * scale;
g.setColor(Color.blue);
g.fillRect(startX + (barWidth + gap) * i, height - 50 - barHeight, barWidth,
barHeight);
// Draw label for year
g.setColor(Color.black);
g.drawString(years[i], startX + (barWidth + gap) * i + 10, height - 30);
// Draw label for turnover
g.drawString(Integer.toString(turnover[i]), startX + (barWidth + gap) * i + 10, height
- 50 - barHeight - 5);
}
}
// Method to get maximum value from an array
public int getMax(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}
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.*;
public class LAB_54 extends Applet {
private Image image;
private AudioClip audioClip;
private MediaTracker mediaTracker;
public void init() {
// Initialize MediaTracker
mediaTracker = new MediaTracker(this);
// 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();
}
}
public void paint(Graphics g) {
// Draw image
if (mediaTracker.checkID(0)) {
g.drawImage(image, 0, 0, this);
}
// 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;
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + ": " + i);
// Pause the thread for a short while
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}
}
public class LAB_55 {
public static void main(String args[]) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
// Set priorities for threads
thread1.setPriority(Thread.MIN_PRIORITY); // Lowest priority
thread2.setPriority(Thread.MAX_PRIORITY); // Highest priority
23FS20MCA00051
ABHINAV CHAUHAN
// Start the threads
thread1.start();
thread2.start();
}
}
Output:
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.*;
public class LAB_56 {
public static void main(String[] args) {
System.out.println("Name : DIVYANSHU SINGHAL");
System.out.println("Reg. No. : 23FS20MCA00072");
String serverAddress = "localhost"; // Server address
int port = 12345; // Server port
try {
// Connect to the server
Socket socket = new Socket(serverAddress, port);
// Create input and output streams
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a greeting message to the server
out.println("Hello from client!");
// Read the response from the server
String response = in.readLine();
System.out.println("Server response: " + response);
// Close the socket
socket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
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.*;
public class LAB_57 {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java LAB_57 <port>");
return;
}
int port = Integer.parseInt(args[0]); // Port number specified by command-line argument
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started. Listening on port " + port);
while (true) {
// Wait for a client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Create input and output streams for the client
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// Read data from the client
String message = in.readLine();
System.out.println("Message from client: " + message);
// Send a response to the client
out.println("Hello from server!");
23FS20MCA00051
ABHINAV CHAUHAN
// Close the connection with the client
clientSocket.close();
System.out.println("Client disconnected.");
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Output:
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;
public class LAB_58 {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Create an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// Add elements to ArrayList
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
// Display elements of ArrayList
System.out.println("ArrayList:");
for (String fruit : arrayList) {
System.out.println(fruit);
}
// Create a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
// Add elements to LinkedList
linkedList.add("Xbox");
linkedList.add("PlayStation");
linkedList.add("Nintendo");
// Display elements of LinkedList
System.out.println("\nLinkedList:");
for (String gameConsole : linkedList) {
23FS20MCA00051
ABHINAV CHAUHAN
System.out.println(gameConsole);
}
// Add an element at a specific index in ArrayList
arrayList.add(1, "Orange");
// Remove an element from LinkedList
linkedList.removeLast();
// Display modified ArrayList and LinkedList
System.out.println("\nModified ArrayList:");
for (String fruit : arrayList) {
System.out.println(fruit);
}
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;
public class VectorExample {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Creating a Vector
Vector<String> vector = new Vector<>();
// Adding elements to the Vector
vector.add("Apple");
vector.add("Banana");
vector.add("Orange");
// Accessing elements in the Vector
System.out.println("Elements in the Vector:");
for (String fruit : vector) {
System.out.println(fruit);
}
// Getting the size of the Vector
System.out.println("Size of the Vector: " + vector.size());
// Removing an element from the Vector
vector.remove("Banana");
23FS20MCA00051
ABHINAV CHAUHAN
// Checking if an element exists in the Vector
if (vector.contains("Banana")) {
System.out.println("Vector contains Banana");
} else {
System.out.println("Vector does not contain Banana");
}
// Clearing the Vector
vector.clear();
// Checking if the Vector is empty
if (vector.isEmpty()) {
System.out.println("Vector is empty");
} else {
System.out.println("Vector is not empty");
}
}
}
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;
public class BinarySearchExample {
public static void main(String[] args) {
System.out.println("Name : ABHINAV CHAUHAN");
System.out.println("Reg. No. : 23FS20MCA00051");
// Create a sorted collection
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
// Sort the collection (binarySearch requires a sorted collection)
Collections.sort(numbers);
// Element to search
int target = 30;
// Perform binary search
int index = Collections.binarySearch(numbers, target);
// Check if element found
if (index >= 0) {
System.out.println("Element " + target + " found at index " + index);
} else {
System.out.println("Element " + target + " not found");
}
}
}
23FS20MCA00051
ABHINAV CHAUHAN
Output:
23FS20MCA00051