Stack using arrays / Push(), Pop(), and Display() methods in JAVA Programming Language
PROGRAM STATEMENT
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate their working.
CONCEPT
A simple class example:
class Student{ String USN,name , branch; int phoneno; }
Object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behaviour. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables. Creating variables of your class type is similar to creating variables of primitive data types, such as integers or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. Suppose you want to create an object of the class and have the reference variable associated with this object. In that case, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
Constructor
EXAMPLE STACK OPERATIONS PROGRAM
/*stack.java*/ import java.io.*; import java.util.Scanner; public class stack { int element,maxsize,top; int[] st; public stack() { Scanner integer=new Scanner(System.in); System.out.println("Enter stack size"); maxsize=integer.nextInt(); st=new int[maxsize]; top=-1; } public void push(int element) { /*if(top>=maxsize) { System.out.println("Overflow!!"); //return(0); }*/ try { st[++top]=element; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } } public int pop() { if(top==-1) { System.out.println("UnderFlow"); return(-1); } return(st[top--]); } public void display(int[] st, int max_size) { int i; System.out.println("Stack Elements:"); for(i=0;i<=max_size;i++) System.out.println(st[i]); } }
/*myStack.java*/ import java.io.*; import java.util.Scanner; public class myStack { static int option; public static void main(String[] args) { stack obj=new stack(); while(true) { System.out.println("\nEnter yours choice\n1.PUSH\n2.POP\n3.Display\n4..EXIT"); Scanner integer=new Scanner(System.in); option=integer.nextInt(); switch(option) { case 1: System.out.println("Enter Element"); obj.element=integer.nextInt(); obj.push(obj.element); break; case 2:System.out.printf("Poped element is %d",obj.pop()); break; case 3:obj.display(obj.st,obj.top); break; case 4:System.exit(0); default:System.out.println("Wrong option"); } } } }