Implement Stack using Array in java

In this post, we will see how to implement Stack using Array in java.Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Array.
Although java provides implementation for all abstract data types such as Stack,Queue and LinkedList but it is always good idea to understand basic data structures and implement them yourself.
Please note that Array implementation of Stack is not dynamic in nature. You can implement Stack through linked list for dynamic behavior.

Java Program to implement Stack using Array:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

packageorg.arpit.java2blog;

/**

* @author Arpit Mandliya

*/

publicclassStackCustom{

intsize;

intarr[];

inttop;

StackCustom(intsize){

this.size=size;

this.arr=newint[size];

this.top=-1;

}

publicvoidpush(intpushedElement){

if(!isFull()){

top++;

arr[top]=pushedElement;

System.out.println("Pushed element:"+pushedElement);

}else{

System.out.println("Stack is full !");

}

}

publicintpop(){

if(!isEmpty()){

intreturnedTop=top;

top--;

System.out.println("Popped element :"+arr[returnedTop]);

returnarr[returnedTop];

}else{

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

return-1;

}

}

publicintpeek(){

returnarr[top];

}

publicbooleanisEmpty(){

return(top==-1);

}

publicbooleanisFull(){

return(size-1==top);

}

publicstaticvoidmain(String[]args){

StackCustom StackCustom=newStackCustom(10);

StackCustom.pop();

System.out.println("=================");

StackCustom.push(10);

StackCustom.push(30);

StackCustom.push(50);

StackCustom.push(40);

System.out.println("=================");

StackCustom.pop();

StackCustom.pop();

StackCustom.pop();

System.out.println("=================");

}

}

When you run above program, you will get below output:

1

2

3

4

5

6

7

8

9

10

11

12

13

Stack isempty!

=================

Pushed element:10

Pushed element:30

Pushed element:50

Pushed element:40

=================

Popped element:40

Popped element:50

Popped element:30

=================

As you can see we have pushed 40 in last, so it is popped first as Stack is of Last In First Out(LIFO) nature.