Bangladesh University of Business and Technology
Assisgement
Course Code:CSE 332
Course Title: Advanced Programming
Submitted By: Submitted To:
Name: Foysal Ahmad Name:[Link] Rahman
ID: 21225103124 Assistant Professor,CSE.
Section: 03 Bangladesh University of
Intake: 49 Business and Technology
Date of Submission: 19-05-2024
1.
Code:
import [Link];
import [Link];
import [Link];
public class FileDataReader {
public static void main(String[] args)
{ try {
File file = new File("[Link]");
Scanner scanner = new Scanner(file);
while ([Link]()) {
String data = [Link]();
[Link](data);
[Link]();
} catch (FileNotFoundException e) {
[Link]("Error: File not found. Please make sure the file exists and is
accessible.");
[Link]();
Output:
2.
Code:
public class ArrayAccessExample {
public static void main(String[] args)
int[] array = {10, 20, 30, 40, 50};
int indexToAccess =
5; try {
int element = array[indexToAccess];
[Link]("Element at index " + indexToAccess + ": " + element);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Invalid index. Index " + indexToAccess + " is out of bounds.");
[Link]();
Output:
3
Code:
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class NegativeAmountException extends Exception {
public NegativeAmountException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException("Initial balance cannot be negative");
}
[Link] = initialBalance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) throws NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot deposit a negative amount");
}
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot withdraw a negative amount");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for withdrawal");
}
balance -= amount;
}
}
public class BankTransaction{
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
[Link]("Initial Balance: " + [Link]());
try {
[Link](500);
[Link]("Deposited 500. Current Balance: " + [Link]());
} catch (NegativeAmountException e) {
[Link]("Deposit failed: " + [Link]());
}
finally {
[Link]("Deposit operation completed.");
}
try {
[Link](2000);
[Link]("Withdrew 2000. Current Balance: " + [Link]());
} catch (InsufficientFundsException | NegativeAmountException e) {
[Link]("Withdrawal failed: " + [Link]());
}
finally {
[Link]("Withdrawal operation completed.");
}
try {
[Link](-100);
[Link]("Deposited -100. Current Balance: " + [Link]());
}
catch (NegativeAmountException e)
{
[Link]("Deposit failed: " + [Link]());
}
finally {
[Link]("Deposit operation completed.");
}
try {
[Link](300);
[Link]("Withdrew 300. Current Balance: " + [Link]());
} catch (InsufficientFundsException | NegativeAmountException e)
{
[Link]("Withdrawal failed: " + [Link]());
}
finally {
[Link]("Withdrawal operation completed.");
}
}
}
Output:
4.
Code:
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message)
super(message);
class BankAccount {
private double balance;
public BankAccount(double initialBalance)
{if (initialBalance < 0) {
throw new IllegalArgumentException("Initial balance cannot be negative");
[Link] = initialBalance;
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be positive");
}
balance += amount;
[Link]("Deposited: " + amount + ", New Balance: " + balance);
public void withdraw(double amount) throws InsufficientBalanceException
{if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive");
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance. Current balance: " +
balance);
balance -= amount;
[Link]("Withdrew: " + amount + ", New Balance: " + balance);
public double getBalance()
{ return balance;
public static void main(String[] args)
{try {
BankAccount account = new
BankAccount(1000); [Link](500);
[Link](300);
[Link](1500); // This will throw an exception
} catch (InsufficientBalanceException e)
{ [Link]([Link]());
} catch (IllegalArgumentException e) {
[Link]([Link]());
Output:
5.
Code:
import [Link];
import [Link];
import [Link];
class InvalidEmailFormatException extends IllegalArgumentException {
public InvalidEmailFormatException(String message) {
super(message);
}
}
public class EmailValidator{
private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@(.+)$";
private static final Pattern EMAIL_PATTERN = [Link](EMAIL_REGEX);
public static void validateEmail(String email) throws InvalidEmailFormatException,
NullPointerException {
if (email == null) {
throw new NullPointerException("Email address cannot be null");
}
Matcher matcher = EMAIL_PATTERN.matcher(email
);
if (![Link]()) {
throw new InvalidEmailFormatException("Invalid email format: " + email);
}
}
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner([Link]);
[Link]("Enter your email address: ");
String email = [Link]();
validateEmail(email);
[Link]("Email address is valid.");
} catch (InvalidEmailFormatException e) {
[Link]("Validation failed: " + [Link]());
} catch (NullPointerException e) {
[Link]("Validation failed: " + [Link]());
}
}
}
Output:
6.
Code:
public class ThreadExample {
public static void main(String[] args) {
Thread deptThread = new Thread(new DeptThread());
Thread nameThread = new Thread(new NameThread());
Thread idThread = new Thread(new IDThread());
[Link]();
[Link]();
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
for (int i = 0; i < 10; i++) {
[Link]("Main thread executing");
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
class DeptThread implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
[Link]("Dept");
try {
[Link](2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
class NameThread implements Runnable {
public void run() {
for (int i = 0; i < 20; i++) {
[Link]("Name");
class IDThread implements Runnable
{@Override
public void run() {
for (int i = 0; i < 30; i++) {
[Link]("ID");
Output:
7
Code:
import [Link];
import [Link];
public class MatrixMultiplier {
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int row1 = [Link];
int col1 = matrix1[0].length;
int col2 =
matrix2[0].length;
int[][] result = new int[row1][col2];
ExecutorService executor =
[Link]([Link]().availableProcessors());
for (int i = 0; i < row1; i++)
{final int row = i;
[Link](() -> {
for (int j = 0; j < col2;
j++) {int sum = 0;
for (int k = 0; k < col1; k++) {
sum += matrix1[row][k] * matrix2[k][j];
result[row][j] = sum;
});
[Link]();
while (![Link]())
{} return result;
public static void main(String[] args) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = multiplyMatrices(matrix1,
matrix2); for (int[] row : result) {
for (int num : row) {
[Link](num + " ");
[Link]();
Output:
8.
Code:
public class FactorialCalculator {
static class FactorialThread extends Thread {
private int number;
private long factorial;
public FactorialThread(int number)
{[Link] = number;
[Link] = 1;
}public void run() {
factorial = calculateFactorial(number);
public long getFactorial()
{return factorial;
} private long calculateFactorial(int n)
{ long result = 1;
for (int i = 2; i <= n;
i++) {result *= i;
} return result;
} public static void main(String[] args)
{ int n = 6;
FactorialThread evenThread = new FactorialThread(n % 2 == 0 ? n : n - 1);
FactorialThread oddThread = new FactorialThread(n % 2 == 0 ? n - 1 :
n);[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e)
{ [Link]();
} long factorial = [Link]() * [Link]();
[Link]("Factorial of " + n + " is: " + factorial);
Output:
9.
Code:
public class LetterPrinter {
static class UppercaseThread extends Thread {
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
[Link](c + " ");
try {
[Link](100); // Sleep to allow lowercase thread to execute
} catch (InterruptedException e) {
static class LowercaseThread extends Thread {
@Override
public void run() {
for (char c = 'a'; c <= 'z'; c++) {
[Link](c + " ");
try {
[Link](100); // Sleep to allow uppercase thread to execute
} catch (InterruptedException e) {
}
} public static void main(String[] args) {
Thread uppercaseThread = new UppercaseThread();
Thread lowercaseThread = new LowercaseThread();
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
Output:
10.
Code:
public class SumCalculator {
static class SumThread extends Thread {
private final int start;
private final int end;
private long sum;
public SumThread(int start, int end) {
[Link] = start;
[Link] = end;
[Link] = 0;
} @Override
public void run()
for (int i = start; i <= end; i++)
{sum += i;
} public long getSum()
{ return sum;
}public static void main(String[] args)
{final int N = 100;
final int numThreads = 5;
SumThread[] threads = new SumThread[numThreads];
int segmentSize = N / numThreads;
int start = 1;
int end = segmentSize;
for (int i = 0; i < numThreads; i++)
{if (i == numThreads - 1) {
end = N; // Last segment
threads[i] = new SumThread(start, end);
start = end + 1;
end += segmentSize;
for (SumThread thread : threads) {
[Link]();
for (SumThread thread : threads) {
try {
[Link]();
} catch (InterruptedException e) {
long totalSum = 0;
for (SumThread thread : threads) {
totalSum += [Link]();
} [Link]("Sum of numbers from 1 to 100: " + totalSum);
}
}
Output:
11.
Code:
import [Link].*;
public class WordCounter {
public static void main(String[] args) {
String paragraph = "Write a program that takes a paragraph of text as input and counts the
occurrences of each word. Additionally, identify the five most common words and display them along
with their frequencies.";
String[] words = [Link]("[^a-zA-Z ]",
"").toLowerCase().split("\\s+"); Map<String, Integer> wordCounts = new
HashMap<>();
for (String word : words) {
[Link](word, [Link](word, 0) + 1);
List<[Link]<String, Integer>> sortedWordCounts = new
ArrayList<>([Link]());
[Link]((a, b) -> [Link]().compareTo([Link]()));
[Link]("Word Counts:");
for ([Link]<String, Integer> entry : sortedWordCounts) {
[Link]([Link]() + ": " + [Link]());
[Link]("\nTop 5 Most Common Words:"); int
count = 0;
for ([Link]<String, Integer> entry : sortedWordCounts)
{if (count >= 5) {
break;
[Link]([Link]() + ": " + [Link]());
count++;
Output:
12.
Code:
import [Link];
public class SubStringChecker
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a sentence: ");
String sentence = [Link]().toLowerCase();
[Link]("Enter a word to check: ");
String word = [Link]().toLowerCase();
boolean isSubstringPresent = [Link](word);
if (isSubstringPresent) {
[Link]("The word \"" + word + "\" is present as a substring in the
sentence.");
} else {
[Link]("The word \"" + word + "\" is not present as a substring in the
sentence.");
} [Link]();
output:
13.
Code:
import [Link];
public class CapitalizeWords
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a sentence: ");
String sentence = [Link]();
String[] words = [Link]("\\s+");
StringBuilder capitalizedSentence = new
StringBuilder(); for (String word : words) {
if (![Link]()) {
String capitalizedWord = [Link](0, 1).toUpperCase() + [Link](1);
[Link](capitalizedWord).append(" ");
String result = [Link]().trim
[Link]("Original sentence: " + sentence);[Link]("Capitalized sentence: " + result);
[Link]();
Output:
14.
Code:
public class ReverseWords {
public static String reverseSentence(String sentence) {
String[] words = [Link]("\\s+");
StringBuilder reversedSentence = new StringBuilder();
for (int i = [Link] - 1; i >= 0; i--) {
[Link](words[i]); if
(i > 0) {
[Link](" ");
return [Link]();
public static void main(String[] args)
{ String sentence = "Hello
world";
String reversedSentence = reverseSentence(sentence);
[Link]("Original sentence: " + sentence);
[Link]("Reversed sentence: " + reversedSentence);
}
Output:
15.
Code:
import [Link];
import [Link];
import [Link];
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
Map<Character, Integer> charCountMap = new HashMap<>();
char[] chars = [Link]();
for (char c : chars) {
if ([Link](c)) {
[Link](c, [Link](c) + 1);
}
else {
[Link](c, 1);
}
}
[Link]("Character counts:");
for ([Link]<Character, Integer> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}
[Link]();
}
}
Output:
16.
Code:
import [Link];
public class FullNameConcatenator {
public static void main(String[] args)
Scanner scanner = new Scanner([Link]);
[Link]("Enter your first name: ");
String firstName = [Link]();
[Link]("Enter your last name: ");
String lastName = [Link]();
String fullName = firstName + " " + lastName;
[Link]("Your full name is: " + fullName);
[Link]();
}
Output:
17.
Code:
public class StringManipulation {
public static void main(String[] args)
String A = "The early bird catches the
worm"; String B = "Patience is a virtue";
String wordFromA = [Link](4,
9); String wordFromB =
[Link](14);
String sentence = wordFromA + " " + wordFromB;
String capitalizedSentence = [Link]();
int lastIndexV = [Link]('V');
[Link]("Extracted word from A: " + wordFromA);
[Link]("Extracted word from B: " + wordFromB);
[Link]("Concatenated sentence: " + sentence);
[Link]("Capitalized sentence: " + capitalizedSentence);
[Link]("Last occurrence of 'V': " + lastIndexV);
Ouput:
18.
Code
import [Link];
import [Link];
class TicketBookingSystem
private Queue<String> ticketRequests;
public TicketBookingSystem() {
ticketRequests = new LinkedList<>();
public void addBookingRequest(String customerName) {
[Link](customerName);
[Link]("Booking request added for: " + customerName);
}
public void processBookings() {
[Link]("\nProcessing bookings:");
while (![Link]()) {
String customerName = [Link]();
[Link]("Booking confirmed for: " + customerName);
public void displayBookingStatus() {
[Link]("\nTotal number of bookings: " + [Link]());
[Link]("Pending bookings:");
for (String customerName : ticketRequests) {
[Link](customerName);
public class Mainn {
public static void main(String[] args) {
TicketBookingSystem bookingSystem = new
TicketBookingSystem();
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]();
[Link]();
}
Output:
19.
Code:
import
[Link]; class
Car {
private double price;
private String brand;
private double speed;
public Car(double price, String brand, double speed)
{[Link] = price;
[Link] = brand;
[Link] = speed;
}public double getPrice()
{return price;
}public String getBrand()
{return brand;
}public double getSpeed()
{return speed; }
}public class Main1 {
public static void main(String[] args) {
ArrayList<Car> carList = new ArrayList<>();
[Link](new Car(2500000, "Toyota", 180));
[Link](new Car(1500000, "Honda", 200));
[Link](new Car(3000000, "Ford", 220));
[Link](new Car(1800000, "Nissan", 190));
[Link](new Car(2200000, "Chevrolet",
210));
[Link]("Cars with price over 2000000 takas:");
for (Car car : carList) {
if ([Link]() > 2000000) {
[Link]("Brand: " + [Link]() + ", Price: " + [Link]() + " takas");
Output:
20.
Code:
import [Link];
public class Gradebook
private String[] studentIDs;
private double[] grades;
public Gradebook(int capacity) {
studentIDs = new
String[capacity]; grades = new
double[capacity];
public void addStudent(String studentID, double grade) {
for (int i = 0; i < [Link]; i++) {
if (studentIDs[i] == null) {
studentIDs[i] =
studentID; grades[i] =
grade;
return;
[Link]("Gradebook is full. Cannot add more students.");
public void removeStudent(String studentID) {
for (int i = 0; i < [Link]; i++) {
if (studentIDs[i] != null && studentIDs[i].equals(studentID)) {
studentIDs[i] = null;
grades[i] =
0.0; return;
[Link]("Student ID not found.");
public void displayStudentIDs() {
[Link]("Student IDs:");
for (String id : studentIDs) {
if (id != null) {
[Link](id);
public void displayGrades() {
[Link]("Grades:");
for (int i = 0; i < [Link]; i++)
{ if (studentIDs[i] != null) {
[Link]("Student ID: " + studentIDs[i] + ", Grade: " + grades[i]);
public static void main(String[] args) {
Gradebook gradebook = new Gradebook(5);
[Link]("1001", 85.5);
[Link]("1002", 90.0);
[Link]("1003", 75.0);
[Link]();
[Link]();
[Link]("1002");
[Link]();
[Link]();
Output:
21.
Code:
import [Link];
import [Link];
class Student {
private String name;
private int id;
public Student(String name, int id)
{ [Link] = name;
[Link] = id;
public String getName()
{ return name;
public int getId()
{return id;
}@Override
public String toString() {
return "Student [name=" + name + ", id=" + id + "]";
public class Mainnnn {
public static void main(String[] args) {
Stack<Student> studentStack = new
Stack<>(); Scanner scanner = new
Scanner([Link]); for (int i = 1; i <= 10;
i++) {
[Link](new Student("Student" + i, i));
int menu;
do {
[Link]("\nMenu:");
[Link]("1. Insert a Student object");
[Link]("2. Delete the top Student object");
[Link]("3. Display the top Student object");
[Link]("4. Exit");
[Link]("Enter your choice: ");
menu = [Link]();
switch (menu) {
case 1:
[Link]("Enter student name: ");
String name = [Link]();
[Link]("Enter student id: ");
int id = [Link]();
[Link](new Student(name, id));
[Link]("Student object inserted successfully.");
break;
case 2:
if (![Link]()) {
Student deletedStudent = [Link](); [Link]("Top
Student object deleted: " + deletedStudent);
} else {
[Link]("Stack is empty. No Student object to delete.");
break;
case 3:
if (![Link]()) {
Student topStudent = [Link]();
[Link]("Top Student object: " + topStudent);
} else {
[Link]("Stack is empty. No Student object to display.");
break;
case 4:
[Link]("Exiting the program...");
break;
default:
[Link]("Invalid menu choice. Please enter a valid menu option.");
} while (menu !=
4);[Link]();
Output:
22.
Code:
import
[Link]; import
[Link];
public class StringDuplicateRemover {
public static void main(String[] args) {
List<String> stringList = new
ArrayList<>(); [Link]("apple");
[Link]("banana");
[Link]("apple");
[Link]("orange");
[Link]("banana");
[Link]("grape");
[Link]("banana");
[Link]("List before removing duplicates:");
[Link](stringList);
removeDuplicates(stringList);
[Link]("\nList after removing duplicates:");
[Link](stringList);
public static void removeDuplicates(List<String> stringList)
{ List<String> uniqueList = new ArrayList<>();
for (String str : stringList)
{ if
() {
[Link](str);
[Link]();
[Link](uniqueList);
Output: