Java Topics
HubJava Collections FrameworkCollections Practice ProgramsComparable vs ComparatorGenericsIteratorArrayListLinkedListStackVectorHashMapHashtableLinkedHashMapTreeMapArrayDequeDeque Double-Ended QueuePriorityQueueHashSetLinkedHashSetTreeSetAdapter PatternBuilder PatternFactory PatternMVC PatternObserver PatternSingleton PatternDynamic ProgrammingGraphHashingHeapLinked List DSAQueue DSARecursionSearching AlgorithmsSorting AlgorithmsStack DSATime ComplexityTreesException Handling Best PracticesCustom ExceptionException Hierarchyfinally BlockException Handlingthrow aur throwstry-catchBuffered StreamsByte StreamsCharacter StreamsDeserializationFile ClassJava NIO New I/OSerializationArrays in JavaArray OperationsArray Practice ProgramsArray Interview QuestionsJagged ArrayMulti-Dimensional ArraysOne Dimensional Arraybreak aur continuedo-while Loopfor Loopif-else StatementsNested Loopsswitch-case Statementwhile LoopJava Compilation ProcessJava ki FeaturesPehla Java ProgramHistory of JavaJava EditionsJava Program StructureJDK, JRE aur JVMJava Kya Hai?Immutable StringsString Class in JavaString Interview QuestionsString MethodsString Practice ProgramsStringBufferStringBuilderComments in JavaData Types in JavaIdentifiers in JavaInput & Output in JavaJava KeywordsOperators in JavaType Casting in JavaVariables in JavaJava Coding Interview QuestionsCollections Interview QuestionsCore Java Interview QuestionsJDBC Interview QuestionsMultithreading Interview QuestionsOOPs Interview QuestionsSpring Framework Interview QuestionsJava 8 Date/Time APIDefault aur Static Methods in InterfaceFunctional InterfaceLambda ExpressionMethod ReferenceOptional ClassStream APIBatch ProcessingCallableStatementJDBC ArchitectureJDBC — Java Database ConnectivityJDBC Practice ProjectsMySQL ConnectionPreparedStatementResultSetStatement InterfaceTransaction ManagementCreating ThreadsDaemon ThreadExecutor FrameworkInter-Thread CommunicationMultithreading Practice ProgramsRunnable InterfaceSynchronizationThread ClassMultithreading IntroductionThread Life CycleThread PriorityJava Cheat SheetImportant Formulas & Key ConceptsImportant Java ProgramsJava Quick RevisionAbstract ClassAbstractionAnonymous ClassClass and ObjectConstructorEncapsulationInheritanceInner ClassInterfaceMethod OverloadingMethod OverridingObject ClassObject CloningObject-Oriented Programming OOPPolymorphismstatic Keywordsuper Keywordthis KeywordWrapper ClassesArray Practice ProgramsBasic Java Practice ProgramsCollection Practice ProgramsJDBC Practice ProgramsMultithreading Practice ProgramsOOPs Practice ProgramsPlacement Coding QuestionsString Practice ProgramsBanking SystemChat ApplicationE-Commerce Backend — Spring Boot REST APIEmployee Management SystemLibrary Management SystemSpring Boot Fullstack ProjectStudent Management SystemCookies in ServletExpression Language ELGenericServletHttpServletJavaServer Pages JSPJSP TagsMVC ArchitectureHttpServletRequest & HttpServletResponseServlet IntroductionServlet Life CycleSession TrackingDependency InjectionSpring BeansSpring CoreSpring FrameworkAPI GatewaySpring Cloud Config ServerDocker DeploymentEureka Server — Service DiscoverySpring Boot CRUD ApplicationException Handling in Spring BootJWT AuthenticationREST API in Spring BootSpring SecuritySpring BootSpring Data JPAValidation in Spring Boot
Stack DSA
Last Updated : 26 May, 2026
title: Stack DSA
DSA in Java31 words5 headingsExamples included
title: Stack (DSA) description: Stack data structure implementation aur problems
LIFO — Last In, First Out.
Implementation using Array
class Stack {
private int[] arr;
private int top;
private int capacity;
Stack(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
top = -1;
}
void push(int data) {
if (top == capacity - 1) throw new RuntimeException("Stack overflow");
arr[++top] = data;
}
int pop() {
if (isEmpty()) throw new RuntimeException("Stack underflow");
return arr[top--];
}
int peek() {
if (isEmpty()) throw new RuntimeException("Stack empty");
return arr[top];
}
boolean isEmpty() { return top == -1; }
int size() { return top + 1; }
}
Classic Problems
Balanced Parentheses
boolean isBalanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') stack.push(c);
else if (c == ')' && (stack.isEmpty() || stack.pop() != '(')) return false;
else if (c == ']' && (stack.isEmpty() || stack.pop() != '[')) return false;
else if (c == '}' && (stack.isEmpty() || stack.pop() != '{')) return false;
}
return stack.isEmpty();
}
Next Greater Element
int[] nextGreater(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Arrays.fill(result, -1);
Deque<Integer> stack = new ArrayDeque<>(); // stores indices
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] < arr[i]) {
result[stack.pop()] = arr[i];
}
stack.push(i);
}
return result;
}
Evaluate Postfix Expression
int evalPostfix(String expr) {
Deque<Integer> stack = new ArrayDeque<>();
for (String token : expr.split(" ")) {
if (token.matches("-?\\d+")) {
stack.push(Integer.parseInt(token));
} else {
int b = stack.pop(), a = stack.pop();
switch (token) {
case "+" -> stack.push(a + b);
case "-" -> stack.push(a - b);
case "*" -> stack.push(a * b);
case "/" -> stack.push(a / b);
}
}
}
return stack.pop();
}
// evalPostfix("3 4 + 2 *") = 14
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Stack DSA.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java topic.
Search Terms
java, java programming, core java, java master course, java notes, master, course, dsa
Related Java Topics