0% found this document useful (0 votes)
3 views33 pages

Java Programming Lab Manual Programs

The document is a solution manual for the Java Programming Concepts course at B.M.S. College of Engineering, detailing the syllabus, course outcomes, and lab instructions for the academic year 2024-25. It includes a variety of programming exercises and examples related to Java, covering topics such as object-oriented programming, string handling, collections, and exception handling. The manual aims to assist students in understanding and implementing Java concepts through practical lab sessions.

Uploaded by

guptabiswas2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

Java Programming Lab Manual Programs

The document is a solution manual for the Java Programming Concepts course at B.M.S. College of Engineering, detailing the syllabus, course outcomes, and lab instructions for the academic year 2024-25. It includes a variety of programming exercises and examples related to Java, covering topics such as object-oriented programming, string handling, collections, and exception handling. The manual aims to assist students in understanding and implementing Java concepts through practical lab sessions.

Uploaded by

guptabiswas2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Code: 24AM4AEJPC Solution Manual

B.M.S. COLLEGE OF ENGINEERING


(An Autonomous Institute, Affiliated to VTU, Belagavi)

DEPARTMENT OF MACHINE LEARNING

JAVA PROGRAMMING CONCEPTS


(Course Code: 24AM4AEJPC)

SOLUTION MANUAL

Lab In-charge

Dr. Sandeep Varma N

Academic Year: 2024-25

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

B.M.S. COLLEGE OF ENGINEERING


(Autonomous Institute, Affiliated to VTU)

VISION
Promoting Prosperity of mankind by augmenting Human Resource Capital through Quality Technical
Education & Training.

MISSION
Accomplish Excellence in the field of Technical Education through Education, Research and Service
needs of society.

DEPARTMENT OF MACHINE LEARNING

VISION
To achieve excellent standards of quality education in the field of Artificial Intelligence and Machine
Learning.
MISSION
To nurture the students with strong fundamentals for a successful carrier in the field of artificial
intelligence and machine learning.
To motivate the students for post-graduation and research.
To create impact in the society with continuous research and innovations.

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

PREFACE
This laboratory manual is prepared by the Department of Machine Learning Introduction
to Artificial Intelligence (22AM4PCIAI). This lab manual can be used as instructional book
for students, staff and instructors to assist in performing and understanding the
programs in Java. In this manual, the programs are as per syllabus prescribed.

INSTRUCTIONS TO THE STUDENTS

Do’s
Learn the topics taught in the instruction class and come well prepared to the laboratory
session.
Update observation & record regularly and get it evaluated by the respective faculty.
Practice additional concepts taught in the instruction class in every lab.
Be obedient and disciplined during the stay in campus.
Maintain cleanliness inside the laboratory.
Damages observed in the laboratory to be informed to the concerned staff immediately.

Don’ts
Usage of cell phones or any other electronic gadgets inside the laboratory.
Eat or drink in the laboratory.
Damage the department belongings.
Meddle with the software programs that are harmful to the laboratory systems.

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

SYLLABUS
Course Title JAVA PROGRAMMING CONCEPTS

Course Code 24AM4AEJPC Credits 1 L-T-P 0-0-1

CIE 50 Marks SEE 100 Marks (50% Weightage)

Contact
Hrs./Week 2 Total Lab Hrs. 12

Sl. No Topics

1. Overview of Java Development Kit, Java Virtual Machine, Java Syntax,


Execution environment and Primitive Datatypes.

2. Demonstration and usage of Wrapper Classes, Boxing and Unboxing


mechanisms.

3. Implement Program on Strings, StringBuilder and StringBuffer

4. Enumerations, Arrays

5. Vector

6. Generics

7. Collections Framework

8. Exception Handling

9. Interface

10. Java Packages

COURSE OUTCOMES
CO1 Apply the core concepts of Java to build console-based applications.
CO2 Analyze the need of Java collection framework to handle group of objects.
CO3 Design and implement robust and modular Java applications using modern integrated
tools.

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

INDEX
Prog Page
Week_# Program Description
No. No.
Part - A
a. Design a membership management system for a fitness center, where
the system should allow gym administrators to store information
about gym members- name, age, membership status(true/false), and

1 1 membership duration (in months). Calculate the membership fee


