How to use Java Stack with Examples

java-stack-tutorial-feature-image

[no_toc]In the tutorial, Grokonez will introduce how to use Java Stack with Examples:

  • How does Java Stack work?
  • Hierarchy of Java Stack
  • Do push, pop, peek, search operations with Java Stack data structure

Related posts:
How to use Java PriorityQueue with Examples
How to use Java TreeMap with Examples

Java Stack

– Java Stack is a last-in-first-out (LIFO) data structure of objects. The usual push and pop operations are provided:

how-to-use-java-stack-data-structure-working-principle

– Java Stack extends class Vector. See a hierarchy of Java Stack:

java.lang.Object
	java.util.AbstractCollection
		java.util.AbstractList
			java.util.Vector
				java.util.Stack

how-to-use-java-stack-data-structure-hierarchy

– Java Stack has just only one Constructor:

public Stack()

-> It creates an empty Stack.

– Java Stack implements five operations that allow a Vector to be treated as a Stack:

  • public boolean empty(): check a stack is empty or not
  • public E pop(): Removes the object at the top of a stack and returns that object as the value of this function.
  • public E peek(): get the object at the top of this stack but NOT removing it from the stack.
  • public E push(E item): Pushes an item onto the top of this stack
  • public int search(Object o): Returns the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.

Java Stack with Integer Elements Example

In the following example, we create an integer stack that does a list operations:

  • Create a stack
  • Push elements to stack
  • Pop elements to stack
  • Check a stack is empty or NOT
  • Look an element in a stack

-> Example Code:

import java.util.Stack;

public class JavaStackExamples {
	
	public static void main(String[] args) {
		
		Stack numbers = new Stack();
		numbers.push(8);
		numbers.push(9);
		numbers.push(1);
		numbers.push(2);
		numbers.push(5);
		numbers.push(16);

		// Get top values of the stack
		int top = numbers.peek();
		System.out.println("top's value = " + top); // 16
		
		// Get position of an element in a stack
		int position = numbers.search(5);
		System.out.println("Position of 5 is " + position); // 2
		
		// Pop each elements of numbers stack
		while(!numbers.empty()) {
			System.out.println(numbers.pop());
		}
		/*
			16
			5
			2
			1
			9
			8
		*/
		
	}
}

Java Stack with String Elements Example

import java.util.Stack;

public class JavaStackExamples {
	
	public static void main(String[] args) {
		
		Stack strings = new Stack();
		strings.push("Jack");
		strings.push("Charlie");
		strings.push("Joe");
		strings.push("George");

		// Get top values of the stack
		String top = strings.peek();
		System.out.println("top's value = " + top); // George
		
		// Get position of an element in a stack
		int position = strings.search("Charlie");
		System.out.println("Position of 'Charlie' is " + position); // 3
		
		// Pop each elements of numbers stack
		while(!strings.empty()) {
			System.out.println(strings.pop());
		}
		/*
			George
			Joe
			Charlie
			Jack
		*/
		
	}
}

Java Stack with User Defined Objects Example

– Create Developer class:

class Developer {
	Integer id;
	String name;

	public Developer(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return this.id;
	}

	public String getName() {
		return this.name;
	}

	public String toString() {
		return String.format("[id = %d, name = %s]", id, name);
	}
}

– For comparing 2 objects when using search operation of Java Stack, we need re-implement equals method:

@Override
public boolean equals(Object o) {
	if (this == o)
		return true;
	if (o == null || getClass() != o.getClass())
		return false;

	Developer developer = (Developer) o;
	return Integer.compare(developer.id, id) == 0 && Objects.equals(name, developer.name);
}

– Now create a Developer Stack, when do a list operations on it:

public class JavaStackExamples {

