0% found this document useful (0 votes)
9 views28 pages

OOPS - RECORD-1 (1) Kaaviya

Uploaded by

rohini sr
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)
9 views28 pages

OOPS - RECORD-1 (1) Kaaviya

Uploaded by

rohini sr
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
You are on page 1/ 28

REG.NO.

: 211423104269

SOLVING QUADRATIC EQUATION


PROGRAM:
import java.util.Scanner;
public class Quadratic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the coefficients from the user


System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
double c = scanner.nextDouble();

// Compute the discriminant


double discriminant = b * b - 4 * a * c;

// Calculate and print the roots based on the discriminant


if (discriminant > 0) {
// Two real and distinct roots
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are: " + root1 + " and " + root2);
} else if (discriminant == 0) {
// One real root (both roots are the same)
double root = -b / (2 * a);
System.out.println("The root is: " + root);
} else {
// No real roots
System.out.println("No real roots.");
}
scanner.close();
}
}

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

OUTPUT:

RESULT:

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

FIBONACCI SERIES
PROGRAM:
a) WITH RECURSIVE FUNCTION
import java.util.Scanner;
public class RecursiveFibonacci {
// Recursive method to calculate Fibonacci
public static int fibonacci(int n) {
if (n <= 1)
{
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int terms = scanner.nextInt();
System.out.println("Fibonacci Sequence using recursion:");
for (int i = 0; i < terms; i++)
{
System.out.print(fibonacci(i) + " ");
}
}
}

OUTPUT:

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

b) WITH NON-RECURSIVE FUNCTION


import java.util.Scanner;
public class NonRecursiveFibonacci {
// Iterative method to calculate Fibonacci
public static void fibonacci(int terms) {
int first = 0, second = 1;
System.out.print(first + " " + second + " ");
for (int i = 2; i < terms; i++) {
int next = first + second;
System.out.print(next + " ");
first = second;
second = next;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int terms = scanner.nextInt();
System.out.println("Fibonacci Sequence using Iteration:");
fibonacci(terms);
}
}

OUTPUT:

RESULT:

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

STRING SORTING

PROGRAM:
import java.util.Scanner;

public class SortNames{


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of names: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] names = new String[n];

System.out.println("Enter the names:");


for (int i = 0; i < n; i++) {
names[i] = scanner.nextLine();
}

// Sort the names using compareTo() method


for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (names[i].compareTo(names[j]) > 0) {
// Swap names[i] and names[j]
String temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println("Names in ascending order:");
for (String name : names) {
System.out.println(name);
}
}
}

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

OUTPUT:

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

PRINTING PRIME NUMBERS


PROGRAM:
import java.util.Scanner;
public class SimplePrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the upper limit from the user
System.out.print("Enter an integer: ");
int limit = scanner.nextInt();
// Print all prime numbers up to the limit
System.out.println("Prime numbers up to " + limit + ":");
for (int i = 2; i <= limit; i++) {
boolean isPrime = true;
// Check if 'i' is a prime number
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break; // No need to check further if a divisor is found
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}

OUTPUT :

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

MATRIX MULTIPLICATION
PROGRAM:
import java.io.*;
import java.util.Scanner;
class GFG {
// Function to print Matrix
static void printMatrix(int M[][], int rowSize, int colSize) {
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
}
}
// Function to multiply two matrices A[][] and B[][]
static void multiplyMatrix(int row1, int col1, int A[][], int row2, int col2, int B[][])
{
int i, j, k;
// Print the matrices A and B
System.out.println("\nMatrix A:");
printMatrix(A, row1, col1);
System.out.println("\nMatrix B:");
printMatrix(B, row2, col2);
// Check if multiplication is possible
if (col1 != row2) {
System.out.println("\nMultiplication Not Possible");
return;
}
// Matrix to store the result
int C[][] = new int[row1][col2];
// Multiply the two matrices
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < col1; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
// Print the result
System.out.println("\nResultant Matrix:");
printMatrix(C, row1, col2);
}
// Driver code
public static void main(String[] args) {

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

Scanner scanner = new Scanner(System.in);


// Input dimensions for the first matrix
System.out.print("Enter number of rows for Matrix A: ");
int row1 = scanner.nextInt();
System.out.print("Enter number of columns for Matrix A: ");
int col1 = scanner.nextInt();
int A[][] = new int[row1][col1];
System.out.println("Enter elements of Matrix A:");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
A[i][j] = scanner.nextInt();
}
}
// Input dimensions for the second matrix
System.out.print("Enter number of rows for Matrix B: ");
int row2 = scanner.nextInt();
System.out.print("Enter number of columns for Matrix B: ");
int col2 = scanner.nextInt();
// Check if multiplication is possible
if (col1 != row2) {
System.out.println("\nMultiplication Not Possible");
scanner.close();
return;
}
int B[][] = new int[row2][col2];
System.out.println("Enter elements of Matrix B:");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
B[i][j] = scanner.nextInt();
}
}
// Multiply the matrices
multiplyMatrix(row1, col1, A, row2, col2, B);
scanner.close();
}
}

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

