Stack Class in Java and how to use - NareshIT

Stack Class in Java and how to use - NareshIT

Stack Class in Java and how to use:

The Data Structures is one of the prime requirements of the programmers as they make the programmers task quite simple. We have the stack class in Java which is a part of the collection framework. And this simplifies all the stack class operations such as the push and pop etc.? And in this article, we find out the details related to the stack class in Java. And we will be covering what is a stack class, what are the methods in the Java Stack class like empty(), pop(), peek(), search(), and push() operation. And we have various Java stack operations like the stack size, iteration through the stack, reversing a list through the use of Java Stack. And with that let's get started. And you can contact us for your Java training.?Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java?training.

Stack class in Java

The stack is based on LIFO or the last in first out. And the Java stack class comes under the Collection hierarchy framework, and we can perform through it the basic operations like the pop, push, etc. The Java collection framework covers the interfaces and the classes. Let’s now brief how the stack class is arranged in Java in the Java collection framework hierarchy. We have the interfaces like the iterable, collections, and list and we have the classes like the vector and stack.

The stack class extends the vector class that implements the List interface. You can create a Stack, and that initially does not have any of the items which means the stack comes with nothing inside it and is empty.

Let’s now have various methods in the Java stack class.

Various methods in the Stack class

The stack class in Java has five methods. Below are those methods, and you can use them directly. The functions are the empty(), push(), pop(), peek() and search(). The empty() method checks whether there is nothing in the stack, and the push() method pushes the item at the top. The pop method removes the object, and the peek () method looks at the object and does not remove it. The search () searches for the item and returns its index.

Let’s have a look at all of these methods through a program.


import java.io.*; 
import java.util.*; 
 
public class Main
    {    
    //push the element at the top of the stack 
       static void push_m(Stack s, int num) {
          s.push(new Integer(num));
          System.out.println(s);
       }
    // print the element at the stack top 
       static void peek_m(Stack s) 
          { 
              Integer el = (Integer) s.peek(); 
              System.out.println("At the top of the stack : " + el); 
          }
    // Search for the element in the stack
       static void search_m(Stack s, int el) 
        { 
            Integer p = (Integer) s.search(el); 
       
            if(p == -1) 
                System.out.println("not exist"); 
            else
                System.out.println(“found at the position" + p); 
        } 
    // Removal at top of the stack
       static void pop_m(Stack s) {
              System.out.print("pop:");
              Integer num = (Integer) s.pop();
              System.out.println(num);
              System.out.println("stack remaining: " + s);
           }
       public static void main(String args[]) {
          Stack s = new Stack();
          System.out.println("Empty stack: " + s);
          push_m(s, 12);
          push_m(s, 11);
          push_m(s, 19);
          peek_m(s);
          search_m(s, 12); 
          search_m(s, 4);
          pop_m(s);
          pop_m(s);
          pop_m(s);
         
       }
}        

Output:

Empty stack: []                                                                                                                
[12]                                                                                                                           
[12, 11]                                                                                                                       
[12, 11, 19]                                                                                                                   
At the top of the stack : 19                                                                                                   
Element found at the position3                                                                                                 
Element not exiat                                                                                                              
pop:19                                                                                                                         
stack remaining: [12, 11]                                                                                                      
pop:11                                                                                                                         
stack remaining: [12]                                                                                                          
pop:12                                                                                                                         
stack remaining: []         

In the above program, we have used all the methods. We have used the push method, pop method, peek method, search method, and empty method.

Let’s move forward and discuss various operations that you can make use of while you implement the stack class in Java.

Java Stack Operations:

import java.util.Stack;

import java.util.EmptyStackException;

public class Main{  

public static void main (String[] args) 

{ 

    Stack s = new Stack();

    s.push("23");

    s.push("22");

    s.push("13");

    // Check if the Stack is empty

            System.out.println("Stack empty? " + s.isEmpty());

 

    // Find the size of Stack

            System.out.println("Size: " + s.size());

    }

}

Stack empty? false                                                                                                                                       

Size: 3

Iterating the elements 

Using iterator()

Using forEach()

Using listIterator() from beginning to last

Lets iterate using the iterator() method.

import java.util.Iterator;

import java.util.Stack;

import java.util.EmptyStackException;

public class Main {

public static void main (String[] args) 

{ 

    Stack s = new Stack();

    s.push("23");

    s.push("21");

    s.push("13");

    Iterator i = s.iterator();

    while(i.hasNext()){

          Object v = i.next();

          System.out.println(v); 

            }   

}

}        

Output:

23

21

13

Iteration is possible through other methods as well. Lets see below:

import java.util.Iterator;

import java.util.EmptyStackException;

import java.util.Stack;

import java.util.ListIterator;

public class Main {

public static void main (String[] args) 

{ 

    Stack s = new Stack()

    s.push("23");

    s.push("24");

    s.push("213");

    System.out.println("Iteration through Foreach METHOD:");

    s.forEach(num ->{

        System.out.println(num);

    });

     

    ListIterator<String> Li = s.listIterator(s.size());

    System.out.println("using ListIterator");

    while (Li.hasPrevious()) {

        String st = Li.previous();

        System.out.println(st);

}

}}        

Iteration through Foreach METHOD:

23

24

213

using ListIterator

213

24

23

Above we have iterated using the forEach() method and then we have reversed it using listIterator.

This brings us to the end of this article on the stack class in Java. Hope you now have all the details about the stack class in Java. Stay tuned for more Java-related information through our blogs.

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java?training. You can also opt for Java?online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let us have a look at what you will get with this Java?training package:


  • You need to pay a nominal fee.
  • You can choose any Java certification, as per your skills and interest.
  • You have the option to select from online and classroom training.
  • A chance to study at one of the best?Java?training institutes in India
  • We provide Java?training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
  • Naresh I technologies cater to one of the best Java?training in India.
  • And a lot more is waiting for you.

Contact us anytime for your complete?Java?online training.

FAQ'S

1. What is a Stack in Java?

A Stack in Java is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It means the last element added to the stack is the first one to be removed. This behavior is similar to a stack of plates where the top plate is the last one placed and the first one to be taken.

2. What is the difference between a Stack and a Queue in Java?

While both Stacks and Queues are linear data structures, they follow different access patterns:

  • Stack: Last-In-First-Out (LIFO) - The last element added is the first one to be removed.
  • Queue: First-In-First-Out (FIFO) - The first element added is the first one to be removed.

3. What are the common operations performed on Stacks in Java?

Some common operations on Stacks include:

push(Object): Adds an element to the top of the stack.

pop(): Removes and returns the top element from the stack.

peek(): Returns the top element without removing it.

isEmpty(): Checks if the stack is empty.

size(): Returns the number of elements in the stack.

For More Details Visit : Java Online Training

Register For Free Demo on UpComing Batches : https://nareshit.com/new-batches


要查看或添加评论,请登录

社区洞察

其他会员也浏览了