KEMBAR78
Practical No 3 Java | PDF
0% found this document useful (0 votes)
17 views3 pages

Practical No 3 Java

Java

Uploaded by

u34846375
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)
17 views3 pages

Practical No 3 Java

Java

Uploaded by

u34846375
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/ 3

Practical no.

3
public class Stack (

private int[] elements;

private int top;

private int capacity;

public Stack() {

this(5);

public Stack(int size) (

capacity size; elements new int[capacity]; }

top-1;

public void push(int number) {

if (isFull()) {

System.out.println("Stack is full. Cannot push number);

} else {

elements[++top] = number;

System.out.println("Pushed + number);

public int pop() {

if (isEmpty()) {

System.out.println("Stack is empty. Cannot pop.");

return -1;

) else {

int poppedElement elements[top--];

System.out.println("Popped" poppedElement);

return poppedElement;

public boolean isEmpty() { return top -1: }


public boolean isFull() (

return top capacity 1;

public void display() (

if (isEmpty()) {

System.out.println("Stack is empty.");

} else {

System.out.print("Stack elements: ");

for (int 10; 1 < top; i++) {

System.out.print(elements[i]+"");

System.out.println();

public static void main(String[] args) {

Stack defaultStack = new Stack();

System.out.println("Default Stack:");

defaultStack.push(18);

defaultStack.push(20);

defaultStack.push(30);

defaultStack.push(40);

defaultStack.push(50);

defaultStack.push(60);

defaultStack.display();

defaultStack.pop();

defaultStack.display();

Stack customStack = new Stack(3);

System.out.println("\nCustom Stack:");

customStack.push(100);

customStack.push(200);
customStack.push(300);

customStack.push(480);

customStack.display();

customStack.pop();

customStack.display();

Output:

Default Stack:

Pushed 10

Pushed 20

Pushed 30

Pushed 40

Pushed 50

Stack is full. Cannot push 60

Stack elements: 10 20 30 40 50

Popped 50

Stack elements: 10 20 30

40

Custom Stack:

Pushed 100

Pushed 200

Pushed 30e

Stack is full. Cannot push 400

Stack elements: 100

200

300

Popped 300

Stack elements: 100 200

You might also like