0% found this document useful (0 votes)
2 views

java asignmentfinal (1)

The document contains a series of Java programming assignments submitted by a student named Foysal Ahmad to an assistant professor at Bangladesh University of Business and Technology. Each assignment includes code snippets demonstrating various programming concepts such as file reading, exception handling, multithreading, matrix multiplication, and string manipulation. The document is structured with code examples followed by their respective outputs.

Uploaded by

smilingface4eyes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java asignmentfinal (1)

The document contains a series of Java programming assignments submitted by a student named Foysal Ahmad to an assistant professor at Bangladesh University of Business and Technology. Each assignment includes code snippets demonstrating various programming concepts such as file reading, exception handling, multithreading, matrix multiplication, and string manipulation. The document is structured with code examples followed by their respective outputs.

Uploaded by

smilingface4eyes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Bangladesh University of Business and Technology

Assisgement
Course Code:CSE 332
Course Title: Advanced Programming

Submitted By: Submitted To:


Name: Foysal Ahmad Name:Md.Mahbubur 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 java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class FileDataReader {

public static void main(String[] args)

{ try {

File file = new File("data.txt");

Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {

String data = scanner.nextLine();

System.out.println(data);

scanner.close();

} catch (FileNotFoundException e) {

System.err.println("Error: File not found. Please make sure the file exists and is
accessible.");

e.printStackTrace();

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];

System.out.println("Element at index " + indexToAccess + ": " + element);

} catch (ArrayIndexOutOfBoundsException e) {

System.err.println("Error: Invalid index. Index " + indexToAccess + " is out of bounds.");

e.printStackTrace();

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");


}
this.balance = 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);

System.out.println("Initial Balance: " + account.getBalance());

try {
account.deposit(500);

System.out.println("Deposited 500. Current Balance: " + account.getBalance());

} catch (NegativeAmountException e) {

System.out.println("Deposit failed: " + e.getMessage());

}
finally {
System.out.println("Deposit operation completed.");
}

try {
account.withdraw(2000);
System.out.println("Withdrew 2000. Current Balance: " + account.getBalance());

} catch (InsufficientFundsException | NegativeAmountException e) {

System.out.println("Withdrawal failed: " + e.getMessage());


}
finally {
System.out.println("Withdrawal operation completed.");
}

try {
account.deposit(-100);

System.out.println("Deposited -100. Current Balance: " + account.getBalance());

}
catch (NegativeAmountException e)
{
System.out.println("Deposit failed: " + e.getMessage());
}
finally {
System.out.println("Deposit operation completed.");
}

try {
account.withdraw(300);

System.out.println("Withdrew 300. Current Balance: " + account.getBalance());

} catch (InsufficientFundsException | NegativeAmountException e)


{
System.out.println("Withdrawal failed: " + e.getMessage());
}
finally {
System.out.println("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");

this.balance = initialBalance;

public void deposit(double amount) {

if (amount <= 0) {

throw new IllegalArgumentException("Deposit amount must be positive");


}

balance += amount;

System.out.println("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;

System.out.println("Withdrew: " + amount + ", New Balance: " + balance);

public double getBalance()

{ return balance;

public static void main(String[] args)

{try {

BankAccount account = new

BankAccount(1000); account.deposit(500);

account.withdraw(300);

account.withdraw(1500); // This will throw an exception


} catch (InsufficientBalanceException e)

{ System.err.println(e.getMessage());

} catch (IllegalArgumentException e) {

System.err.println(e.getMessage());

Output:

5.

Code:

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

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 = Pattern.compile(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 (!matcher.matches()) {

throw new InvalidEmailFormatException("Invalid email format: " + email);


}
}

public static void main(String[] args) {


Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter your email address: ");
String email = scanner.nextLine();

validateEmail(email);

System.out.println("Email address is valid.");

} catch (InvalidEmailFormatException e) {

System.out.println("Validation failed: " + e.getMessage());

} catch (NullPointerException e) {

System.out.println("Validation failed: " + e.getMessage());


}

}
}

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());

deptThread.start();

nameThread.start();

try {

nameThread.join();

} catch (InterruptedException e) {

idThread.start();

for (int i = 0; i < 10; i++) {

System.out.println("Main thread executing");


try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e) {

class DeptThread implements Runnable {

public void run() {

for (int i = 0; i < 10; i++) {

System.out.println("Dept");

try {

Thread.sleep(2000); // Sleep for 2 seconds

} catch (InterruptedException e) {

class NameThread implements Runnable {

public void run() {

for (int i = 0; i < 20; i++) {


System.out.println("Name");

class IDThread implements Runnable

{@Override

public void run() {

for (int i = 0; i < 30; i++) {

System.out.println("ID");

Output:
7

Code:

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class MatrixMultiplier {

public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {

int row1 = matrix1.length;

int col1 = matrix1[0].length;

int col2 =

matrix2[0].length;

int[][] result = new int[row1][col2];

ExecutorService executor =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (int i = 0; i < row1; i++)

{final int row = i;

executor.submit(() -> {

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;

});

executor.shutdown();

while (!executor.isTerminated())

{} 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) {

System.out.print(num + " ");

System.out.println();

Output:
8.

Code:

public class FactorialCalculator {

static class FactorialThread extends Thread {

private int number;

private long factorial;

public FactorialThread(int number)

{this.number = number;

this.factorial = 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);evenThread.start();

oddThread.start();

try {

evenThread.join();

oddThread.join();

} catch (InterruptedException e)

{ e.printStackTrace();

} long factorial = evenThread.getFactorial() * oddThread.getFactorial();

System.out.println("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++) {

System.out.print(c + " ");

try {

Thread.sleep(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++) {

System.out.print(c + " ");

try {

Thread.sleep(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();

uppercaseThread.start();

lowercaseThread.start();

try {

uppercaseThread.join();

lowercaseThread.join();

} 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) {

this.start = start;

this.end = end;

this.sum = 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) {

thread.start();

for (SumThread thread : threads) {

try {

thread.join();

} catch (InterruptedException e) {

long totalSum = 0;

for (SumThread thread : threads) {

totalSum += thread.getSum();

} System.out.println("Sum of numbers from 1 to 100: " + totalSum);

}
}

Output:

11.

Code:

import java.util.*;

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 = paragraph.replaceAll("[^a-zA-Z ]",

"").toLowerCase().split("\\s+"); Map<String, Integer> wordCounts = new

HashMap<>();

for (String word : words) {

wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);

List<Map.Entry<String, Integer>> sortedWordCounts = new


ArrayList<>(wordCounts.entrySet());
sortedWordCounts.sort((a, b) -> b.getValue().compareTo(a.getValue()));

System.out.println("Word Counts:");

for (Map.Entry<String, Integer> entry : sortedWordCounts) {

System.out.println(entry.getKey() + ": " + entry.getValue());

System.out.println("\nTop 5 Most Common Words:"); int

count = 0;

for (Map.Entry<String, Integer> entry : sortedWordCounts)

{if (count >= 5) {

break;

System.out.println(entry.getKey() + ": " + entry.getValue());

count++;

Output:
12.

Code:

import java.util.Scanner;

public class SubStringChecker

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a sentence: ");

String sentence = scanner.nextLine().toLowerCase();

System.out.print("Enter a word to check: ");

String word = scanner.nextLine().toLowerCase();

boolean isSubstringPresent = sentence.contains(word);

if (isSubstringPresent) {

System.out.println("The word \"" + word + "\" is present as a substring in the


sentence.");

} else {

System.out.println("The word \"" + word + "\" is not present as a substring in the


sentence.");

} scanner.close();

output:
13.

Code:

import java.util.Scanner;

public class CapitalizeWords

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a sentence: ");

String sentence = scanner.nextLine();

String[] words = sentence.split("\\s+");

StringBuilder capitalizedSentence = new

StringBuilder(); for (String word : words) {

if (!word.isEmpty()) {

String capitalizedWord = word.substring(0, 1).toUpperCase() + word.substring(1);

capitalizedSentence.append(capitalizedWord).append(" ");

String result = capitalizedSentence.toString().trim

System.out.println("Original sentence: " + sentence);System.out.println("Capitalized sentence: " + result);


scanner.close();

Output:
14.

Code:

public class ReverseWords {

public static String reverseSentence(String sentence) {

String[] words = sentence.split("\\s+");

StringBuilder reversedSentence = new StringBuilder();

for (int i = words.length - 1; i >= 0; i--) {

reversedSentence.append(words[i]); if

(i > 0) {

reversedSentence.append(" ");

return reversedSentence.toString();

public static void main(String[] args)

{ String sentence = "Hello

world";

String reversedSentence = reverseSentence(sentence);

System.out.println("Original sentence: " + sentence);

System.out.println("Reversed sentence: " + reversedSentence);

}
Output:
15.
Code:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CharacterCounter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = scanner.nextLine();

Map<Character, Integer> charCountMap = new HashMap<>();

char[] chars = input.toCharArray();

for (char c : chars) {

if (charCountMap.containsKey(c)) {

charCountMap.put(c, charCountMap.get(c) + 1);


}
else {
charCountMap.put(c, 1);
}
}

System.out.println("Character counts:");

for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {

System.out.println(entry.getKey() + ": " + entry.getValue());


}

scanner.close();
}
}
Output:

16.

Code:

import java.util.Scanner;

public class FullNameConcatenator {

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your first name: ");

String firstName = scanner.nextLine();

System.out.print("Enter your last name: ");

String lastName = scanner.nextLine();

String fullName = firstName + " " + lastName;

System.out.println("Your full name is: " + fullName);

scanner.close();

}
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 = A.substring(4,

9); String wordFromB =

B.substring(14);

String sentence = wordFromA + " " + wordFromB;

String capitalizedSentence = sentence.toUpperCase();

int lastIndexV = capitalizedSentence.lastIndexOf('V');

System.out.println("Extracted word from A: " + wordFromA);

System.out.println("Extracted word from B: " + wordFromB);

System.out.println("Concatenated sentence: " + sentence);

System.out.println("Capitalized sentence: " + capitalizedSentence);


System.out.println("Last occurrence of 'V': " + lastIndexV);

Ouput:

18.
Code

import java.util.LinkedList;

import java.util.Queue;

class TicketBookingSystem

private Queue<String> ticketRequests;

public TicketBookingSystem() {

ticketRequests = new LinkedList<>();

public void addBookingRequest(String customerName) {

ticketRequests.offer(customerName);

System.out.println("Booking request added for: " + customerName);


}

public void processBookings() {

System.out.println("\nProcessing bookings:");

while (!ticketRequests.isEmpty()) {

String customerName = ticketRequests.poll();


System.out.println("Booking confirmed for: " + customerName);

public void displayBookingStatus() {

System.out.println("\nTotal number of bookings: " + ticketRequests.size());

System.out.println("Pending bookings:");

for (String customerName : ticketRequests) {

System.out.println(customerName);

public class Mainn {

public static void main(String[] args) {

TicketBookingSystem bookingSystem = new

TicketBookingSystem();

bookingSystem.addBookingRequest("Alice");

bookingSystem.addBookingRequest("Bob");

bookingSystem.addBookingRequest("Charlie");

bookingSystem.processBookings();

bookingSystem.displayBookingStatus();

}
Output:

19.

Code:

import

java.util.ArrayList; class

Car {

private double price;

private String brand;

private double speed;

public Car(double price, String brand, double speed)

{this.price = price;

this.brand = brand;

this.speed = 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<>();

carList.add(new Car(2500000, "Toyota", 180));

carList.add(new Car(1500000, "Honda", 200));

carList.add(new Car(3000000, "Ford", 220));

carList.add(new Car(1800000, "Nissan", 190));

carList.add(new Car(2200000, "Chevrolet",

210));

System.out.println("Cars with price over 2000000 takas:");

for (Car car : carList) {

if (car.getPrice() > 2000000) {

System.out.println("Brand: " + car.getBrand() + ", Price: " + car.getPrice() + " takas");

Output:
20.
Code:

import java.util.Arrays;

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 < studentIDs.length; i++) {

if (studentIDs[i] == null) {

studentIDs[i] =

studentID; grades[i] =

grade;

return;

System.out.println("Gradebook is full. Cannot add more students.");

public void removeStudent(String studentID) {

for (int i = 0; i < studentIDs.length; i++) {

if (studentIDs[i] != null && studentIDs[i].equals(studentID)) {


studentIDs[i] = null;

grades[i] =

0.0; return;

System.out.println("Student ID not found.");

public void displayStudentIDs() {

System.out.println("Student IDs:");

for (String id : studentIDs) {

if (id != null) {

System.out.println(id);

public void displayGrades() {

System.out.println("Grades:");

for (int i = 0; i < studentIDs.length; i++)

{ if (studentIDs[i] != null) {

System.out.println("Student ID: " + studentIDs[i] + ", Grade: " + grades[i]);

public static void main(String[] args) {


Gradebook gradebook = new Gradebook(5);

gradebook.addStudent("1001", 85.5);

gradebook.addStudent("1002", 90.0);

gradebook.addStudent("1003", 75.0);

gradebook.displayStudentIDs();

gradebook.displayGrades();

gradebook.removeStudent("1002");

gradebook.displayStudentIDs();

gradebook.displayGrades();

Output:
21.

Code:

import java.util.Scanner;

import java.util.Stack;

class Student {

private String name;

private int id;

public Student(String name, int id)

{ this.name = name;

this.id = 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(System.in); for (int i = 1; i <= 10;

i++) {

studentStack.push(new Student("Student" + i, i));

int menu;

do {

System.out.println("\nMenu:");

System.out.println("1. Insert a Student object");

System.out.println("2. Delete the top Student object");

System.out.println("3. Display the top Student object");

System.out.println("4. Exit");

System.out.print("Enter your choice: ");

menu = scanner.nextInt();

switch (menu) {

case 1:

System.out.print("Enter student name: ");

String name = scanner.next();

System.out.print("Enter student id: ");

int id = scanner.nextInt();

studentStack.push(new Student(name, id));

System.out.println("Student object inserted successfully.");

break;

case 2:
if (!studentStack.isEmpty()) {

Student deletedStudent = studentStack.pop(); System.out.println("Top

Student object deleted: " + deletedStudent);

} else {

System.out.println("Stack is empty. No Student object to delete.");

break;

case 3:

if (!studentStack.isEmpty()) {

Student topStudent = studentStack.peek();

System.out.println("Top Student object: " + topStudent);

} else {

System.out.println("Stack is empty. No Student object to display.");

break;

case 4:

System.out.println("Exiting the program...");

break;

default:

System.out.println("Invalid menu choice. Please enter a valid menu option.");

} while (menu !=

4);scanner.close();

Output:
22.

Code:

import

java.util.ArrayList; import

java.util.List;

public class StringDuplicateRemover {

public static void main(String[] args) {

List<String> stringList = new

ArrayList<>(); stringList.add("apple");

stringList.add("banana");

stringList.add("apple");

stringList.add("orange");
stringList.add("banana");

stringList.add("grape");

stringList.add("banana");

System.out.println("List before removing duplicates:");

System.out.println(stringList);

removeDuplicates(stringList);

System.out.println("\nList after removing duplicates:");

System.out.println(stringList);

public static void removeDuplicates(List<String> stringList)

{ List<String> uniqueList = new ArrayList<>();

for (String str : stringList)

{ if

(!uniqueList.contains(str)) {

uniqueList.add(str);

stringList.clear();

stringList.addAll(uniqueList);

Output:

You might also like