based on the membership duration using a predefined fee. Display
detailed information of the member.
b. Design JAVA program to print a chessboard pattern.
a. Demonstrate boxing of primitive data types into their corresponding

2 2 wrapper class objects and unbox them back to their primitive


forms.
a. Develop a text processing tool for a language learning platform. The tool needs
to compare strings, concatenate strings, and create copies of strings for various
languages. Implement appropriate Java functionalities.
b. Write a program in Java for String handling which performs the following:
3 3 i. Checks the capacity of String Buffer objects.
ii. Reverses the contents of string given on console and converts the
resultant string in upper case.
iii. Reads a string from console and appends it to the resultant string.
a. Create an enumeration Day of Week with seven values SUNDAY through
SATURDAY. Add a method Workday() to the DayofWeek class that
returns true if the value on which it is called is MONDAY through
FRIDAY.
4 4
b. Design a JAVA program to help a teacher track the exam scores of five
students in a class. The teacher wants to input the exam scores of each
student and then view statistics such as the sum of all scores and the
highest score attained.
5 5 Develop an online shopping platform to manage a dynamic list of products
available for sale.
i. Implement a program called OnlineShoppingManager that uses a
Vector to store product objects. Each product should have attributes for

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

name, price and category.


ii. Design methods in the OnlineShoppingManager class to add products
to the inventory, remove products from the inventory and display all
products in the inventory.
Write a Java program to implement a dynamic, growable queue using generics. The

6 6 queue should be able to store elements of any data type and dynamically resize
itself as needed to accommodate more elements.
Consider a small hospital with a pharmacy that needs a simple inventory
management system to keep track of its medications and medical supplies. Each

7 7 item in the inventory has a unique ID, name, quantity in stock, and price. The
hospital wants functionalities to add new items, update existing items, remove
items, display the list of all items, and search for a specific item by its ID.
Write a JAVA program which has Class called Account that creates account with
Rs500 minimum balance, a deposit() method to deposit amount, a withdraw()
method to withdraw amount and also throws LessBalanceException if an account
holder tries to withdraw money which makes the balance become less than Rs500.
i. A Class called LessBalanceException which returns the statement that says
8 8
withdraw amount (Rs) is not valid.
ii. A Class which creates 2 accounts, both account deposit money and one
account tries to withdraw more money which generates a
LessBalanceException take appropriate action for the same.
Write a JAVA program which has
i. An Interface class for Stack Operations
ii. A Class that implements the Stack Interface and creates a fixed length Stack.

9 9 iii. A Class that implements the Stack Interface and creates a Dynamic length
Stack.
iv. A Class that uses both the above Stacks through Interface reference and
does the Stack operations that demonstrates the runtime binding.
10 10 Define one class A in package apack. In class A, four variables are defined of
access modifiers default, protected, private and public.
Define class B in package bpack which extends A and write display() method
which access variables of class A.
Define class C in package cpack which has one method display() in that create one
object of class A and display its variables.

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

Define class ProtectedDemo in package dpack which contains the main () method.
Create objects of class B and C and call display method for both these objects.
Analyze the program by interpreting the access modifiers and provide valid
conclusion.

1a. Design a membership management system for a fitness center, where the system
should allow gym administrators to store information about gym members- name, age,
membership status(true/false), and membership duration (in months). Calculate the
membership fee based on the membership duration using a predefined fee. Display
detailed information of the member.

import [Link];
public class GymMembershipManager {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user to enter member information
[Link]("Welcome to the Gym Membership Management System!");
[Link]("Enter member name: ");
String name = [Link]();
[Link]("Enter member age: ");
int age = [Link]();
[Link]("Is the membership active? (true/false): ");
boolean isActive = [Link]();
[Link]("Enter membership duration (in months): ");
int duration = [Link]();

// Calculate membership fee (assuming $50 per month)


double membershipFee = duration * 50.0;

// Display member details

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

[Link]("\nMember Details:");
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Membership Status: " + (isActive ? "Active" : "Inactive"));
[Link]("Membership Duration: " + duration + " months");
[Link]("Membership Fee: $" + membershipFee);
[Link]();
}
}

1b. Design JAVA program to print a chessboard pattern.

