Home » Java programming language

Java Stack peek() Method with Example

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

Stack Class peek() method

  • peek() method is available in java.util package.
  • peek() method is used to return the top element from this Stack and it retrieves elements without removing.
  • peek() 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.
  • peek() method does not throw an exception at the time of returning top element.

Syntax:

    public Object peek();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is Object, it returns head element from the stack.

Example:

// Java program to demonstrate the example 
// of Object peek() method of Stack Class

import java.util.*;

public class PeekOfStack {
 public static void main(String args[]) {
  // Instantiates Stack object
  Stack s = new Stack();

  // By using push() method isto
  // push the given onto the stack
  s.push(10);
  s.push(20);
  s.push(30);
  s.push(40);
  s.push(50);

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

  // By using peek() method is
  // to return the top element
  // without removing
  Object ele = s.peek();

  // Display Peek Element
  System.out.println("s.peek(): " + ele);
 }
}

Output

s:[10, 20, 30, 40, 50]
s.peek(): 50





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.