Stack add(Object) method in Java with Example
The add(Object) method of Stack Class appends the specified element to the end of this Stack.
Syntax:
boolean add(Object element)
Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack.
Return Value: This method returns True after successful execution, else False.
Below program illustrates the working of java.util.Stack.add(Object element) method:
Example 1:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack
= new Stack<String>();
stack.add( "Geeks" );
stack.add( "for" );
stack.add( "Geeks" );
stack.add( "10" );
stack.add( "20" );
System.out.println( "The Stack is: "
+ stack);
stack.add( "Last" );
stack.add( "Element" );
System.out.println( "The new Stack is: "
+ stack);
}
}
|
Output:
The Stack is: [Geeks, for, Geeks, 10, 20]
The new Stack is: [Geeks, for, Geeks, 10, 20, Last, Element]
Example 2:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> stack
= new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
stack.add( 50 );
System.out.println( "The Stack is: "
+ stack);
stack.add( 100 );
stack.add( 200 );
System.out.println( "The new Stack is: "
+ stack);
}
}
|
Output:
The Stack is: [10, 20, 30, 40, 50]
The new Stack is: [10, 20, 30, 40, 50, 100, 200]
Last Updated :
24 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...