Java StackThe stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection of objects. One of them is the Stack class that provides different operations such as push, pop, search, etc. In this section, we will discuss the Java Stack class, its methods, and implement the stack data structure in a Java program. But before moving to the Java Stack class have a quick view of how the stack works. The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and pop operation removes an element from the top of the stack. Let's see how they work on stack. ![]() Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack. ![]() Let's remove (pop) 18, 45, and 11 from the stack. ![]() Empty Stack: If the stack has no element is known as an empty stack. When the stack is empty the value of the top variable is -1. ![]() When we push an element into the stack the top is increased by 1. In the following figure,
![]() When we pop an element from the stack the value of top is decreased by 1. In the following figure, we have popped 9. ![]() The following table shows the different values of the top. ![]() Java Stack ClassIn Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must import the java.util package. The stack class arranged in the Collections framework hierarchy, as shown below. ![]() Stack Class ConstructorThe Stack class contains only the default constructor that creates an empty stack. Creating a StackIf we want to create a stack, first, import the java.util package and create an object of the Stack class. Or Where type denotes the type of stack like Integer, String, etc. Methods of the Stack ClassWe can perform push, pop, peek and search operation on the stack. The Java Stack class provides mainly five methods to perform these operations. Along with this, it also provides all the methods of the Java Vector class.
Stack Class empty() MethodThe empty() method of the Stack class check the stack is empty or not. If the stack is empty, it returns true, else returns false. We can also use the isEmpty() method of the Vector class. Syntax Returns: The method returns true if the stack is empty, else returns false. In the following example, we have created an instance of the Stack class. After that, we have invoked the empty() method two times. The first time it returns true because we have not pushed any element into the stack. After that, we have pushed elements into the stack. Again we have invoked the empty() method that returns false because the stack is not empty. StackEmptyMethodExample.java Output: Is the stack empty? true Elements in Stack: [78, 113, 90, 120] Is the stack empty? false Stack Class push() MethodThe method inserts an item onto the top of the stack. It works the same as the method addElement(item) method of the Vector class. It passes a parameter item to be pushed into the stack. Syntax Parameter: An item to be pushed onto the top of the stack. Returns: The method returns the argument that we have passed as a parameter. Stack Class pop() MethodThe method removes an object at the top of the stack and returns the same object. It throws EmptyStackException if the stack is empty. Syntax Returns: It returns an object that is at the top of the stack. Let's implement the stack in a Java program and perform push and pop operations. StackPushPopExample.java Output: stack: [] push -> 20 stack: [20] push -> 13 stack: [20, 13] push -> 89 stack: [20, 13, 89] push -> 90 stack: [20, 13, 89, 90] push -> 11 stack: [20, 13, 89, 90, 11] push -> 45 stack: [20, 13, 89, 90, 11, 45] push -> 18 stack: [20, 13, 89, 90, 11, 45, 18] pop -> 18 stack: [20, 13, 89, 90, 11, 45] pop -> 45 stack: [20, 13, 89, 90, 11] pop -> 11 stack: [20, 13, 89, 90] Stack Class peek() MethodIt looks at the element that is at the top in the stack. It also throws EmptyStackException if the stack is empty. Syntax Returns: It returns the top elements of the stack. Let's see an example of the peek() method. StackPeekMethodExample.java Output: Stack: [Apple, Grapes, Mango, Orange] Element at the top of the stack: Orange Stack Class search() MethodThe method searches the object in the stack from the top. It parses a parameter that we want to search for. It returns the 1-based location of the object in the stack. Thes topmost object of the stack is considered at distance 1. Suppose, o is an object in the stack that we want to search for. The method returns the distance from the top of the stack of the occurrence nearest the top of the stack. It uses equals() method to search an object in the stack. Syntax Parameter: o is the desired object to be searched. Returns: It returns the object location from the top of the stack. If it returns -1, it means that the object is not on the stack. Let's see an example of the search() method. StackSearchMethodExample.java Java Stack OperationsSize of the StackWe can also find the size of the stack using the size() method of the Vector class. It returns the total number of elements (size of the stack) in the stack. Syntax Let's see an example of the size() method of the Vector class. StackSizeExample.java Output: Is the stack empty or not? false The stack size is: 5 Iterate ElementsIterate means to fetch the elements of the stack. We can fetch elements of the stack using three different methods are as follows:
Using the iterator() MethodIt is the method of the Iterator interface. It returns an iterator over the elements in the stack. Before using the iterator() method import the java.util.Iterator package. Syntax Let's perform an iteration over the stack. StackIterationExample1.java Output: BMW Audi Ferrari Bugatti Jaguar Using the forEach() MethodJava provides a forEach() method to iterate over the elements. The method is defined in the Iterable and Stream interface. Syntax Let's iterate over the stack using the forEach() method. StackIterationExample2.java Output: Iteration over the stack using forEach() Method: 119 203 988 Using listIterator() MethodThis method returns a list iterator over the elements in the mentioned list (in sequence), starting at the specified position in the list. It iterates the stack from top to bottom. Syntax Parameter: The method parses a parameter named index. Returns: This method returns a list iterator over the elements, in sequence. Exception: It throws IndexOutOfBoundsException if the index is out of range. Let's iterate over the stack using the listIterator() method. StackIterationExample3.java Output: Iteration over the Stack from top to bottom: 988 203 119 Next TopicJava Tutorial
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com