How to use stack in Java

4 Answers

0 votes
import java.util.Stack;

public class MyClass {
    public static void main(String args[]) {
        Stack<String> st = new Stack<>();
        
        st.push("java");
        st.push("c++");
        st.push("c#");

        System.out.println(st);
    }
}



/*
run:

[java, c++, c#]

*/

 



answered Apr 1, 2021 by avibootz
0 votes
import java.util.Stack;

public class MyClass {
    public static void main(String args[]) {
        Stack<String> st = new Stack<>();
        
        st.push("java");
        st.push("c++");
        st.push("c#");
        st.push("python");

        System.out.println(st);
        
        st.pop();
        
        System.out.println(st);
    }
}




/*
run:

[java, c++, c#, python]
[java, c++, c#]

*/

 



answered Apr 1, 2021 by avibootz
0 votes
import java.util.Stack;

public class MyClass {
    public static void main(String args[]) {
        Stack<String> st = new Stack<>();
        
        st.push("java");
        st.push("c++");
        st.push("c#");
        st.push("python");

        st.forEach(System.out::println);
    }
}




/*
run:

java
c++
c#
python

*/

 



answered Apr 1, 2021 by avibootz
0 votes
import java.util.Stack;

public class MyClass {
    public static void main(String args[]) {
        Stack<String> st = new Stack<>();
        
        st.push("java");
        st.push("c++");
        st.push("c#");
        st.push("python");

        System.out.println(st.peek());
    }
}




/*
run:

python

*/

 



answered Apr 1, 2021 by avibootz
...