Home » Java programming language

Java Stack push() Method with Example

Stack Class push() method: Here, we are going to learn about the push() method of Stack Class with its syntax and example.
Submitted by Preeti Jain, on March 24, 2020

Stack Class push() method

  • push() method is available in java.util package.
  • push() method is used to push the given element (ele) onto the Stack.
  • push() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • push() method does not throw an exception at the time of pushing an element.

Syntax:

    public void push(Object ele);

Parameter(s):

  • Object ele – represents the object to be pushed onto the top of this Stack.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void push(Object ele) method 
// of Stack

import java.util.*;

public class PushOfStack {
 public static void main(String args[]) {

  // Instantiates Stack object
  Stack s = new Stack();

  // By using push() method isto
  // push the given object at the 
  // top of the stack
  s.push(10);
  s.push(20);
  s.push(30);
  s.push(40);
  s.push(50);

  // Display Stack
  System.out.println("s:" + s);

 }
}

Output

s:[10, 20, 30, 40, 50]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.