	public static void main(String[] args) {

		Stack devs = new Stack();
		devs.push(new Developer(1, "Jack"));
		devs.push(new Developer(4, "Joe"));
		devs.push(new Developer(10, "Davis"));
		devs.push(new Developer(6, "Mary"));

		// Get top values of the stack
		Developer top = devs.peek();
		System.out.println("top's value = " + top); // top's value = [id = 6, name = Mary] 

		// Get position of an element in a stack
		int position = devs.search(new Developer(4, "Joe"));
		System.out.println("Position of 'Joe' developer is " + position); // Position of 'Joe' developer is 3

		// Pop each elements of devs stack
		while (!devs.empty()) {
			System.out.println(devs.pop());
		}
		/*
			[id = 6, name = Mary]
			[id = 10, name = Davis]
			[id = 4, name = Joe]
			[id = 1, name = Jack]
		 */
	}
}

-> Output:

top's value = [id = 6, name = Mary]
Position of 'Joe' developer is 3
[id = 6, name = Mary]
[id = 10, name = Davis]
[id = 4, name = Joe]
[id = 1, name = Jack]

Conclusion

We had learned how to use Java Stack with examples:

  • Understand about Java Stack’s Working Principle and Hierarchy
  • Create Java Stack Examples with Integer, String and User Defined Object

Happy Learning! See you later!