OUTPUT :

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

PALINDROME PROGRAM
PROGRAM:
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();
// Remove spaces and convert to lowercase
String cleanedInput = input.replaceAll("\\s+", "").toLowerCase();
if (isPalindrome(cleanedInput)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}

public static boolean isPalindrome(String str) {


int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

OUTPUT :

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

GENERATING ELECTRICITY BILL


PROGRAM:
import java.util.*;
class Ebill {
public static void main(String args[]) {
customerdata ob = new customerdata();
ob.getdata();
ob.calc();
ob.display();
}
}
class customerdata {
Scanner in = new Scanner(System.in);
Scanner ins = new Scanner(System.in);
String cname, type;
int bn;
double current, previous, tbill, units;
void getdata() {
System.out.print("\n\t Enter Consumer Number: ");
bn = in .nextInt();
System.out.print("\n\t Enter Type of Connection (D for Domestic or C for
Commercial): ");
type = ins.nextLine();
System.out.print("\n\t Enter Consumer Name: ");
cname = ins.nextLine();
System.out.print("\n\t Enter Previous Month Reading: ");
previous = in .nextDouble();
System.out.print("\n\t Enter Current Month Reading: ");
current = in .nextDouble();
}
void calc() {
units = current - previous;
if (type.equals("D")) {
if (units <= 100 && units <= 100)
tbill = 1 * units;
else if (units > 100 && units <= 200)
tbill = 100 + (units - 100) * 2.50;
else if (units > 200 && units <= 500)
tbill = 350 + (units - 200) * 4;
else if (units > 500)
tbill = 1550 + (units - 500) * 6;
} else {

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

if (units <= 100)


tbill = 2 * units;
else if (units > 100 && units <= 200)
tbill = 200 + (units - 100) * 4.50;
else if (units > 200 && units <= 500)
tbill = 650 + (units - 200) * 6;
else
tbill = 2450 + (units - 500) * 7;
}
}
void display() {
System.out.println("\n\t Consumer Number = " + bn);
System.out.println("\n\t Consumer Name = " + cname);
if (type.equals("D"))
System.out.println("\n\t Type Of Connection = DOMESTIC ");
else
System.out.println("\n\t Type Of Connection = COMMERCIAL ");
System.out.println("\n\t Current Month Reading = " + current);
System.out.println("\n\t Previous Month Reading = " + previous);
System.out.println("\n\t Total Units = " + units);
System.out.println("\n\t Total Bill = RS " + tbill);
}
}

OUTPUT :

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

IMPLEMENTING CONVERTER USING PACKAGES


PROGRAM:
Currency.java
package currencyconversion;
import java.util.Scanner;

public class Currency {


double inr, usd, euro, yen;
Scanner in = new Scanner(System.in);

public void dollarToRupee() {


System.out.println("Enter dollars to convert into Rupees:");
usd = in.nextDouble();
inr = usd * 67;
System.out.println("Dollar = " + usd + " is equal to INR = " + inr);
}

public void rupeeToDollar() {


System.out.println("Enter Rupees to convert into Dollars:");
inr = in.nextDouble();
usd = inr / 67;
System.out.println("Rupee = " + inr + " is equal to USD = " + usd);
}

public void euroToRupee() {


System.out.println("Enter euros to convert into Rupees:");
euro = in.nextDouble();
inr = euro * 79.50;
System.out.println("Euro = " + euro + " is equal to INR = " + inr);
}

public void rupeeToEuro() {


System.out.println("Enter Rupees to convert into Euros:");
inr = in.nextDouble();
euro = inr / 79.50;
System.out.println("Rupee = " + inr + " is equal to Euro = " + euro);
}

public void yenToRupee() {


System.out.println("Enter yen to convert into Rupees:");
yen = in.nextDouble();
inr = yen * 0.61;

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

System.out.println("Yen = " + yen + " is equal to INR = " + inr);


}

public void rupeeToYen() {


System.out.println("Enter Rupees to convert into Yen:");
inr = in.nextDouble();
yen = inr / 0.61;
System.out.println("INR = " + inr + " is equal to Yen = " + yen);
}
}

Distance.java
package distanceconversion;
import java.util.Scanner;

public class Distance {


double km, m, miles;
Scanner sc = new Scanner(System.in);

public void kmToMeter() {


System.out.print("Enter kilometers: ");
km = sc.nextDouble();
m = km * 1000;
System.out.println(km + " km is equal to " + m + " meters");
}

public void meterToKm() {


System.out.print("Enter meters: ");
m = sc.nextDouble();
km = m / 1000;
System.out.println(m + " meters is equal to " + km + " kilometers");
}

public void milesToKm() {


System.out.print("Enter miles: ");
miles = sc.nextDouble();
km = miles * 1.60934;
System.out.println(miles + " miles is equal to " + km + " kilometers");
}

public void kmToMiles() {


System.out.print("Enter kilometers: ");
km = sc.nextDouble();

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

miles = km * 0.621371;
System.out.println(km + " km is equal to " + miles + " miles");
}
}

Timer.java
package timeconversion;
import java.util.Scanner;

public class Timer {


int hours, minutes, seconds, input;
Scanner sc = new Scanner(System.in);

public void secondsToHours() {


System.out.print("Enter the number of seconds: ");
input = sc.nextInt();
hours = input / 3600;
minutes = (input % 3600) / 60;
seconds = (input % 3600) % 60;
System.out.println("Hours: " + hours + " Minutes: " + minutes + " Seconds: " +
seconds);
}

public void minutesToHours() {


System.out.print("Enter the number of minutes: ");
minutes = sc.nextInt();
hours = minutes / 60;
minutes = minutes % 60;
System.out.println("Hours: " + hours + " Minutes: " + minutes);
}

public void hoursToMinutes() {


System.out.print("Enter the number of hours: ");
hours = sc.nextInt();
minutes = hours * 60;
System.out.println("Minutes: " + minutes);
}

public void hoursToSeconds() {


System.out.print("Enter the number of hours: ");
hours = sc.nextInt();
seconds = hours * 3600;
System.out.println("Seconds: " + seconds);

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

}
}

Converter.java
import currencyconversion.Currency;
import distanceconversion.Distance;
import timeconversion.Timer;
import java.util.Scanner;

public class Converter {


public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int choice;
Currency c = new Currency();
Distance d = new Distance();
Timer t = new Timer();

do {
System.out.println("1. Dollar to Rupee");
System.out.println("2. Rupee to Dollar");
System.out.println("3. Euro to Rupee");
System.out.println("4. Rupee to Euro");
System.out.println("5. Yen to Rupee");
System.out.println("6. Rupee to Yen");
System.out.println("7. Kilometer to Meter");
System.out.println("8. Meter to Kilometer");
System.out.println("9. Miles to Kilometer");
System.out.println("10. Kilometer to Miles");
System.out.println("11. Hours to Minutes");
System.out.println("12. Hours to Seconds");
System.out.println("13. Seconds to Hours");
System.out.println("14. Minutes to Hours");
System.out.println("15. Exit");
System.out.print("Enter your choice: ");
choice = s.nextInt();
switch (choice) {
case 1: c.dollarToRupee(); break;
case 2: c.rupeeToDollar(); break;
case 3: c.euroToRupee(); break;
case 4: c.rupeeToEuro(); break;
case 5: c.yenToRupee(); break;
case 6: c.rupeeToYen(); break;
case 7: d.kmToMeter(); break;

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

case 8: d.meterToKm(); break;


case 9: d.milesToKm(); break;
case 10: d.kmToMiles(); break;
case 11: t.hoursToMinutes(); break;
case 12: t.hoursToSeconds(); break;
case 13: t.secondsToHours(); break;
case 14: t.minutesToHours(); break;
case 15: System.out.println("Exiting..."); break;
default: System.out.println("Invalid choice! Please try again.");
}
} while (choice != 15);
s.close();
}
}

