CALCULATOR
USING
JAVA
BY
syed Hasan Mohammed Yahiya (100524733080)
Bani Saha (100524733069)
TABLE OF
CONTENT
Introduction Analysis of space complexity
Data Structures used Analysis of time complexity
Expression notations code overview & code
postfix evaluation conclusion
INTRODUCTION
In today's era of digital innovation, the ability to perform accurate and efficient calculations is essential across
many domains of science, engineering, and daily life. Our project—developing a calculator application in Java
—aims to provide users with a simple, effective, and user-friendly platform to evaluate arithmetic expressions
directly within the console environment. This calculator supports basic arithmetic operations and demonstrates
key programming concepts like stack manipulation, operator precedence handling, and real-time user
interaction.
The project showcases practical application of Java utility classes and data structures to convert infix
expressions into postfix notation and compute results, ensuring efficient handling of complex calculations
and operator priorities. By structuring the code modularly and leveraging robust Java packages, our
calculator is both reliable and extensible for future enhancements.
DATA STRUCTURES USED
STACKS VISION
QUEUES
A stack in Java is a linear data structure A queue in Java is a linear data structure
that follows the Last In First Out (LIFO) that follows the First-In First-Out (FIFO)
01
principle, meaning that the last element
01
principle, meaning the first element added
added is the first one to be removed. Other is the first one to be removed. Other
functions include pushing or popping operations performed by queues are
peek(), offer(), isempty() and poll(), which
elements in the program.
are used to bring an element front, add an
element, check if empty and delete an
element respectively
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Suspendisse quis enim Lorem ipsum dolor sit amet, consectetur
02 pretium, bibendum ante ullamcorper,
tincidunt augue. Nunc sed lorem aliquam,
malesuada lectus eu, placerat lorem. Proin
02 adipiscing elit. Suspendisse quis enim
pretium, bibendum ante ullamcorper,
tincidunt augue. Nunc sed lorem aliquam,
at aliquet sapien, vitae elementum mi. malesuada lectus eu, placerat lorem. Proin
at aliquet sapien, vitae elementum mi.
It is a Standard mathematical notation with
INFIX operators between operands. It requires
parenthesis for precedence. They are human
readable arithmetic expressions used in
programming to solve complex arithmetic
problems.
It is a notation where the operator follows the
operand. for eg ‘34++’ is written instead of ‘3+4’.
POSTFIX this eliminates the need of parenthesis in the
arithmetic notations and is also used in cases of
decrement and increment etc.
Prefix notation in Java is an arithmetic
expression format where the operator is
PREFIX written before its operands. This notation does
not require parentheses to denote operation
precedence because the order of operations is
EXPRESSION inherently unambiguous.
NOTATIONS BENEFITS
THE MAIN BENEFITS ARE:
1-It simplifies the evaluation.
2-removes ambiguity.
3-enables stack-based processing with linear
complexity.
INFIX TO POSTFIX CONVERSION
[Link] EXPRESSION:
Process each character from left to right, identifying
operands,operators and paranthesis.
[Link] MANAGEMENT:
Push operands directly to output, handle operators based on
precedence and associativity rules.
[Link] HANDLING:
Push opening parantheses to stack, pop until matching parenthesis when closing
encountered.
[Link] PROCESSING:
Pop remaining operators from stack to complete the postfix expression
construction.
01
The method postfixExp:
Uses a Stack<Character> to store operators temporarily. In the worst
ANALYSIS OF
case, this stack can hold all operators in the input expression, so its space
complexity is O(n)O(n), where nn is the length of the input string.
Uses a StringBuilder for the output postfix expression. This also grows
SPACE
linearly with the input size, hence O(n).
Uses a HashMap of fixed size (operator precedence map) which is O(1)
as it stores only a few operators.
Uses StringBuilder numberBuffer to accumulate digits which at max will be
COMPLEXITY proportional to the length of one number; considered O(n)O(n) in worst
case (one long number).
OF 02
The method postfixCal:
Uses a Stack<Integer> to evaluate the postfix
[1] expression. The space complexity for this stack
is also O(n)O(n) because, in the worst case, all
operands could be pushed before any operation
is applied.
ANALYSIS OF TIME COMPLEXITY
1. postfixExp (Infix to Postfix Conversion)
The time complexity of the postfixExp method is O(N).
Input Size (N): N is the length of the input expression string str.
The Main Loop: The method iterates through the input string exactly once using a for loop: for(int i=0;i<[Link]();i++)3. This is an {O(N)}
operation.
Stack Operations: Inside the loop, all stack operations (push, pop, peek) 4and map lookups ([Link](c)) take {O(1)}$ time on average.
Final Stack Clearing: The final while loop to empty the stack also involves processing each remaining operator once, which is {O(N)} in total.
2. postfixCal (Postfix Evaluation)
The time complexity of the postfixCal method is also $O(N)$.
Input Size ($N$): $N$ is related to the number of tokens (operands and operators) in the input postfix string str.
Tokenization: The line String[] tokens = [Link]().split("\\s+"); 8 splits the string into tokens. This operation takes time proportional to the length of the
string, which is {O(N)}.
Evaluation Loop: The method iterates through the array of tokens exactly once: for (String tok : tokens)9. Let $M$ be the number of tokens; this loop
is {O(M)}. Since M is bounded by N, this is {O(N)}
Stack Operations: Inside the loop, stack operations (push, pop) 10and arithmetic calculations 11 are all constant-time operations, {O(1)}. Each
operand is pushed once, and each operator causes two pops and one push.
import [Link].*;
SAMPLE CODE
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter An Expression: ");
String infix = [Link]();
String postFix = postfixExp(infix);
[Link]("Postfix: " + postFix);
[Link]("Result: " + postfixCal(postFix));
}
public static String postfixExp(String str) {
Map<Character, Integer> precedence = new HashMap<>();
[Link]('^', 3);
[Link]('*', 2);
[Link]('/', 2);
[Link]('+', 1);
[Link]('-', 1);
Stack<Character> stack = new Stack<>();
StringBuilder numberBuffer = new StringBuilder();
StringBuilder output = new StringBuilder();
for(int i=0;i<[Link]();i++){
SAMPLE CODE
char c = [Link](i);
if([Link](c)){
[Link](c);
}
else{
if(![Link]()){
[Link](numberBuffer).append(' ');
[Link](0);
}
if(c=='('){
[Link](c);
}
else if(c==')'){
while(![Link]() && [Link]()!='('){
[Link]([Link]()).append(' ');
}
[Link]();
}
else { //for operators + * / - ^
while(![Link]() && [Link]()!='(' && [Link]([Link]())>=[Link](c)){
[Link]([Link]()).append(' ');
}
[Link](c);}}}
if(![Link]()){
SAMPLE CODE
[Link](numberBuffer).append(' ');
}
while(![Link]()){
[Link]([Link]()).append(' ');
}
return [Link]().trim();
public static int postfixCal(String str) {
Stack<Integer> stack = new Stack<>();
String[] tokens = [Link]().split("\\s+");
for (String tok : tokens) {
if ([Link]("-?\\d+")) {
[Link]([Link](tok)); } else {
int b = [Link]();
int a = [Link]();
switch ([Link](0)) {
case '+' -> [Link](a + b);
case '-' -> [Link](a - b);
case '*' -> [Link](a * b);
case '/' -> [Link](a / b);
case '^' -> [Link]((int) [Link](a, b));
default -> throw new IllegalArgumentException("Unknown operator: " + tok);
}
}
}
return [Link]();
SAMPLE OUTPUT
USER INPUT:
ENTER AN EXPRESSION:
5 * (4 + 2) ^ 2 - 10
FINAL OUTPUT:
POSTFIX: 5 4 2 + 2 ^ * 10 -
RESULT: 170
SAMPLE OUTPUT
PROGRAM EXECUTION:
1 . INFIX TO POSTFIX CONVERSION (POSTFIXEXP METHOD): THE EXPRESSION 5 * (4 + 2) ^ 2 - 10 IS
CONVERTED TO ITS POSTFIX EQUIVALENT USING STANDARD OPERATOR PRECEDENCE RULES AND
STACK-BASED LOGIC.
2. AND - HAVE A PRECEDENCE OF 1.
3. AND / HAVE A PRECEDENCE OF 2.
4. HAS THE HIGHEST PRECEDENCE OF 3.
THE RESULTING POSTFIX EXPRESSION IS: 5 4 2 + 2 ^ * 10 -
POSTFIX EVALUATION (POSTFIXCAL METHOD):
THE PROGRAM EVALUATES THE POSTFIX EXPRESSION 5 4 2 + 2 ^ * 10 - USING A STACK.
FINAL OUTPUT:
POSTFIX: 5 4 2 + 2 ^ * 10 -
RESULT: 170
THE CALCULATION FOR THE ORIGINAL EXPRESSION IS:
5 (4 + 2)^2 - 10
5(6)^2 - 10
5 * 36 - 10
180 - 10
170
THANK YOU
DONE BY,
SYED HASAN MOHAMMED YAHIYA (80)
BANI SAHA (69)