73 thoughts on “How to use Java Stack with Examples”

  1. After research a couple of of the blog posts in your website now, and I truly like your approach of blogging. I bookmarked it to my bookmark website record and will likely be checking back soon. Pls try my web page as well and let me know what you think.

  2. There are a few interesting points at some point on this page but I don’t know if them all center to heart. There is certainly some validity but I’m going to take hold opinion until I look into it further. Great write-up , thanks and we want far more! Included with FeedBurner at the same time

  3. Howdy very nice web site!! Guy .. Beautiful .. Wonderful .. I will bookmark your site and take the feeds additionally¡KI am glad to find a lot of useful info right here in the put up, we want work out more techniques in this regard, thanks for sharing. . . . . .

  4. I¦ll immediately take hold of your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Kindly permit me understand in order that I may just subscribe. Thanks.

  5. Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my site =). We could have a link exchange arrangement between us!

  6. I have been exploring for a little bit for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i’m happy to convey that I’ve an incredibly good uncanny feeling I discovered exactly what I needed. I most certainly will make certain to don’t forget this website and give it a look regularly.

  7. Hiya, I’m really glad I have found this information. Today bloggers publish just about gossips and web and this is really annoying. A good website with exciting content, that is what I need. Thank you for keeping this web-site, I will be visiting it. Do you do newsletters? Cant find it.

  8. Whats up very cool blog!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your blog and take the feeds also?KI’m happy to seek out a lot of useful information here in the post, we’d like work out more strategies in this regard, thanks for sharing. . . . . .

  9. It¦s in reality a nice and helpful piece of information. I am happy that you shared this useful information with us. Please stay us informed like this. Thank you for sharing.

  10. 931354 979923Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something informative to read? 475298

  11. Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

  12. Excellent read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

  13. Hi! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Cheers!

  14. Throughout the awesome design of things you’ll get a B+ with regard to effort. Where exactly you misplaced me was in your specifics. As it is said, the devil is in the details… And it could not be more true at this point. Having said that, let me say to you what exactly did work. The authoring is actually highly powerful which is probably why I am taking the effort in order to comment. I do not really make it a regular habit of doing that. Second, even though I can certainly see the leaps in reasoning you make, I am not really certain of how you appear to unite your points which produce your conclusion. For right now I shall subscribe to your point however trust in the foreseeable future you connect your facts much better.

  15. I just like the valuable information you supply for your articles. I will bookmark your weblog and test again right here regularly. I’m reasonably certain I will learn plenty of new stuff proper right here! Best of luck for the next!

  16. Very efficiently written information. It will be useful to everyone who employess it, as well as yours truly :). Keep up the good work – for sure i will check out more posts.

  17. Hello very cool site!! Guy .. Beautiful .. Superb .. I’ll bookmark your site and take the feeds also…I am glad to search out so many helpful information right here within the put up, we want develop extra techniques in this regard, thank you for sharing. . . . . .

  18. 701189 491037Im so pleased to read this. This really is the kind of manual that needs to be given and not the accidental misinformation thats at the other blogs. Appreciate your sharing this best doc. 859922

  19. I’m not sure where you are getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for excellent information I was looking for this info for my mission.

  20. Wow that was unusual. I just wrote an extremely long comment
    but after I clicked submit my comment didn’t show up. Grrrr…
    well I’m not writing all that over again. Anyhow, just wanted to
    say fantastic blog!

  21. Hi to all, how is the whole thing, I think every one is getting more from this web site,
    and your views are pleasant in favor of new viewers.

  22. An intriguing discussion is worth comment. I do believe that you ought to
    write more on this issue, it might not be a taboo matter but generally folks don’t discuss these subjects.
    To the next! Best wishes!!

  23. We are a bunch of volunteers and opening a brand
    new scheme in our community. Your web site provided us with valuable information to work on. You’ve done an impressive job and our whole group might
    be thankful to you.

  24. Thanks , I have just been searching for information about this subject for a while and yours is the greatest I’ve came upon till now.
    However, what in regards to the bottom line? Are you certain about the source?

  25. Thanks for the marvelous posting! I actually enjoyed reading
    it, you can be a great author.I will make certain to bookmark your blog and may come back someday.

    I want to encourage you to definitely continue your great writing, have a nice day!

  26. Hello there, I found your website by means of Google even as
    searching for a comparable matter, your web site got here up,
    it seems good. I’ve bookmarked it in my google bookmarks.

    Hello there, just changed into alert to your blog thru Google, and
    located that it is really informative. I’m going to watch out for
    brussels. I’ll be grateful if you proceed this {in future}.
    A lot of other people will probably be benefited out of your writing.
    Cheers!

  27. Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn’t show
    up. Grrrr… well I’m not writing all that over again. Anyway, just
    wanted to say fantastic blog!

  28. Hi! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us useful information to work on. You have done a marvellous job!

  29. Excellent way of explaining, and nice article to obtain data on the topic
    of my presentation focus, which i am going to deliver
    in academy.

  30. You really make it seem so easy along with your presentation however
    I in finding this matter to be actually one thing which I think I would by
    no means understand. It sort of feels too complicated and extremely wide for me.
    I’m looking ahead for your subsequent submit, I will attempt to get the dangle of it!

  31. Hi there, I discovered your site by way of Google at the same time as searching for
    a comparable topic, your site came up, it seems to
    be great. I’ve bookmarked it in my google bookmarks.
    Hi there, just changed into aware of your weblog through
    Google, and located that it’s truly informative.
    I’m gonna watch out for brussels. I’ll be grateful if you happen to continue this {in future}.
    Many other folks can be benefited out of your writing.
    Cheers!

  32. My developer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on a number of websites for about a year and am nervous about switching to another platform.
    I have heard good things about blogengine.net.
    Is there a way I can import all my wordpress posts into it?
    Any kind of help would be really appreciated!

  33. I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know
    such detailed about my problem. You are incredible! Thanks!

  34. This is really interesting, You’re a very skilled blogger.
    I have joined your feed and look forward to seeking more of your fantastic post.

    Also, I’ve shared your site in my social networks!

  35. Sweet blog! I found it while searching on Yahoo News. Do you
    have any suggestions on how to get listed in Yahoo News? I’ve been trying
    for a while but I never seem to get there! Appreciate it

  36. It’s genuinely very difficult in this busy life to listen news on TV,
    therefore I just use the web for that purpose, and take the most up-to-date news.

  37. Hey there! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in trading links or maybe guest writing a blog post or vice-versa?
    My site covers a lot of the same subjects as yours and I feel we could greatly benefit from each other.
    If you’re interested feel free to send me an e-mail.

    I look forward to hearing from you! Excellent blog by the
    way!

  38. Good post however I was wanting to know if you could write
    a litte more on this subject? I’d be very grateful if you could elaborate a little bit further.

    Appreciate it!

  39. I don’t even know how I finished up here, but I assumed this publish used
    to be good. I don’t understand who you’re however certainly you’re going to a famous
    blogger if you are not already. Cheers!

  40. My family always say that I am killing my time here
    at net, but I know I am getting familiarity all the time by reading such good articles or reviews.

Leave a Reply

Your email address will not be published. Required fields are marked *