OUTPUT:

RESULT:

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

GENERATE PAY SLIPS FOR EMPLOYEES USING


INHERITANCE
PROGRAM:
import java.util.Scanner;

class Employee {
String empName;
int empId;
String address;
String emailId;
String mobileNo;
Employee(String empName, int empId, String address, String emailId, String
mobileNo) {
this.empName = empName;
this.empId = empId;
this.address = address;
this.emailId = emailId;
this.mobileNo = mobileNo;
}
public void displayEmployeeDetails() {
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Address: " + address);
System.out.println("Email ID: " + emailId);
System.out.println("Mobile No: " + mobileNo);
}
}

class Programmer extends Employee {


double basicPay;
Programmer(String empName, int empId, String address, String emailId, String
mobileNo, double basicPay) {
super(empName, empId, address, emailId, mobileNo);
this.basicPay = basicPay;
}

public void generatePaySlip() {


double da = 0.97 * basicPay; // Dearness Allowance
double hra = 0.10 * basicPay; // House Rent Allowance
double pf = 0.12 * basicPay; // Provident Fund
double staffClubFund = 0.001 * basicPay; // Staff Club Fund

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

double grossSalary = basicPay + da + hra; // Correct initialization of gross salary


double deductions = pf + staffClubFund; // Correct initialization of deductions
// Calculating net salary
double netSalary = grossSalary - deductions;
// Displaying the pay slip
System.out.println("\n--- Pay Slip for Programmer ---");
displayEmployeeDetails();
System.out.println("Basic Pay: " + basicPay);
System.out.println("DA: " + da);
System.out.println("HRA: " + hra);
System.out.println("PF: " + pf);
System.out.println("Staff Club Fund: " + staffClubFund);
System.out.println("Gross Salary: " + grossSalary);
System.out.println("Deductions: " + deductions);
System.out.println("Net Salary: " + netSalary); // No errors in net salary
calculation
}
}