public class ChessboardPattern {

public static void main(String[] args) {

int size = 8; // Size of the chessboard

// Loop through each row

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

// Loop through each column

for (int j = 0; j < size; j++) {

// Check if the sum of row and column indices is even

if ((i + j) % 2 == 0) {

// Print black square for even sum

[Link]("**");

} else {

// Print white square for odd sum

[Link](" ");

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

// Move to the next line after printing each row

[Link]();

2 a . Demonstrate boxing of primitive data types into their corresponding wrapper class objects
and unbox them back to their primitive forms

public class boxing {

public static void main(String[] args) {

Integer boxedInt = [Link](10);

// Double boxing

Double boxedDouble = [Link](20.5);

// Character boxing

Character boxedChar = [Link]('A');

// Boolean boxing

Boolean boxedBoolean = [Link](true);

// Float boxing

Float boxedFloat = [Link](30.5f);

// Unboxing: Converting wrapper class objects back to their primitive data types

// Integer unboxing

int unboxedInt = [Link]();

// Double unboxing

double unboxedDouble = [Link]();

// Character unboxing

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

char unboxedChar = [Link]();

// Boolean unboxing

boolean unboxedBoolean = [Link]();

// Float unboxing

float unboxedFloat = [Link]();

// Display results

[Link]("Boxed Integer: " + boxedInt);

[Link]("Unboxed Integer: " + unboxedInt);

[Link]("Boxed Double: " + boxedDouble);

[Link]("Unboxed Double: " + unboxedDouble);

[Link]("Boxed Character: " + boxedChar);

[Link]("Unboxed Character: " + unboxedChar);

[Link]("Boxed Boolean: " + boxedBoolean);

[Link]("Unboxed Boolean: " + unboxedBoolean);

[Link]("Boxed Float: " + boxedFloat);

[Link]("Unboxed Float: " + unboxedFloat);

Dept. of MEL, BMSCE Session: Dec 2024- March 2025


Course Code: 24AM4AEJPC Solution Manual

3a. Develop a text processing tool for a language learning platform. The tool needs to compare strings,
concatenate strings, and create copies of strings for various languages. Implement appropriate Java
functionalities.

public class String_Functions {


// Function to compare two strings
public static boolean compareStrings(String str1, String str2) {
return [Link](str2);
}

// Function to copy a string


public static String copyString(String original) {
return new String(original);
}

// Function to concatenate two strings


public static String concatenateStrings(String str1, String str2) {
return str1 + str2;
}
public static void main(String[] args) {

// Test compareStrings function


String str1 = "Hello";
String str2 = "hello";
[Link]("String comparison:");
[Link]("Are the strings equal? " + compareStrings(str1, str2));

// Test copyString function


String original = "Copy me!";
String copied = copyString(original);

11
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

[Link]("\nString copy:");
[Link]("Original string: " + original);
[Link]("Copied string: " + copied);

// Test concatenateStrings function


String part1 = "Hello, ";
String part2 = "world!";
String concatenated = concatenateStrings(part1, part2);
[Link]("\nString concatenation:");
[Link]("Concatenated string: " + concatenated);
}
}

3b. Write a program in Java for String handling which performs the following:
i. Checks the capacity of String Buffer objects.
ii. Reverses the contents of string given on console and converts the resultant string in upper
case.
iii. Reads a string from console and appends it to the resultant string.

import [Link];

public class StringBufferHandling {


public static void main(String[] args) {
// Task i: Checking capacity of StringBuffer objects
StringBuffer sb1 = new StringBuffer();
[Link]("Capacity of StringBuffer object sb1: " + [Link]());

StringBuffer sb2 = new StringBuffer("Hello");


[Link]("Capacity of StringBuffer object sb2: " + [Link]());

12
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

// Task ii: Reversing the contents of string and converting to uppercase


Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();

StringBuffer reversedBuffer = new StringBuffer(inputString);


[Link]();
String reversedUpperCase = [Link]().toUpperCase();
[Link]("Reversed string in uppercase: " + reversedUpperCase);

// Task iii: Reading a string from console and appending it


[Link]("Enter a string to append: ");
String appendString = [Link]();
[Link](appendString);
[Link]("String after appending: " + reversedBuffer);

[Link]();
}
}

4 a . Create an enumeration Day of Week with seven values SUNDAY through SATURDAY. Add a
method Workday() to the DayofWeek class that returns true if the value on which it is called is
MONDAY through FRIDAY.

import [Link];
public class Enumeration {
public enum DayOfWeek {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,

13
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

THURSDAY,
FRIDAY,
SATURDAY;

// Method to check if the day is a workday (Monday to Friday)


public boolean isWorkday() {
return (this != SATURDAY && this != SUNDAY);
}
}
public static void main(String[] args) {
// Check if Monday is a workday
[Link]("Is Monday a workday? " + [Link]());

// Check if Saturday is a workday


[Link]("Is Saturday a workday? " + [Link]());
}
}

4b. Design a JAVA program to help a teacher track the exam scores of five students in a class. The
teacher wants to input the exam scores of each student and then view statistics such as the sum of all
scores and the highest score attained.
import [Link];

public class ExamScoreTracker {


public static void main(String[] args) {
final int NUM_STUDENTS = 5;
int[] examScores = new int[NUM_STUDENTS];

// Input exam scores for each student


Scanner scanner = new Scanner([Link]);
[Link]("Enter exam scores for each student:");

14
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

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


[Link]("Enter score for student " + (i + 1) + ": ");
examScores[i] = [Link]();
}

// Calculate sum of scores and highest score


int sum = 0;
int highestScore = examScores[0];
for (int score : examScores) {
sum += score;
if (score > highestScore) {
highestScore = score;
}
}

// Display statistics
[Link]("\nExam score statistics:");
[Link]("Sum of all scores: " + sum);
[Link]("Highest score attained: " + highestScore);
}
}

5. Develop an online shopping platform to manage a dynamic list of products available for sale.

i. Implement a program called OnlineShoppingManager that uses a Vector to store product


objects. Each product should have attributes for name, price and category.
ii. Design methods in the OnlineShoppingManager class to add products to the inventory,
remove products from the inventory and display all products in the inventory.
import [Link];
class Product {

15
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

String name;
double price;
String category;
public Product(String name, double price, String category) {
[Link] = name;
[Link] = price;
[Link] = category;

}
}

public class OnlineShoppingManager {


private Vector<Product> inventory;

public OnlineShoppingManager() {
inventory = new Vector<>();
}

public void addProduct(String name, double price, String category) {


Product product = new Product(name, price, category);
[Link](product);
}

public void removeProduct(String name) {


for (int i = 0; i < [Link](); i++) {
if ([Link](i).[Link](name)) {
[Link](i);
break;
}
}
}

16
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

public void displayInventory() {


[Link]("Inventory:");
for (Product product : inventory) {
[Link]("Name: " + [Link] + ", Price: " + [Link] + ", Category: "
+ [Link] );
}
}

public static void main(String[] args) {


OnlineShoppingManager manager = new OnlineShoppingManager();

// Add some products to the inventory


[Link]("Laptop", 40000, "Electronics");
[Link]("T-shirt", 550, "Clothing");
[Link]("Book", 920, "Books");

// Display all products in the inventory


[Link]();

// Remove a product
[Link]("Book");

// Display updated inventory


[Link]();

[Link]("Laptop");

// Display updated inventory


[Link]();
}

17
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

6. Write a Java program to implement a dynamic, growable queue using generics. The queue should be
able to store elements of any data type and dynamically resize itself as needed to accommodate more
elements.
import [Link];
public class GQueue<T> {
T[] que;
static int size;
public GQueue() {
que = (T[]) new Object[2];
size = 0;
}
public void enqueue(T element) {
if (size == [Link]) {
int newCapacity = [Link] * 2;
que = [Link](que, newCapacity);
}
que[size++] = element;
}

public T dequeue() {
if (size==0) {
[Link]("Queue is empty");
}
T del_element = que[0];
[Link](que, 1, que, 0, size - 1);
que[--size] = null;

18
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

return del_element;
}
public void display() {
for (T element : que) {
[Link](element);
}
}
public static void main(String[] args) {
// Create a GrowableQueue of integers
GQueue<Integer> integerQueue = new GQueue<>();
// Enqueue elements
[Link](10);
[Link](20);
[Link](30);

[Link]("ELements in the queue are:");


[Link]();
// Dequeue an element
int dequeuedElement = [Link]();
[Link]("Dequeued element: " + dequeuedElement);

// Display size of the queue


[Link]("Queue size: " +(++size));

}
}

7. Consider a small hospital with a pharmacy that needs a simple inventory management system to keep
track of its medications and medical supplies. Each item in the inventory has a unique ID, name, quantity
in stock, and price. The hospital wants functionalities to add new items, update existing items, remove
items, display the list of all items, and search for a specific item by its ID.

19
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

import [Link];

class Pharmacy {
public final int id;
public final String name;
public int quantity;
public double price;

public Pharmacy(int id, String name, int quantity, double price) {


[Link] = id;
[Link] = name;
[Link] = quantity;
[Link] = price;
}
}

public class PharmacyManagementSystem {


private ArrayList<Pharmacy> inventory = new ArrayList<>();

// Add new item to inventory


public void addItem(Pharmacy item) {
[Link](item);
}

// Update existing item in inventory


public void updateItem(int id, int quantity, double price) {
for (Pharmacy item : inventory) {
if ([Link] == id) {
[Link] = quantity;
[Link] = price;

20
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

break;
}
}
}
// Remove item from inventory
public void removeItem(int id) {
[Link](item -> [Link] == id);
}

// Display list of all items


public void displayInventory() {
[Link]("Inventory:");
for (Pharmacy item : inventory) {
[Link]([Link] + " | " + [Link] + " | Quantity: " + [Link] + " |
Price: " + [Link]);
}
}

// Search for item by ID


public Pharmacy searchItemByID(int id) {
for (Pharmacy item : inventory) {
if ([Link] == id) {
return item;
}
}
return null; // Item not found
}

public static void main(String[] args) {


PharmacyManagementSystem ims = new PharmacyManagementSystem();

21
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

// Adding sample items


[Link](new Pharmacy(1, "Crocin", 100, 2.5));
[Link](new Pharmacy(2, "Calpol", 50, 3.0));
[Link](new Pharmacy(3, "Crickmol", 200, 1.0));

// Displaying inventory
[Link]();

// Updating an item
[Link](1, 90, 2.0);

// Displaying inventory after update


[Link]();

// Searching for an item


[Link]("Searching for item with ID 2:");
Pharmacy foundItem = [Link](2);
if (foundItem != null) {
[Link]("Item found: " + [Link]);
} else {
[Link]("Item not found.");
}

// Removing an item
[Link](2);

// Displaying inventory after removal


[Link]();
}
}

22
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

8. Write a JAVA program which has Class called Account that creates account with Rs500 minimum
balance, a deposit() method to deposit amount, a withdraw() method to withdraw amount and also throws
LessBalanceException if an account holder tries to withdraw money which makes the balance become
less than Rs500.

i. A Class called LessBalanceException which returns the statement that says withdraw amount (Rs) is
not valid.

ii. A Class which creates 2 accounts, both account deposit money and one account tries to withdraw
more money which generates a LessBalanceException take appropriate action for the same.
class LessBalanceException extends Exception {
public LessBalanceException(double amount) {
super("Withdraw amount (" + amount + " Rs) is not possible. ");
}
}

class Account {
double balance;
static final double MIN_BALANCE = 500;

public Account() {
balance = MIN_BALANCE;
}

public void deposit(double amount) {


balance += amount;
[Link]("Deposited " + amount + " Rs. New balance: " + balance + "
Rs");
}

public void withdraw(double amount) throws LessBalanceException {


if (balance - amount < MIN_BALANCE) {
throw new LessBalanceException(amount);

23
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

}
balance -= amount;
[Link]("Withdrawn " + amount + " Rs. New balance: " + balance + "
Rs");
}

public double getBalance() {


return balance;
}
}

public class TestAccount {


public static void main(String[] args) {
Account account1 = new Account();
Account account2 = new Account();

// Deposit money into both accounts


[Link](1000);
[Link](700);

// Try to withdraw from account1


try {
[Link](1600);
} catch (LessBalanceException e) {
[Link]("LessBalanceException: " + [Link]());
}

// Try to withdraw from account2


try {
[Link](200);
} catch (LessBalanceException e) {

24
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

[Link]("LessBalanceException: " + [Link]());


}
}
}

9. Write a JAVA program which has


i. An Interface class for Stack Operations
ii. A Class that implements the Stack Interface and creates a fixed length Stack.
iii. A Class that implements the Stack Interface and creates a Dynamic length Stack.
iv. A Class that uses both the above Stacks through Interface reference and does the Stack
operations that demonstrates the runtime binding.

// i. Interface for Stack Operations


interface Stack {
void push(int element);
int pop();
boolean isEmpty();
int size();
}

// ii. Fixed-Length Stack Implementation


class FixedLengthStack implements Stack {
private int[] stackArray;
private int top;
private int capacity;

public FixedLengthStack(int capacity) {


[Link] = capacity;

25
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

[Link] = new int[capacity];


[Link] = -1;
}

@Override
public void push(int element) {
if (top == capacity - 1) {
[Link]("Stack Overflow: Cannot push element, stack is full.");
return;
}
stackArray[++top] = element;
}

@Override
public int pop() {
if (isEmpty()) {
[Link]("Stack Underflow: Cannot pop element, stack is empty.");
return -1;
}
return stackArray[top--];
}

@Override
public boolean isEmpty() {
return top == -1;
}

@Override
public int size() {
return top + 1;
}

26
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

// iii. Dynamic-Length Stack Implementation


class DynamicLengthStack implements Stack {
private int[] stackArray;
private int top;
private int capacity;

public DynamicLengthStack() {
[Link] = 10; // Initial capacity
[Link] = new int[capacity];
[Link] = -1;
}

@Override
public void push(int element) {
if (top == capacity - 1) {
// If the stack is full, double the capacity
capacity *= 2;
int[] newStackArray = new int[capacity];
[Link](stackArray, 0, newStackArray, 0, [Link]);
stackArray = newStackArray;
}
stackArray[++top] = element;
}

@Override
public int pop() {
if (isEmpty()) {
[Link]("Stack Underflow: Cannot pop element, stack is empty.");
return -1;

27
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

}
return stackArray[top--];
}

@Override
public boolean isEmpty() {
return top == -1;
}

@Override
public int size() {
return top + 1;
}
}

// iv. Class Demonstrating Runtime Binding and Stack Operations


class StackOperations {
public static void main(String[] args) {
// Using FixedLengthStack through Interface reference
Stack fixedStack = new FixedLengthStack(5);
[Link]("Fixed Length Stack Operations:");
performStackOperations(fixedStack);

// Using DynamicLengthStack through Interface reference


Stack dynamicStack = new DynamicLengthStack();
[Link]("\nDynamic Length Stack Operations:");
performStackOperations(dynamicStack);
}

public static void performStackOperations(Stack stack) {


[Link]("Stack Size: " + [Link]());

28
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

[Link](10);
[Link]("Stack Size: " + [Link]());
[Link](20);
[Link]("Stack Size: " + [Link]());
[Link](30);
[Link]("Stack Size: " + [Link]());
[Link]("Pop: " + [Link]());
[Link]("Stack Size: " + [Link]());
[Link]("Pop: " + [Link]());
[Link]("Stack Size: " + [Link]());
[Link]("Is Empty: " + [Link]());
[Link]("Stack Size: " + [Link]());
[Link]("Pop: " + [Link]());
[Link]("Stack Size: " + [Link]());
[Link]("Is Empty: " + [Link]());
}
}

29
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

10.
Define one class A in package apack. In class A, four variables are defined of access
modifiers default, protected, private and public.
Define class B in package bpack which extends A and write display() method which access
variables of class A.
Define class C in package cpack which has one method display() in that create one object of
class A and display its variables.
Define class ProtectedDemo in package dpack which contains the main () method.
Create objects of class B and C and call display method for both these objects. Analyze the
program by interpreting the access modifiers and provide valid conclusion.

30
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

31
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

From Class B:
Protected: 20
Public: 40

From Class C:
Public: 40

32
Dept. of MEL, BMSCE Session: June 2023- Sept 2023
Course Code: 24AM4AEJPC Solution Manual

33
Dept. of MEL, BMSCE Session: June 2023- Sept 2023

You might also like