Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Program to Convert List to Stream in Java
Next article icon

Java Program to Convert Infix Expression to Postfix expression

Last Updated : 24 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article let us discuss how to convert an infix expression to a postfix expression using Java.

Pre-Requisites:

1. Infix expression: Infix expressions are expressions where an operator is in between two operators. It is the generic way to represent an expression or relationship between the operators and operands mathematically. Example: 3 * 5, a + b

2. Postfix expression: Postfix expressions are expressions where an operator is placed after all of its operands. Example: 3 5 *, a b +

3. Required Data structures:

Stack: Stack is a linear data structure that follows the Last-In-First-Out principle. we are going to use a Stack data structure for the conversion of infix expression to postfix expression. To know more about the Stack data structure refer to this article - Stack Data Structure.

Rules to Convert Infix Expression to Postfix Expression

There are certain rules used for converting infix expressions to postfix expressions as mentioned below:

  • Initialize an empty stack to push and pop the operators based on the following rules.
  • You are given an expression string to traverse from left to right and while traversing when you encounter an
    • operator: you can directly add it to the output (Initialize a data structure like a list or an array to print the output which stores and represents the required postfix expression).
    • operand: pop the operands from the stack and add them to the output until the top of the stack has lower precedence and associativity than the current operand.
    • open-parenthesis ( ' ( ' ): push it into the stack.
    • closed-parenthesis ( ' ) ' ): Pop the stack and add it to the output until open-parenthesis is encountered and discard both open and closed parenthesis from the output.
  • Once you traverse the entire string, pop the stack and add it to the output, until the stack is empty.

Operators

Precedence

Associativity

^

Highest

Right to Left

*, /

High

Left to Right

+, -

Low

Left to Right

To know more about Precedence and Associativity, refer to this article - Precedence - Associativity

Example Explaining the Conversion

Let's consider an example to demonstrate the conversion of infix expression to postfix expression using stack.

Infix expression: 3 * 5 + ( 7 - 3 )

Procedure:

Step

Character Element

Stack

Output (Postfix Expression)

The Operation Performed on the Stack

1.

3


3

-

2.

*

*

3

push '*'

3.

5

*

3 5

-

4.

+

* +

3 5 *

pop '*'

push '+'

5.

(

+ (

3 5 *

push '('

6.

7

+ (

3 5 * 7

-

7.

-

+ ( -

3 5 * 7

push '-'

8.

)


3 5 * 7 - +

pop '-'

pop '+'

The output of the Infix expression 3 * 5 + ( 7 - 3 ) is 3 5 * 7 - +

Implementation:

Input: 3 * 5 + ( 7 - 3 )

Output: 3 5 * 7 - +

Let's implement the above procedure using Java:

Java
// Java Program to Convert Infix // expression to Postfix expression import java.util.*;  // Driver Class public class InfixPostfixConversion {     // lets define a method for conversion of infix     // expression to postfix expression     public static String infixToPostfix(String infix)     {          // The output will be represented as postfix         StringBuilder postfix = new StringBuilder();          // Initialize the stack to         // store the operators         Stack<Character> stk = new Stack<>();          for (char c : infix.toCharArray()) {              // if the encountered character is an operand             // add it to the output i.e postfix             if (Character.isLetterOrDigit(c)) {                 postfix.append(c);                  // if the encountered character is '(' push                 // it to the stack(stk)             }             else if (c == '(') {                 stk.push(c);                  // if the encountered character is ')' pop                 // the stack(stk) until '(' is encountered             }             else if (c == ')') {                 while (!stk.isEmpty()                        && stk.peek() != '(') {                     postfix.append(stk.pop());                 }                 stk.pop(); // discard '(' by popping it from                            // the stack             }             else {                  // if the encountered character is not                 // parenthesis or operand, then check the                 // precendence of the operator and pop the                 // stack and add it to the output                 // until the top of the stack has lower                 // precedence than the current character                 while (!stk.isEmpty()                        && precedence(stk.peek())                               >= precedence(c)) {                     postfix.append(stk.pop());                 }                 stk.push(c); // push the current operator to                              // the stack             }         }          // After traversing the entire string, check whether         // the stack is empty or not, if the stack is not         // empty, pop the stack and add it to the output*/         while (!stk.isEmpty()) {             postfix.append(stk.pop());         }          return postfix.toString();     }      // define a method to check the precedence of the     // operator     public static int precedence(char operator)     {         switch (operator) {         case '+':         case '-':             return 1;         case '*':         case '/':             return 2;         default:             return 0;         }     }      // main function     public static void main(String[] args)     {         System.out.println("Enter a Infix expression:");         Scanner sc = new Scanner(System.in);         String infix = sc.next();          sc.close();         String postfix = infixToPostfix(infix);          System.out.println("Postfix Expression: \n"                            + postfix);     } } 

Output:

Enter a Infix expression: 3*5+(7-3)
Postfix Expression: 35*73-+

Complexity of the Above Method:

Time complexity: O(n) to traverse the entire string at least once.
Space complexity: O(n) for using stack space.


Next Article
Program to Convert List to Stream in Java

P

puzitha23
Improve
Article Tags :
  • Java
  • Java Programs
  • Geeks Premier League
  • Java-Conversion-Programs
  • Geeks Premier League 2023
Practice Tags :
  • Java

Similar Reads

  • Program to Convert List to Stream in Java
    The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack class
    3 min read
  • Java Program to convert integer to boolean
    Given a integer value, the task is to convert this integer value into a boolean value in Java. Examples: Input: int = 1 Output: true Input: int = 0 Output: false Approach: Get the boolean value to be converted. Check if boolean value is true or false If the integer value is greater than equal to 1,
    2 min read
  • Java Program to Convert InputStream to String
    Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
    4 min read
  • Program to convert List of String to List of Integer in Java
    The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and
    3 min read
  • Program to convert set of String to set of Integer in Java
    Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
    2 min read
  • Java Program to Convert Enum to String
    Given an enum containing a group of constants, the task is to convert the enum to a String. Methods: We can solve this problem using two methods: Using name() MethodUsing toString() Method Let us discuss both of them in detail and implementing them to get a better understanding of the same. Method 1
    2 min read
  • Java Program to Convert String to String Array Using Regular Expression
    Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided un
    3 min read
  • Java Program to Convert String to Object
    In-built Object class is the parent class of all the classes i.e each class is internally a child class of the Object class. So we can directly assign a string to an object. Basically, there are two methods to convert String to Object. Below is the conversion of string to object using both of the me
    2 min read
  • Java Program to Convert String to Integer Array
    In Java, we cannot directly perform numeric operations on a String representing numbers. To handle numeric values, we first need to convert the string into an integer array. In this article, we will discuss different methods for converting a numeric string to an integer array in Java. Example: Below
    3 min read
  • How to Convert Char to String in Java?
    In this article, we will learn how to Convert Char to String in Java. If we have a char value like 'G' and we want to convert it into an equivalent String like "G" then we can do this by using any of the following three listed methods in Java. Using toString() method of Character classUsing valueOf(
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences