Project Based Learning in Java (24CSH-301 / 24ITH-301) - Lab 1
Experiment 1.1: String Analysis, Matrix Operations, and Banking System
Develop Java programs to analyse strings, perform matrix operations, and
implement basic banking system functionality.
AimImplement Java programs for string analysis, matrix operations, and a banking system with essential features and validations.
ObjectivesTo learn about arrays in Java, and about the usage of loops and switch statements.
Mapped COCO1, CO2
Lab Brief
What You Need To Build
Easy Level
String Character Counter
Write a Java program to analyse a string input by the user. The program
should count the number of vowels, consonants, digits, and special
characters in the string.
Read the full input line using Scanner.
Visit every character using a loop.
Classify each character safely.
Display all four counts clearly.
Medium Level
Matrix Operations
Write a Java program to perform matrix operations (addition, subtraction,
and multiplication) on two matrices provided by the user. The program
should check the dimensions of the matrices to ensure valid operations.
Use 2D arrays to store matrices.
Use nested loops for input, display, and processing.
Validate dimensions before each operation.
Print meaningful messages for invalid operations.
Hard Level
Basic Banking System
Create a Java program to implement a basic banking system with account
creation (Name, Account Number, Balance), deposit and withdrawal
operations, and overdraft prevention.
Model the account with a BankAccount class.
Keep the balance private and change it only through methods.
Check the balance before every withdrawal.
Drive the program with a menu using switch.
Input/Apparatus used:
Hardware - minimum 384 MB RAM, 100 GB hard disk. Software - JDK with any
Java IDE such as Eclipse, NetBeans, or IntelliJ IDEA, or a plain terminal
with javac and java.
Before Coding
Prerequisite Concepts
These are the concepts from the first lecture days that this experiment
depends on. Revise each one before writing any code.
Java Program Structure
Every program needs a class and a main method. The public
class name must match the file name, and execution always starts
from main.
public class Demo {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Data Types, Variables, and Constants
This experiment uses int for counters and matrix elements,
double for money, and String (a reference type)
for text. Declare a variable with a type before use; mark values that must
never change with final.
int count = 0;
double balance = 5000.0;
String name = "Aman";
final double MIN_BALANCE = 0.0;
Operators, Expressions, and Casting
Arithmetic (+ - * / %), relational (== != < > <= >=),
and logical (&& || !) operators build every condition in this lab.
Remember: int / int gives an int, so cast when a
decimal result is needed.
if (amount > 0 && amount <= balance) { ... }
double avg = (double) sum / count;
Reading Input with Scanner
Scanner reads keyboard input. Use nextLine() for
full lines with spaces, nextInt() / nextDouble()
for numbers. After a numeric read, a leftover newline can make the next
nextLine() return empty - consume it first.
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
sc.nextLine(); // consume leftover newline
String name = sc.nextLine();
Control Flow: if-else, switch, Loops
The Easy task classifies characters with if-else. The Medium
task fills and processes matrices with nested for loops. The
Hard task repeats a menu with while and dispatches choices
with switch - end every case with break.
switch (choice) {
case 1: /* deposit */ break;
case 2: /* withdraw */ break;
default: System.out.println("Invalid choice!");
}
Arrays and 2D Arrays
An array stores a fixed-size sequential collection of elements of the same
type, indexed from 0 to length - 1. A matrix is a
two-dimensional array: the first index selects the row, the second the column.
A class is a template; an object is an instance created with new.
For the banking task, keep fields private and expose behaviour
through public methods so the balance can never be modified
without validation.
class BankAccount {
private double balance; // hidden data
public void deposit(double amt) { /* validated */ }
public void withdraw(double amt) { /* validated */ }
}
Constructors
A constructor runs when an object is created and initialises its fields.
It has the same name as the class and no return type. Use
this to distinguish fields from parameters.
String Analysis: Vowels, Consonants, Digits, Special Characters
Problem statement: Write a Java program to analyse a string
input by the user. The program should count the number of vowels, consonants,
digits, and special characters in the string.
Classification Rules
Character type
How to identify it
Vowel
Letter found in AEIOUaeiou
Consonant
Letter but not a vowel
Digit
Character.isDigit(ch)
Special character
Anything that is not a letter or digit, including spaces
Figure 1. Character classification flow for the Easy task.
Algorithm
Start the program and create a Scanner object.
Read the complete string using nextLine().
Initialise counters for vowels, consonants, digits, and special characters.
Loop through every character in the string.
If the character is a letter, check whether it is a vowel or consonant.
If it is not a letter, check whether it is a digit.
If it is neither a letter nor digit, count it as a special character.
Print all counts.
Java Program
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();
int vowelCount = 0;
int consonantCount = 0;
int digitCount = 0;
int specialCount = 0;
String vowels = "AEIOUaeiou";
for (char ch : input.toCharArray()) {
if (Character.isLetter(ch)) {
if (vowels.indexOf(ch) != -1) {
vowelCount++;
} else {
consonantCount++;
}
} else if (Character.isDigit(ch)) {
digitCount++;
} else {
specialCount++;
}
}
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
System.out.println("Digits: " + digitCount);
System.out.println("Special Characters: " + specialCount);
scanner.close();
}
}
Sample Output
Enter a string: Hello World 123!
Vowels: 3
Consonants: 7
Digits: 3
Special Characters: 3
Lab note:
In the sample input, spaces are counted as special characters. If your instructor
wants spaces ignored, add an extra condition before counting a character as special.
Problem statement: Write a Java program to perform matrix
operations (addition, subtraction, and multiplication) on two matrices provided
by the user. The program should check the dimensions of the matrices to ensure
valid operations.
Dimension Rules
Operation
Valid when
Result size
Addition
rowsA == rowsB and colsA == colsB
rowsA x colsA
Subtraction
rowsA == rowsB and colsA == colsB
rowsA x colsA
Multiplication
colsA == rowsB
rowsA x colsB
How Each Element Is Computed
Operation
Formula for result[i][j]
Addition
A[i][j] + B[i][j]
Subtraction
A[i][j] - B[i][j]
Multiplication
Sum of A[i][k] * B[k][j] for every k (row i of A dot column j of B)
Figure 2. Matrix operations are valid only when dimensions satisfy the required rule.
Algorithm
Read rows and columns for Matrix A.
Read all elements of Matrix A using nested loops.
Read rows and columns for Matrix B.
Read all elements of Matrix B using nested loops.
If dimensions are equal, perform addition and subtraction; otherwise print why they are not possible.
If colsA == rowsB, perform multiplication; otherwise print why it is not possible.
Display every result matrix row by row.
Java Program
import java.util.Scanner;
public class MatrixOperations {
public static int[][] inputMatrix(Scanner scanner, int rows, int cols) {
int[][] matrix = new int[rows][cols];
System.out.println("Enter elements for matrix (" + rows + "x" + cols + "):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}
public static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
public static int[][] addMatrices(int[][] a, int[][] b, int rows, int cols) {
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public static int[][] subtractMatrices(int[][] a, int[][] b, int rows, int cols) {
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] - b[i][j];
}
}
return result;
}
public static int[][] multiplyMatrices(
int[][] a, int[][] b, int rowsA, int colsA, int colsB) {
int[][] result = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows and columns for Matrix A: ");
int rowsA = scanner.nextInt();
int colsA = scanner.nextInt();
int[][] matrixA = inputMatrix(scanner, rowsA, colsA);
System.out.print("Enter the number of rows and columns for Matrix B: ");
int rowsB = scanner.nextInt();
int colsB = scanner.nextInt();
int[][] matrixB = inputMatrix(scanner, rowsB, colsB);
if (rowsA == rowsB && colsA == colsB) {
System.out.println("\nMatrix Addition:");
displayMatrix(addMatrices(matrixA, matrixB, rowsA, colsA));
System.out.println("\nMatrix Subtraction:");
displayMatrix(subtractMatrices(matrixA, matrixB, rowsA, colsA));
} else {
System.out.println("\nAddition and subtraction not possible.");
System.out.println("Dimensions must match.");
}
if (colsA == rowsB) {
System.out.println("\nMatrix Multiplication:");
displayMatrix(multiplyMatrices(matrixA, matrixB, rowsA, colsA, colsB));
} else {
System.out.println("\nMultiplication not possible.");
System.out.println("Matrix A columns must equal Matrix B rows.");
}
scanner.close();
}
}
Sample Output
Enter the number of rows and columns for Matrix A: 2 2
Enter elements for matrix (2x2):
1 2
3 4
Enter the number of rows and columns for Matrix B: 2 2
Enter elements for matrix (2x2):
5 6
7 8
Matrix Addition:
6 8
10 12
Matrix Subtraction:
-4 -4
-4 -4
Matrix Multiplication:
19 22
43 50
Worked check:result[0][0] = 1*5 + 2*7 = 19 - row 0 of A multiplied element-wise
with column 0 of B, then summed. Verify one element by hand like this before
trusting the whole output. Also note that nextInt() skips
whitespace, so elements may be typed separated by spaces or newlines.
Problem statement: Create a Java program to implement a basic
banking system with the following features: account creation (Name, Account
Number, Balance), deposit and withdrawal operations, and prevention of
overdraft by checking the balance before withdrawal.
Class Design
Member
Purpose
accountHolderName, accountNumber, balance
Private fields - account state hidden from outside code (encapsulation)
BankAccount(name, accNumber, initialBalance)
Constructor - creates the account with its opening details
deposit(amount)
Adds money only when amount > 0
withdraw(amount)
Deducts money only when amount > 0 and amount <= balance (overdraft prevention)
displayAccountDetails()
Prints holder name, account number, and current balance
Figure 3. The menu loop repeats until the user chooses Exit; withdrawals check the balance first.
Algorithm
Read the account holder name, account number, and initial balance.
Create a BankAccount object using the constructor.
Repeat: display the menu (Deposit, Withdraw, Display Details, Exit) and read the choice.
For Deposit, read the amount and add it to the balance only if it is positive.
For Withdraw, read the amount and deduct it only if it is positive and does not exceed the balance; otherwise report insufficient balance.
For Display Details, print the holder name, account number, and current balance.
For Exit, print a closing message and stop; for any other choice, print an error and show the menu again.
Java Program
import java.util.Scanner;
class BankAccount {
private String accountHolderName;
private String accountNumber;
private double balance;
// Constructor to initialise account
public BankAccount(String name, String accNumber, double initialBalance) {
this.accountHolderName = name;
this.accountNumber = accNumber;
this.balance = initialBalance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Rs." + amount + " deposited successfully.");
} else {
System.out.println("Invalid deposit amount.");
}
}
// Method to withdraw money (overdraft prevented)
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Rs." + amount + " withdrawn successfully.");
} else if (amount > balance) {
System.out.println("Insufficient balance!");
} else {
System.out.println("Invalid withdrawal amount.");
}
}
// Method to display account details
public void displayAccountDetails() {
System.out.println("\nAccount Details:");
System.out.println("Account Holder: " + accountHolderName);
System.out.println("Account Number: " + accountNumber);
System.out.println("Current Balance: Rs." + balance);
}
}
public class BankingSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account Holder Name: ");
String name = scanner.nextLine();
System.out.print("Enter Account Number: ");
String accNumber = scanner.nextLine();
System.out.print("Enter Initial Balance: Rs.");
double initialBalance = scanner.nextDouble();
BankAccount account = new BankAccount(name, accNumber, initialBalance);
System.out.println("\nAccount created successfully!");
while (true) {
System.out.println("\n--- Banking System Menu ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Account Details");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter deposit amount: Rs.");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter withdrawal amount: Rs.");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.displayAccountDetails();
break;
case 4:
System.out.println("Thank you for using our banking system!");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please select a valid option.");
}
}
}
}
Sample Output
Enter Account Holder Name: Aman Kumar
Enter Account Number: CU1234567
Enter Initial Balance: Rs.5000
Account created successfully!
--- Banking System Menu ---
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 1
Enter deposit amount: Rs.2000
Rs.2000.0 deposited successfully.
--- Banking System Menu ---
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 2
Enter withdrawal amount: Rs.10000
Insufficient balance!
--- Banking System Menu ---
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 3
Account Details:
Account Holder: Aman Kumar
Account Number: CU1234567
Current Balance: Rs.7000.0
--- Banking System Menu ---
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 4
Thank you for using our banking system!
Overdraft prevention:
The withdrawal is allowed only when amount > 0 && amount <= balance.
Because balance is private, no code outside
BankAccount can subtract from it directly - every withdrawal is
forced through this check. That is encapsulation doing real work, not just theory.
Review
Quiz and Viva Questions
1. What is an array, and what types of arrays exist in Java?
An array is a fixed-size sequential collection of elements of the same type, indexed from 0. Java supports single-dimensional arrays (int[]) and multi-dimensional arrays (int[][] and beyond).
2. What do you mean by a jagged array?
A jagged array is a 2D array whose rows have different lengths, for example int[][] a = new int[3][]; where each a[i] is later given its own size.
3. What is the static keyword in Java?
static makes a member belong to the class rather than to any object, so it can be used without creating an instance - which is why main is static.
4. What is the use of the final keyword?
final makes a variable a constant (it cannot be reassigned), prevents a method from being overridden, and prevents a class from being extended.
5. Explain the switch statement.
switch compares one expression against several case labels and runs the matching block. Each case usually ends with break to stop fall-through, and default handles unmatched values - exactly how the banking menu dispatches choices.
6. Why is nextLine() used for the Easy string problem?
It reads the complete line, including spaces. Using next() would stop at the first space.
7. Which methods check whether a character is a digit or a letter?
Character.isDigit(ch) checks for a digit, and Character.isLetter(ch) checks for a letter.
8. When are matrix addition and subtraction valid?
They are valid when both matrices have the same number of rows and the same number of columns.
9. When is matrix multiplication valid, and what size is the result?
It is valid when the number of columns in Matrix A equals the number of rows in Matrix B. The result is rowsA x colsB.
10. Why are nested loops used for matrices?
A matrix has rows and columns. One loop moves through rows, and another loop moves through columns; multiplication needs a third loop for the dot product.
11. Why are the fields of BankAccount declared private?
So the balance can only change through deposit() and withdraw(), which validate the amount first. This is encapsulation - hiding data and exposing controlled behaviour.
12. How does the banking program prevent overdraft?
withdraw() checks amount <= balance before deducting. If the amount exceeds the balance, it prints "Insufficient balance!" and leaves the balance unchanged.
13. What is the role of the constructor in the banking program?
BankAccount(name, accNumber, initialBalance) runs when the object is created with new and initialises all three fields, so an account can never exist half-built.