stack – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Wed, 05 Jul 2023 16:18:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg stack – Programmerbay https://programmerbay.com 32 32 Stack Class in Java with Program Example https://programmerbay.com/stack-class-in-java-with-program-example/ https://programmerbay.com/stack-class-in-java-with-program-example/#respond Wed, 05 Jul 2023 16:18:55 +0000 https://programmerbay.com/?p=9354 Stack extends Vector class that implements Last in first out (LIFO) data structure, introduced in JDK 1.0. The data structure specifies the last element to be added to the stack, is the first one to be removed. It is a subclass of the Vector class that enables it to inherit all the attributes and methods of its parent class. It is considered as a legacy class as it exist even before the collection framework and it is re-engineered to support the collection.

Screenshot from 2023 07 04 19 23 17

Further, it provides only a default constructor to create an empty stack object.

One of the main use case of the Stack class is to reverse a sequence of elements. This can be done by pushing elements onto the stack and then popping them off one by one from the top.

The collection class provides various methods for manipulating elements present in the stack, such as push(), pop(), peek(), and empty().

Methods Of Stack Class

push(): The push method is used to add an element to the top of the stack

pop(): The pop method is used to remove and return the element at the top.

peek(): The peek method returns the element at the top without removing it.

empty(): It returns true if the stack is empty, otherwise, false.

search(): It searches an element, and returns offset, otherwise, -1 to signify not found.

Other Inherited Methods

MethodsExplanation
addElement(T obj)Inserts an element to the end of the list.
removeElement( T obj)Removes the very first occurrence of the given element
trimToSize()Reduces the capacity of the given vector to the current size
ensureCapacity(int minCapacity)Increases the capacity to ensure that the list can hold at least the specified number of elements
setSize()Set the size of the given vector, storing null values to new empty spaces
capacity()Returns the current capacity of the vector
insertElementAt(T obj, int indx)Inserts the given element at the specified position, moving elements greater than that index by 1
removeElementAt(int indx)Deletes the element at the specified index
setElementAt(T obj, int indx)Replaces the element at the specified position with the specified element
elementAt(int indx)Returns the element at the given position
firstElement()Returns the first element in the list
lastElement()Returns the last element in the list
copyInto(Object[] o)Copies elements to the given arrays passed as parameter
indexOf(T o)Returns the index of the first occurrence of the specified element
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Here’s a program example to reverse a sequence of integers using Stack:

Program: 

import java.util.Stack;

public class Main
{
  public static void main (String[]args)
  {
    Stack < Integer > stack = new Stack <> ();
    stack.push (1);
    stack.push (2);
    stack.push (3);
    stack.push (4);
    while (!stack.empty ())
      {
  System.out.println ("Element :: "+ stack.pop ());
      }
  }
}

Output:

Element :: 4
Element :: 3
Element :: 2
Element :: 1

Over Stack class, the Deque interface should be used as it provides a more complete and flexible API. The Deque interface extends the Queue interface and supports both LIFO and First-In-First-Out (FIFO) operations. The ArrayDeque class implements the Deque interface which is a resizable array and is a good choice for most use cases.

Here’s a program code to reverse a sequence of integers  using the ArrayDeque class:
Program:
import java.util.ArrayDeque;
public class Main
{
  public static void main (String[]args)
  {
    ArrayDeque < Integer > deque = new ArrayDeque <> ();
    deque.push (1);
    deque.push (2);
    deque.push (3);
    deque.push (4);
    while (!deque.isEmpty ())
      {
  System.out.println ("Element :: "+deque.pop ());
      }
  }
}
Output:
Element :: 4
Element :: 3
Element :: 2
Element :: 1

 

]]>
https://programmerbay.com/stack-class-in-java-with-program-example/feed/ 0
Java Program to Implement Stack https://programmerbay.com/java-program-to-implement-stack/ https://programmerbay.com/java-program-to-implement-stack/#respond Tue, 14 Jun 2022 16:59:58 +0000 https://programmerbay.com/?p=5100 The program shows stack implementation. In this article, we’ll be writing a custom stack implementation with the following operations pop, peek, and push. Apart from that, we’ll be using predefined class to achieve the stack functionality.

A stack is a data structure that works in LIFO ( Last in First out) manner. Data can be inserted with push operation and deleted using pop operation, only from one end called Top.

Java program to implement Stack using Custom Implementation

Program:

import java.util.Scanner;
class StackExample {
    int number[];
    int top;
    int limit;