class AssistantProfessor extends Employee {


double basicPay;
AssistantProfessor(String empName, int empId, String address, String emailId,
String mobileNo, double basicPay) {
super(empName, empId, address, emailId, mobileNo);
this.basicPay = basicPay;
}

public void generatePaySlip() {


double da = 0.97 * basicPay;
double hra = 0.10 * basicPay;
double pf = 0.12 * basicPay;
double staffClubFund = 0.001 * basicPay;
double grossSalary = basicPay + da + hra;
double deductions = pf + staffClubFund;
double netSalary = grossSalary - deductions;
System.out.println("\n--- Pay Slip for Assistant Professor ---");
displayEmployeeDetails();
System.out.println("Basic Pay: " + basicPay);
System.out.println("DA: " + da);
System.out.println("HRA: " + hra);
System.out.println("PF: " + pf);
System.out.println("Staff Club Fund: " + staffClubFund);
System.out.println("Gross Salary: " + grossSalary);

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

System.out.println("Deductions: " + deductions);


System.out.println("Net Salary: " + netSalary);
}
}
class AssociateProfessor extends Employee {
double basicPay;
AssociateProfessor(String empName, int empId, String address, String emailId,
String mobileNo, double basicPay) {
super(empName, empId, address, emailId, mobileNo);
this.basicPay = basicPay;
}

public void generatePaySlip() {


double da = 0.97 * basicPay;
double hra = 0.10 * basicPay;
double pf = 0.12 * basicPay;
double staffClubFund = 0.001 * basicPay;
double grossSalary = basicPay + da + hra;
double deductions = pf + staffClubFund;
double netSalary = grossSalary - deductions;
System.out.println("\n--- Pay Slip for Associate Professor ---");
displayEmployeeDetails();
System.out.println("Basic Pay: " + basicPay);
System.out.println("DA: " + da);
System.out.println("HRA: " + hra);
System.out.println("PF: " + pf);
System.out.println("Staff Club Fund: " + staffClubFund);
System.out.println("Gross Salary: " + grossSalary);
System.out.println("Deductions: " + deductions);
System.out.println("Net Salary: " + netSalary);
}
}

