Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Stack Class in Collection Framework, Essays (university) of Java Programming

The java stack class in the collection framework, its implementation of the last-in-first-out (lifo) data structure, and its methods such as push(), pop(), peek(), empty(), and search(). An example is provided to illustrate the usage of the stack class.

Typology: Essays (university)

2018/2019

Uploaded on 12/02/2019

9141219194
9141219194 🇮🇳

4

(1)

2 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
THE COLLECTIONS
FRAMEWORK
Sagar B V
4AL18CS400
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Java Stack Class in Collection Framework and more Essays (university) Java Programming in PDF only on Docsity!

THE COLLECTIONS

FRAMEWORK

Sagar B V 4AL18CS

STACK

  • Java Collection framework provides a Stack class which models and implements Stack data structure.
  • The class is based on the basic principle of last-in-first-out.
  • Stack only defines the default constructor, which creates an empty stack.
  • Syntax: class Stack Here, E specifies the type of element stored in the stack.
    • To put an object on the top of the stack, call push().
    • To remove and return the top element, call pop().
    • An EmptyStackException is thrown if you call pop() when the invoking stack is empty.

Here is an example that creates a stack, pushes several integer objects onto it, and then pops them off again: // Demonstrate the stack class. import java.util.*; class StackDemo { static void showpush(stack st, int a) { st.push(a); System.out.println(“push(“ + a + “)”); System.out.println(“stack: “ +st); }

Static void showpop(stack st) { System.out.print(“pop->“); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println(“stack: “ +st); } static void showpeek(Stack st) { Integer element = (Integer) st.peek(); System.out.println("Element on stack top : " + element); }

public static void main(String args[]) { stack st = new Stack(); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpeek (st); showsearch (st,66); showsearch (st,15); } try{ Integer obj = (Integer)st.pop(); } catch (EmptyStackException e) { System.out.println(“Empty stack"); } }

The following produce the output produced by the program: push(42) stack: [42] push(66) stack: [42,66] push(99) stack: [42,66,99] pop -> 99 stack: [42,66] Element on stack top : Element is found at position 2 Element not found