    // constructor
    public StackExample(int size){
        top =-1;
        limit =size;
        number=new int[size];
    }
    // insert an element
    void push(int num)
    {
        if(isFull())
            System.out.println("Stack is full");
        else
        {
            top=top+1;
            number[top]=num;
        }

    }
    // popping out the element that is at the top of stack
    void pop(){
        if(isEmpty())
            System.out.println("Stack is Empty");
        else{
            top=top-1;
            System.out.println("Element popped out");
        }
    }
    void peek()
    {
        System.out.println("Top most element in Stack ="+number[top]);

    }
    // check stack, is it full or not?
    boolean isFull(){
        return top >=limit-1;
    }
    boolean isEmpty(){
        return top==-1;
    }

    void print(){
        System.out.println("Elements in Stack:-");
        for(int i=top;i>=0;i--)
            System.out.println(number[i]);
    }


    public static void main(String[] args) {
        Scanner input =new Scanner(System.in) ;
        int size,option,element;
        char chr;
        System.out.print("Enter the maximum size that a stack can have = ");
        size=input.nextInt();
        StackExample obj= new StackExample(size);
        do{
            System.out.println("Please press any number from the following operations:-"
                    + "\n 1. Insert an element "
                    + "\n 2. Pop an element"
                    + "\n 3. Peek of the stack"
                    + "\n 4. Display the elements of the stack");
            option=input.nextInt();

            switch(option){
                case 1:
                    System.out.print("Please enter the element to insert = ");
                    element=input.nextInt();
                    obj.push(element);
                    break;
                case 2:
                    obj.pop();
                    break;
                case 3:
                    obj.peek();
                    break;
                case 4:
                    obj.print();
                    break;
                default:
                    System.out.println("Choose wrong option ");

            }
            System.out.println("Want to continue? y or n ");
            chr=input.next().charAt(0);
        }while(chr=='y'||chr=='Y');
    }
}

Output:

Java program to implement Stack using Stack Class

Java supports a predefined class named Stack. It offers methods like push(), pop() and peek() that helps in achieving stack implementation

Program: 

import java.util.Stack;

class StackExample {
    public static void main(String[] args) {
        Stack<Integer> integerStack = new Stack<>();
        // Pushing 5 element into the stack
        integerStack.push(34);
        integerStack.push(2);
        integerStack.push(5);
        integerStack.push(100);
        integerStack.push(2);

        // printing the stack's elements
        System.out.println("Elements in the Stack :: " + integerStack);

        // Pop operation on the stack, 2 would be removed from the top
        integerStack.pop();

        // printing the stack's elements
        System.out.println("Elements in the Stack :: " + integerStack);

        // Peek operation on the stack,100 would be printed
        System.out.println("Top of the stack :: " + integerStack.peek());
    }
}

Output:

Elements in the Stack :: [34, 2, 5, 100, 2]
Elements in the Stack :: [34, 2, 5, 100]
Top of the stack :: 100

]]>
https://programmerbay.com/java-program-to-implement-stack/feed/ 0
How are Java Objects Stored in Memory? https://programmerbay.com/how-does-an-object-in-java-is-created-and-stored/ https://programmerbay.com/how-does-an-object-in-java-is-created-and-stored/#respond Mon, 22 Jun 2020 16:06:29 +0000 https://www.programmerbay.com/?p=3090 Class is a user-defined data type which is naturally used to declare objects of that type. So, an object is a real-world entity, having a set of attributes and behavior. However, an object can’t be simply declared as same as primitive types.

How are Java Objects Stored in Memory?

In Java, creation of an object is a two-step procedure where we first declare an object of that class type and then a physical copy of the actual object of the class is assigned to that variable.

java memory object

This assignment of an actual copy of the object is done by using ‘new keyword’ for dynamic allocation of memory. A ‘new keyword’ allocates memory in heap and a reference to the allocated object which is nothing but an address is stored in the variable of the respective reference type.

Syntax:

Myclass obj;   //  Not an object, just a reference variable 

Obj = new Myclass(); // instantiation and initialization object
  •  A reference variable is created and used to store the address of an object.
  • A ‘new keyword’ paired with a constructor is used to assign the reference variable, this is how instantiation and initialization of an object take place. Instantiation of an object is done by new, whereas Initialization is by the constructor of that class. A constructor initializes the newly created objects.

Each time when an object is declared, it is said to be an instance of a class is created.

How java Objects are stored in memory

An object gets memory on the heap. In stack memory, the variable of class type stores the address of an object.

In heap memory, a physical copy of an object is stored and the reference or address of this copy in the variable of the associated class. Objects that can no longer be referenced are cleaned up by Garbage collector.

Java program to demonstrate the working of object

class myclass{
void display(){

System.out.println("I am printing");
}

}
public class Sample1 {

public static void main(String[] args) {
myclass obj;
obj= new myclass();
obj.display();
}

}

 

Output:

I am printing

]]>
https://programmerbay.com/how-does-an-object-in-java-is-created-and-stored/feed/ 0