class Professor extends Employee {


double basicPay;
Professor(String empName, int empId, String address, String emailId, String
mobileNo, double basicPay) {
super(empName, empId, address, emailId, mobileNo);
this.basicPay = basicPay;
}

public void generatePaySlip() {


double da = 0.97 * basicPay;

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

double hra = 0.10 * basicPay;


double pf = 0.12 * basicPay;
double staffClubFund = 0.001 * basicPay;
double grossSalary = basicPay + da + hra;
double deductions = pf + staffClubFund;
double netSalary = grossSalary - deductions;
System.out.println("\n--- Pay Slip for Professor ---");
displayEmployeeDetails();
System.out.println("Basic Pay: " + basicPay);
System.out.println("DA: " + da);
System.out.println("HRA: " + hra);
System.out.println("PF: " + pf);
System.out.println("Staff Club Fund: " + staffClubFund);
System.out.println("Gross Salary: " + grossSalary);
System.out.println("Deductions: " + deductions);
System.out.println("Net Salary: " + netSalary);
}
}

public class EmployeePayrollSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter employee details:");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Address: ");
String address = scanner.nextLine();
System.out.print("Email: ");
String email = scanner.nextLine();
System.out.print("Mobile No: ");
String mobile = scanner.nextLine();
System.out.println("\nChoose Designation:");
System.out.println("1. Programmer");
System.out.println("2. Assistant Professor");
System.out.println("3. Associate Professor");
System.out.println("4. Professor");
int choice = scanner.nextInt();
System.out.print("Enter Basic Pay: ");
double basicPay = scanner.nextDouble();

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

switch (choice) {
case 1:
Programmer programmer = new Programmer(name, id, address, email,
mobile, basicPay);
programmer.generatePaySlip();
break;

case 2:
AssistantProfessor assistantProfessor = new AssistantProfessor(name, id,
address, email, mobile, basicPay);
assistantProfessor.generatePaySlip();
break;

case 3:
AssociateProfessor associateProfessor = new AssociateProfessor(name, id,
address, email, mobile, basicPay);
associateProfessor.generatePaySlip();
break;

case 4:
Professor professor = new Professor(name, id, address, email, mobile,
basicPay);
professor.generatePaySlip();
break;

default:
System.out.println("Invalid choice.");
}
scanner.close();
}
}

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

OUTPUT:

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

IMPLEMENTING STACK ADT

PROGRAM:
import java.util.Scanner;

// Step 1: Create an interface MyStack


interface MyStack {
void push(int element);
void pop();
void display();
}

// Step 2: Create a class Stack by implementing the interface MyStack


class Stack implements MyStack {
private int[] stackArray;
private int top;

// Step 3: Initialize the size of stack array and top


public Stack(int size) {
stackArray = new int[size];
top = -1; // Stack is initially empty
}

// Step 4: Define the Push() method


@Override
public void push(int element) {
try {
if (top == stackArray.length - 1) {
throw new Exception("Stack Overflow"); // Exception for overflow
}
stackArray[++top] = element; // Increment top and push element
System.out.println("Element pushed: " + element);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

// Step 5: Define the Pop() method


@Override
public void pop() {
try {

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

if (top == -1) {
throw new Exception("Stack Underflow"); // Exception for underflow
}
int poppedElement = stackArray[top--]; // Decrement top and return element
System.out.println("Element popped: " + poppedElement);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

// Step 6: Print the Stack elements by defining Display() method


@Override
public void display() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
System.out.print("Stack elements: ");
for (int i = top; i >= 0; i--) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
}
}

// Step 7: Create a class StackADT and define stack_array.


public class StackADT {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack stack = new Stack(5); // Create a stack of size 5
while (true) {
System.out.println("Enter the option: 1. Push 2. Pop 3. Display 4. Exit");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter element to push: ");
int element = scanner.nextInt();
stack.push(element);
break;
case 2:
stack.pop();
break;

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY


REG.NO.: 211423104269

case 3:
stack.display();
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return; // Exit the program
default:
System.out.println("Invalid option. Please try again.");
}
}
}
}

OUTPUT :

RESULT :

23IT1311 – OBJECT ORIENTED PROGRAMMING LABORATORY

You might also like