<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aman Gupta</title>
    <description>The latest articles on DEV Community by Aman Gupta (@alphaaman).</description>
    <link>https://dev.to/alphaaman</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F541993%2Fe6fd1d88-761d-4836-9ae2-1c1c65c8b230.png</url>
      <title>DEV Community: Aman Gupta</title>
      <link>https://dev.to/alphaaman</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/alphaaman"/>
    <language>en</language>
    <item>
      <title>The Art of Clean Code: Java Style and Conventions</title>
      <dc:creator>Aman Gupta</dc:creator>
      <pubDate>Tue, 26 Sep 2023 12:03:13 +0000</pubDate>
      <link>https://dev.to/alphaaman/the-art-of-clean-code-java-style-and-conventions-193h</link>
      <guid>https://dev.to/alphaaman/the-art-of-clean-code-java-style-and-conventions-193h</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Welcome to our journey through the world of Java code style and conventions! 🚀&lt;/p&gt;

&lt;p&gt;In the realm of software development, writing top-notch code is like creating a masterpiece. It's all about adhering to consistent rules and guidelines to craft code that's not just correct, but also elegant, readable, and easy to maintain.&lt;/p&gt;

&lt;p&gt;In this guide, we're going to take you on an interactive adventure where you'll discover the secrets of writing Java code that stands out. Buckle up as we explore essential principles and techniques that will transform your code into a work of art. 🎨💻&lt;/p&gt;

&lt;p&gt;Ready? Let's dive in! 🏊‍♂️🌊&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Following Java Best Practices
&lt;/h2&gt;

&lt;p&gt;Following Java best practices for code style and conventions brings several benefits to developers and projects. First and foremost, it improves code readability, making it easier for both yourself and others to understand and navigate the codebase. Consistent code style also helps with collaboration, as everyone can work on the code seamlessly without tripping over different formatting preferences.&lt;/p&gt;

&lt;p&gt;Moreover, adhering to best practices enhances code maintainability. When code follows a standard structure and naming conventions, it becomes easier to locate specific elements, identify potential issues, and make modifications. It also helps in writing efficient and bug-free code, as proper formatting and naming conventions can catch potential errors early on.&lt;/p&gt;

&lt;p&gt;By adopting Java best practices for code style and conventions, you not only make your code easier to work with but also contribute to a positive and productive development environment. Plus, who doesn't want to be known as the person who writes clean and professional code?&lt;/p&gt;

&lt;h2&gt;
  
  
  Naming Conventions and Variable Declarations
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;h4&gt;
  
  
  Naming Conventions for Classes, Interfaces, and Packages
&lt;/h4&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine you're organizing your toy collection. You want to make sure you can quickly find each toy when you need it, right? Well, naming classes, interfaces, and packages in coding is a bit like giving your toys clear labels.&lt;/p&gt;

&lt;p&gt;Here are some tips to make sure your code names make sense:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Descriptive Names&lt;/strong&gt;: Instead of naming something "&lt;em&gt;Thing1&lt;/em&gt;" or "&lt;em&gt;Stuff&lt;/em&gt;," choose a name that explains what it does. For example, if you have a piece of code that calculates the total price of items in a shopping cart, you might call it &lt;code&gt;calculateTotalPrice&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Start with a Capital Letter&lt;/strong&gt;: Just like you write your name with a capital letter at the beginning, in code, class and interface names should also start with a capital letter. For example, "&lt;em&gt;Car&lt;/em&gt;" instead of "&lt;em&gt;car&lt;/em&gt;."&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Camel Case&lt;/strong&gt;: Camel case means that if your name has more than one word, you start each new word with a capital letter, like &lt;code&gt;calculateTotalPrice&lt;/code&gt; instead of &lt;code&gt;calculatetotalprice&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lowercase for Packages&lt;/strong&gt;: When you organize your toys into boxes, you give the boxes names, right? In coding, we do something similar with packages. Use lowercase letters for package names and follow a convention like &lt;code&gt;com.example.package&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Variable Naming and Declaration Guidelines&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine you have a bunch of jars, and you want to put different things in them. It would be confusing if you labeled the jars with random letters or codes, right? Instead, you'd use labels that tell you exactly what's inside each jar.&lt;/p&gt;

&lt;p&gt;In coding, it's similar when you create variables (like jars) to store information. Here are some tips:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Descriptive Names&lt;/strong&gt;: When you create a variable, give it a name that says what it holds. For example, if you're storing a person's age, you could call it "&lt;em&gt;personAge&lt;/em&gt;" instead of just "&lt;em&gt;x&lt;/em&gt;."&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Short Names&lt;/strong&gt;: Don't use super short names or weird abbreviations that nobody can understand. Imagine if your jar label said "&lt;em&gt;A&lt;/em&gt;" instead of "&lt;em&gt;Cookies&lt;/em&gt;" – that wouldn't help anyone!&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Include Data Type&lt;/strong&gt;: Sometimes, it's a good idea to add the type of information the variable holds in its name. For instance, if it's a number, you can use something like "&lt;em&gt;countInt&lt;/em&gt;" or if it's a name, "&lt;em&gt;nameString&lt;/em&gt;." This way, it's even clearer.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Constants and Enumerations Naming Conventions&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine you have some special values in your code that never change, like the maximum number of something. It's like having a super important rule written down.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Uppercase Letters&lt;/strong&gt;: When you write these special values, use BIG letters to make them stand out. So instead of saying "&lt;em&gt;maximumSize&lt;/em&gt;," you write "&lt;em&gt;MAX_SIZE&lt;/em&gt;."&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Add Underscores Between Words&lt;/strong&gt;: If your special value has more than one word, put an underscore (_) between them. It's like putting a dash between words for clarity. For example, "MAX_SIZE" instead of "MAXSIZE."&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enums (Special Lists)&lt;/strong&gt;: If you have a list of special values, each value should also follow the BIG letters and underscore rule. But put each value on a separate line, like this:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;  &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;Color&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;RED&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="no"&gt;GREEN&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="no"&gt;BLUE&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Abbreviations&lt;/strong&gt;: Don't use short forms or abbreviations unless everybody knows what they mean. So, instead of "&lt;em&gt;MAX_SZ&lt;/em&gt;," use "&lt;em&gt;MAX_SIZE&lt;/em&gt;" to make sure everyone understands.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Formatting and Indentation Best Practices
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Code Formatting Guidelines&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When you write code, it's like writing a story. To make sure everyone can easily read and understand your code, follow these rules:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Spaces for Indentation&lt;/strong&gt;: Imagine your code as a set of building blocks. Each time you go deeper into a block (like inside a loop or a function), use four spaces to indent it. This makes it neat and organized.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Braces Get Their Own Lines&lt;/strong&gt;: Think of curly braces '{' and '}' like bookends. Put them on separate lines, and make sure they line up nicely. It's like how you'd place bookends neatly on a shelf.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Spaces Around Symbols&lt;/strong&gt;: Imagine code symbols (+, -, =) as traffic signs. Give them some space. For example, write "x = 5" instead of "x=5". It's 
like leaving room around road signs for better visibility.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Indentation and Line Length Recommendations&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Indentation Is Like Stacking Blocks&lt;/strong&gt;: Keep your code organized by stacking blocks of code neatly. Each level should be four spaces. This helps others understand where things belong.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line Length Is Like Writing on a Page&lt;/strong&gt;: Make sure your lines of code are not too long, like a sentence that goes on and on. Try to keep them between 80 to 120 characters, so you don't have to scroll left and right to read the code.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Aligning Code and Using White Spaces&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Aligning Is Like Lining Up Soldiers&lt;/strong&gt;: When you have things that should match or look similar, make sure they line up. For example, if you have a list of names, they should all start at the same spot, like soldiers in a formation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blank Lines Are Like Paragraphs&lt;/strong&gt;: Just like in a book, you use blank lines to separate different sections of your code. It's like having paragraphs so that readers can understand where one idea ends and the next begins.
By following these guidelines, your code becomes like a well-organized book that's easy for others to read and understand.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Comments and Documentation Guidelines
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Importance of Comments and Documentation&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Comments and documentation provide valuable information about the code's purpose, functionality, and usage. They serve as a guide for developers and future maintainers, helping them understand the code and make informed decisions. Taking the time to write clear comments and documentation can save hours of confusion and frustration.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Writing Clear and Concise Comments&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When you write comments in your code, think of them as helpful notes to yourself and others who might read your code later. Here's how to make your comments useful:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Focus on "Why" More than "How"&lt;/strong&gt;: Instead of explaining exactly how your code works (because that should be clear from the code itself), focus on why you made certain choices. This helps readers understand the reasons behind your code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Overdoing It&lt;/strong&gt;: Don't put comments everywhere. Only comment on things that are complex or might not be obvious to someone reading your code. Too many comments can clutter your code and make it hard to read.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Document Assumptions&lt;/strong&gt;: If your code relies on certain assumptions or has limitations, it's essential to mention them in your comments. This prevents misunderstandings.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Documenting JavaDoc Tags and Usage&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;JavaDoc is like a special way of writing comments that can automatically generate documentation for your code. Here's how to use it effectively:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use JavaDoc Tags: When you write comments for classes and methods, use special tags (like @ param, @return, @throws) to provide extra information. These tags help users of your code understand what inputs are expected, what gets returned, and what exceptions might be thrown.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Be Consistent&lt;/strong&gt;: If you're creating a public interface that others will use, make sure your JavaDoc comments are consistent and clear. Think of it as a contract between you (the developer) and anyone who uses your code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep It Up-to-Date&lt;/strong&gt;: Whenever you change your code, remember to update your JavaDoc comments too. This ensures that the documentation always matches the code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Error Handling,Exceptions and Logging
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Error Handling Practices&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Error handling is like preventing problems before they become big headaches. In Java, here's what you should do:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Catch Specific Errors&lt;/strong&gt;: When something goes wrong, don't just catch any error. Catch the specific one that fits the situation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deal with Errors Nicely&lt;/strong&gt;: Don't just ignore errors; handle them gracefully. This means you should do something useful when things go awry, not just pretend they didn't happen.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Give Helpful Error Messages&lt;/strong&gt;: If something goes wrong, tell people what happened in a way they can understand. This helps with troubleshooting.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Don't Nest Too Much&lt;/strong&gt;: Avoid putting errors within errors within errors (try-catch blocks inside each other). It makes your code hard to read.
Remember, errors happen, but how you handle them can make a big difference.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Exception Handling Best Practices&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Think of exceptions like unexpected guests. Here's how to handle them in Java:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Checked Exceptions Carefully&lt;/strong&gt;: Only use them when it makes sense in your program. They're like RSVP guests - you expect them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use Unchecked Exceptions for Checks&lt;/strong&gt;: For things like checking if a password is correct, use unchecked exceptions. It's like uninvited guests who show up without notice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Exceptions in Constructors&lt;/strong&gt;: Constructors should be trouble-free entry points. Don't let them throw surprises.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fail Fast, Fail Loudly&lt;/strong&gt;: If something's wrong, let it be known early and clearly. Don't wait until the party is ruined.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Proper Logging and Error Reporting&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Logging is like taking notes at an event to understand what's happening. Do it right:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Reliable Logging Tools&lt;/strong&gt;: Pick a good tool (like Log4j or SLF4J) to keep track of what's going on.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Control Log Amount&lt;/strong&gt;: Set the amount of information you log - not too little, not too much.&lt;/li&gt;
&lt;li&gt;Write Useful Log Messages: Make sure your log messages are clear and have the right details.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Report Critical Issues&lt;/strong&gt;: Tell the right people when something serious goes wrong.
By doing these things, you can keep your application from becoming a chaos party.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Object-Oriented Design Principles
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Encapsulation and Information Hiding&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Encapsulation is like keeping your stuff organized in boxes. In Java, it's about organizing your code neatly:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Private Members&lt;/strong&gt;: Keep most of your code's details private. It's like hiding your stuff in a box. Only show what's necessary.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Getters and Setters&lt;/strong&gt;: If someone needs something from your box, give it to them through a controlled way, like using a "getter" or "setter."&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Limit Visibility&lt;/strong&gt;: Don't let everyone see everything. Keep some things hidden unless there's a good reason to show them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Loose Coupling, High Cohesion&lt;/strong&gt;: Your code should be like a puzzle with pieces that fit well together but aren't too stuck. It helps make your code easier to manage.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Inheritance and Polymorphism Guidelines&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Inheritance and polymorphism are like family relationships in code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Composition Over Inheritance&lt;/strong&gt;: Think of it like building new LEGO creations instead of just using existing LEGO sets. Create new things when needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;LEGO&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3r04mp76zwsmfizje7s.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3r04mp76zwsmfizje7s.jpg" alt="LEGO"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Abstract Classes and Interfaces&lt;/strong&gt;: Use them to define common rules or behaviors that different parts of your code should follow.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Be Careful with Overrides&lt;/strong&gt;: When you change how something works in a family tree, be sure it doesn't cause unexpected surprises.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Polymorphism&lt;/strong&gt;: Write code that can adapt and change, like being flexible with different LEGO pieces.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Composition and Interface Segregation&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Composition is like creating complex structures from simple parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Composition Over Inheritance&lt;/strong&gt;: Build your code by putting together small, simple pieces rather than inheriting from big, complicated ones.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Focused Interfaces&lt;/strong&gt;: Make sure each interface does one clear job, like a tool for a specific task.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Split Big Interfaces&lt;/strong&gt;: If a tool has too many functions, break it into smaller, more specialized tools. It's like having a toolbox with many compartments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dependency Injection&lt;/strong&gt;: Assemble your code using parts and tools, like putting together a LEGO set.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By following these principles, your code becomes like a well-organized collection of boxes, LEGO creations, and specialized tools, making it easier to manage and maintain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing and Debugging Strategies
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Writing Effective Unit Tests&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unit tests are like superheroes for your code. Here's how to use them well in Java:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Focused Tests&lt;/strong&gt;: Write tests that check one specific thing at a time. It's like a superhero with a single superpower.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing Framework&lt;/strong&gt;: Use a testing tool (like JUnit or TestNG) to make testing easier and organized.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Positive and Negative Tests&lt;/strong&gt;: Test things that should work (positive) and things that shouldn't (negative). Cover all possibilities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automate Your Tests&lt;/strong&gt;: Make your tests run automatically, so you can catch issues early.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By writing these effective unit tests, you'll save your code from evil bugs.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Debugging Techniques and Tools&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Debugging is like being a detective for code problems. Here's how to do it well in Java:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Step-by-Step and Breakpoints&lt;/strong&gt;: Examine your code step by step, like a detective following clues. Use breakpoints to pause the code where you want to investigate.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Console and Debuggers&lt;/strong&gt;: Print important information to the console or use a debugger tool to inspect your code as it runs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stack Traces and Errors&lt;/strong&gt;: Look at error messages and stack traces to figure out what went wrong.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Debugging Tools&lt;/strong&gt;: Use special tools and features in your coding environment to help you find issues faster.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With these techniques and tools, you'll become a code detective and solve cases of mysterious bugs.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Code Coverage and Test Automation&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Code coverage and test automation are like having backup dancers for your code's performance:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;High Code Coverage&lt;/strong&gt;: Try to test as much of your code as possible. It's like making sure your dancers hit every move.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Code Coverage Tools&lt;/strong&gt;: Use tools like JaCoCo or Cobertura to measure how well your tests cover your code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automate Everything&lt;/strong&gt;: Make your tests run automatically. This saves time and ensures consistency.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Different Types of Tests&lt;/strong&gt;: Use different types of tests (unit, integration, end-to-end) to check your code from all angles.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With code coverage and test automation, your code will perform flawlessly on the quality assurance stage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code Review and Collaboration Practices
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Importance of Code Reviews&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Think of code reviews as quality checks for your code. In Java, they're important because:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Early Issue Detection&lt;/strong&gt;: They help find and fix problems before they cause trouble in your software.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Knowledge Sharing&lt;/strong&gt;: They let team members learn from each other's code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Coding Standards&lt;/strong&gt;: They make sure everyone follows the same coding rules and best practices.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Teamwork&lt;/strong&gt;: They promote working together, leading to better code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Embracing code reviews means building a strong foundation for your Java projects.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Conducting Effective Code Reviews&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Effective code reviews are like helpful conversations, not critiques. Here's how to do them well:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Focus on Code, Not People&lt;/strong&gt;: Don't blame individuals. Look at the code's strengths and weaknesses.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Give Specific Feedback&lt;/strong&gt;: Point out exactly what needs improvement and why.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Timely Reviews&lt;/strong&gt;: Don't make others wait. Keep the process moving.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Encourage Discussion&lt;/strong&gt;: Let reviewers and authors talk and learn from each other.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With effective code reviews, your code gets better over time.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Collaborative Development and Version Control&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Collaboration and version control are like a dance where everyone stays in sync:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use Version Control (like Git)&lt;/strong&gt;: It helps manage code changes and lets people work together.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Branching and Merging&lt;/strong&gt;: Have a plan for how to work on different parts of the code and combine them.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These practices ensure everyone works together smoothly, just like synchronized dancers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In conclusion, following these best practices for coding, testing, and collaboration in Java leads to more efficient, maintainable, and reliable software. By adhering to these guidelines, developers can create high-quality Java applications that meet industry standards and foster productive teamwork.&lt;/p&gt;

&lt;p&gt;It's been great connecting with you! If you have any more questions or need assistance in the future, feel free to reach out &lt;a href="https://www.instagram.com/_alpha_golf/?hl=en" rel="noopener noreferrer"&gt;me&lt;/a&gt;. Goodbye, and have a wonderful day!&lt;/p&gt;

</description>
      <category>java</category>
      <category>javascript</category>
      <category>python</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Java Collections Framework - A Quick and In-Depth Look (Part - 2)</title>
      <dc:creator>Aman Gupta</dc:creator>
      <pubDate>Wed, 20 Sep 2023 17:27:14 +0000</pubDate>
      <link>https://dev.to/alphaaman/java-collections-framework-a-quick-and-in-depth-look-part-2-imo</link>
      <guid>https://dev.to/alphaaman/java-collections-framework-a-quick-and-in-depth-look-part-2-imo</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Welcome to Part 2 of our series on the Java Collections Framework! In this continuation, we'll explore more advanced aspects of this essential framework, diving into key interfaces and classes that make data management in Java both efficient and powerful. Get ready to level up your Java skills and expand your toolkit for handling collections and data structures.&lt;/p&gt;

&lt;p&gt;We have discussed there List and Queue Interfaces and if you haven't read first part then you read it &lt;a href="https://dev.to/alphaaman/building-a-role-based-access-control-system-with-jwt-in-spring-boot-a7l"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Set Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The Set interface represents an unordered collection of unique elements. Unlike lists, sets do not allow duplicate values, making them ideal for scenarios where you need to ensure distinct elements. The Set interface includes several methods for adding, removing, and checking the presence of elements. Popular implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet, each with its own characteristics and use cases. By using Set, you can efficiently manage collections of elements without worrying about duplicates, making it a valuable tool in Java programming.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1wOc5LD8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9luw89x8jx71rr5qd0hp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1wOc5LD8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9luw89x8jx71rr5qd0hp.png" alt="Set" width="680" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  HashSet
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;HashSet provides a collection of unique elements without any specific order. This means that you can store elements in a HashSet, and it will automatically ensure that duplicates are not allowed. It is highly efficient for checking the presence of elements and adding or removing elements from the set. While elements are not stored in a particular sequence, this data structure is particularly useful when you need to maintain a collection of items where uniqueness is a priority, and the order of elements doesn't matter.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K4fcven_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uooixqlr62zhupxs0lve.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K4fcven_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uooixqlr62zhupxs0lve.png" alt="HashSet" width="700" height="360"&gt;&lt;/a&gt;&lt;br&gt;
Here's an example of how to use a HashSet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.HashSet&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HashSetExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;HashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;fruits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Adding elements&lt;/span&gt;
        &lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Apple"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Banana"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Cherry"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Attempting to add a duplicate element (it won't be added)&lt;/span&gt;
        &lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Apple"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Iterating through the set&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;fruit&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruit&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, "Apple" is added only once, demonstrating HashSet's uniqueness property. When you iterate through the HashSet, the order of elements may not be the same as they were added, highlighting its unordered nature.&lt;/p&gt;

&lt;h3&gt;
  
  
  LinkedHashSet
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;LinkedHashSet combines the features of both HashSet and LinkedHashMap, offering a collection of unique elements with predictable iteration order. Unlike HashSet, LinkedHashSet maintains the order in which elements were inserted into the set. This means that when you iterate over a LinkedHashSet, the elements will be returned in the order they were added. This can be useful in situations where you need both uniqueness and a specific order for your elements.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's consider a library catalog system. In this scenario, you want to maintain a list of books in a way that allows you to keep track of unique titles while preserving the order in which the books were added to the catalog. You decide to use a LinkedHashSet to store the book titles. As new books arrive at the library, you add their titles to the LinkedHashSet. Because LinkedHashSet maintains the insertion order, you can easily browse the catalog in the order the books were acquired, making it convenient for library staff to locate and manage the collection efficiently.&lt;/p&gt;

&lt;p&gt;Here's a simple Java program that demonstrates the usage of a LinkedHashSet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.LinkedHashSet&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashSetExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a LinkedHashSet to store unique elements while preserving insertion order&lt;/span&gt;
        &lt;span class="nc"&gt;LinkedHashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;fruitsSet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Adding elements to the LinkedHashSet&lt;/span&gt;
        &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Apple"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Banana"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Cherry"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Banana"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Adding a duplicate element&lt;/span&gt;

        &lt;span class="c1"&gt;// Display the elements of the LinkedHashSet&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Fruits in the LinkedHashSet:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;fruit&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruit&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Check if a specific element exists in the LinkedHashSet&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;searchFruit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Cherry"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;contains&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;searchFruit&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;searchFruit&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" is in the LinkedHashSet."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;searchFruit&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" is not in the LinkedHashSet."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Remove an element from the LinkedHashSet&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;removedFruit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Banana"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;isRemoved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fruitsSet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedFruit&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;isRemoved&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedFruit&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" has been removed from the LinkedHashSet."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedFruit&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" was not found in the LinkedHashSet."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This program creates a LinkedHashSet named fruitsSet, adds several fruits (including a duplicate), displays the elements while preserving insertion order, checks for the existence of a specific fruit, and removes an element from the LinkedHashSet. It illustrates the key features of LinkedHashSet, including uniqueness and order preservation.&lt;/p&gt;

&lt;h3&gt;
  
  
  TreeSet
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A TreeSet is a sorted collection in Java that implements the Set interface. Unlike a HashSet, which does not guarantee any specific order of elements, a TreeSet maintains elements in sorted order. This sorting is typically in ascending order, but you can customize it by providing a comparator during TreeSet creation. TreeSet uses a Red-Black Tree data structure internally for efficient sorting and retrieval operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here's a brief example to demonstrate the usage of a TreeSet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.TreeSet&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TreeSetExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a TreeSet to store integers in sorted order&lt;/span&gt;
        &lt;span class="nc"&gt;TreeSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add elements to the TreeSet&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Display the elements in sorted order&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Numbers in ascending order:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Remove an element from the TreeSet&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;removedNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;isRemoved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedNumber&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;isRemoved&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedNumber&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" has been removed."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;removedNumber&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" was not found."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, a TreeSet named numbers is created to store integers. When elements are added, the TreeSet automatically sorts them in ascending order. The program also demonstrates the removal of an element from the TreeSet. TreeSet is useful when you need a sorted collection of unique elements in your Java application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Map Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The Map interface in Java represents a collection of key-value pairs, where each key is unique and maps to a specific value. It allows for efficient data retrieval based on keys, making it useful for tasks like looking up values by identifiers. Java provides various implementations of the Map interface, such as HashMap, TreeMap, and LinkedHashMap, each suited for different use cases. Maps are commonly used to store and manage data where the relationship between keys and values is critical. They enable quick and direct access to values based on their associated keys, enhancing the efficiency of data retrieval and manipulation in Java programs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine you're managing a restaurant. You can use a Map to represent your menu. Each item on the menu has a unique identifier (like an item code or name), and the Map associates this identifier with the item's details, such as its name, description, price, and availability. When customers place orders, you can efficiently look up menu items and calculate the total bill by referencing the Map. This application of the Map interface simplifies order processing and enhances customer service in the restaurant business.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7ralhn7O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpkrozmya7jd85jmsb0u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7ralhn7O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpkrozmya7jd85jmsb0u.png" alt="Map Interface" width="440" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.&lt;br&gt;
Here are the common methods of the Map interface with their descriptions:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;put(K key, V value)&lt;/td&gt;
&lt;td&gt;Associates the specified value with the specified key in this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;get(Object key)&lt;/td&gt;
&lt;td&gt;Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove(Object key)&lt;/td&gt;
&lt;td&gt;Removes the mapping for the specified key from this map if present.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;containsKey(Object key)&lt;/td&gt;
&lt;td&gt;Returns true if this map contains a mapping for the specified key.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;containsValue(Object value)&lt;/td&gt;
&lt;td&gt;Returns true if this map maps one or more keys to the specified value.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;size()&lt;/td&gt;
&lt;td&gt;Returns the number of key-value mappings in this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;isEmpty()&lt;/td&gt;
&lt;td&gt;Returns true if this map contains no key-value mappings.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;clear()&lt;/td&gt;
&lt;td&gt;Removes all of the mappings from this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;keySet()&lt;/td&gt;
&lt;td&gt;Returns a Set view of the keys contained in this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;values()&lt;/td&gt;
&lt;td&gt;Returns a Collection view of the values contained in this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;entrySet()&lt;/td&gt;
&lt;td&gt;Returns a Set view of the mappings contained in this map.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  HashMap
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A HashMap in Java is a fundamental data structure that facilitates the storage and retrieval of data using key-value pairs. It is a part of the Java Collections Framework and provides efficient access to values based on their associated keys. HashMaps use a hash function to compute an index into an array where the values are stored, making retrieval swift even for large datasets. They do not allow duplicate keys and permit one null key along with multiple null values. Java developers frequently use HashMaps to implement data structures like dictionaries and associative arrays, where data is organized and accessed by unique keys, enabling efficient and fast data retrieval in various applications.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OgSwghUF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3tgf523swfmnt2tdn12.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OgSwghUF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3tgf523swfmnt2tdn12.png" alt="HashMAp" width="800" height="286"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's a simple example of how to use a HashMap in Java:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.HashMap&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HashMapExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a HashMap&lt;/span&gt;
        &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ageMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add key-value pairs&lt;/span&gt;
        &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Alice"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Bob"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Charlie"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;22&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Retrieve values by key&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;aliceAge&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Alice"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Returns 25&lt;/span&gt;

        &lt;span class="c1"&gt;// Check if a key exists&lt;/span&gt;
        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;containsKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;containsKey&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"David"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Returns false&lt;/span&gt;

        &lt;span class="c1"&gt;// Iterate over key-value pairs&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;keySet&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ageMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;"'s age is "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we create a HashMap called ageMap, add key-value pairs, retrieve values by keys, check for the existence of keys, and iterate over the entries. HashMap is a versatile and widely used data structure in Java for various applications where you need to associate keys with values efficiently.&lt;/p&gt;

&lt;h3&gt;
  
  
  HashTable
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A HashTable is similar to a HashMap but has several differences. A HashTable is a synchronized collection, which means it is thread-safe and can be used in multi-threaded applications without the need for external synchronization. It uses a hash function to map keys to values, allowing for efficient key-value retrieval. However, HashTable has become somewhat outdated, and it is recommended to use HashMap in most cases, as it offers similar functionality but is not synchronized, making it more efficient for single-threaded applications. Additionally, HashTable does not allow null keys or values, whereas HashMap permits one null key and multiple null values.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine you have a magical book, and you want to keep a record of famous landmarks in different countries. This book has pages for each country, and you can write down the famous place in that country on its respective page.Whenever you want to know the famous landmark for a particular country, you simply open your magical book to the corresponding page, and there it is, just like how a HashTable lets you quickly retrieve values (landmarks) associated with specific keys (countries).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_NqB3BZC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n88z5x1zy3ehrt0xpfl1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_NqB3BZC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n88z5x1zy3ehrt0xpfl1.png" alt="Hash Table" width="800" height="418"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's a simplified representation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Hashtable&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LandmarksExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a HashTable to store country-landmark pairs&lt;/span&gt;
        &lt;span class="nc"&gt;Hashtable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;landmarks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Hashtable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add country-landmark pairs&lt;/span&gt;
        &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"India"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Taj Mahal"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"France"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Eiffel Tower"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"China"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Great Wall of China"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"USA"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Statue of Liberty"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Retrieve and print landmarks&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;landmarkIndia&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"India"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;landmarkFrance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"France"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;landmarkChina&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"China"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;landmarkUSA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;landmarks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"USA"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Famous Landmarks:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"India: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;landmarkIndia&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"France: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;landmarkFrance&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"China: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;landmarkChina&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"USA: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;landmarkUSA&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the HashTable stores country-landmark pairs, allowing you to retrieve the famous landmark for each country.&lt;/p&gt;

&lt;h3&gt;
  
  
  LinkedHashMap
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A LinkedHashMap in Java is a class that combines the features of a hash table and a linked list to store key-value pairs. It maintains the order of elements based on the insertion sequence, allowing predictable iteration. This means that when you iterate through a LinkedHashMap, the elements are returned in the order in which they were added. It provides efficient access to elements via hashing and preserves the order of insertion, making it useful for scenarios where you need both quick access to elements and a predictable iteration order.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A LinkedHashMap in Java can be compared to a numbered list of tasks you need to accomplish in a day. Each task (an entry) is associated with a unique number (the order of insertion), and you want to maintain the order of tasks as you complete them. As you go about your day, you keep track of your tasks in this list. If you finish one task, you cross it off, and if you add a new one, you simply append it to the end of the list. This way, your tasks are not only organized but also executed in the order you added them. Similarly, a LinkedHashMap maintains the order of key-value pairs based on the insertion sequence, allowing you to access and manipulate them in a predictable order.&lt;/p&gt;

&lt;p&gt;Here's a simple Java program that demonstrates how to use a LinkedHashMap to store and retrieve country-capital pairs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Map&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashMapExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a LinkedHashMap to store country-capital pairs&lt;/span&gt;
        &lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add country-capital pairs&lt;/span&gt;
        &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"India"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"New Delhi"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"USA"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Washington, D.C."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"China"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Beijing"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"France"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Paris"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Retrieve and print the capitals of selected countries&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;capitalOfIndia&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"India"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;capitalOfUSA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"USA"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Capital of India: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;capitalOfIndia&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Capital of USA: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;capitalOfUSA&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Iterate through the LinkedHashMap and print all country-capital pairs&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"All Country-Capital Pairs:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Entry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;countryCapitalMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;entrySet&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;country&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;capital&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" - "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;capital&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  TreeMap
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A TreeMap is a class in Java that implements the Map interface and extends the AbstractMap class. It is part of the Java Collections Framework and provides a Red-Black tree-based implementation of the Map interface. TreeMap stores its elements in a sorted and balanced tree structure, which allows for efficient operations like insertion, deletion, and retrieval of elements.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wRSAeY1h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b212gfburvaff2ypyin.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wRSAeY1h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b212gfburvaff2ypyin.png" alt="Tree Map" width="640" height="360"&gt;&lt;/a&gt;&lt;br&gt;
A TreeMap in Java is like an organized library catalog where books (values) are sorted and arranged by their genres (keys). This data structure automatically keeps genres in alphabetical order, making it easy to find and manage books within each category efficiently. When you add a new book to the library, you simply place it in the correct genre's section in the TreeMap. This sorting and organization make TreeMap a valuable tool for tasks requiring ordered data, ensuring quick and effective access to information.&lt;/p&gt;

&lt;p&gt;Here's a simple example of how a TreeMap can be used to store and retrieve key-value pairs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TreeMapExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a TreeMap to store age-name pairs&lt;/span&gt;
        &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ageNameMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add age-name pairs to the TreeMap&lt;/span&gt;
        &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"John"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Alice"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;22&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Bob"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;28&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Eve"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Retrieve and print the names of people by their ages&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Name of person with age 25: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Name of person with age 30: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;

        &lt;span class="c1"&gt;// Iterate through the TreeMap and print all age-name pairs in ascending order of age&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"All Age-Name Pairs:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Entry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ageNameMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;entrySet&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Age: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;", Name: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we create a TreeMap named ageNameMap to store age-name pairs. The keys are ages (integers), and the values are names (strings). We add pairs using the put method and retrieve the names of people by their ages using the get method. When we iterate through the TreeMap, it automatically returns the age-name pairs in ascending order of age due to its sorting mechanism.&lt;/p&gt;

&lt;p&gt;We've seen how Set implementations like HashSet, LinkedHashSet, and TreeSet cater to different needs, from unsorted uniqueness to sorted order. Similarly, Map implementations like HashMap, LinkedHashMap, and TreeMap offer varying approaches to key-value mapping, with differences in performance and ordering.&lt;/p&gt;

&lt;p&gt;Stay tuned for the next installment as we continue this exciting journey through the world of Java collections!&lt;/p&gt;

&lt;p&gt;Thanks for reading blog post.&lt;br&gt;
If you have any queries or doubts, feel free to connect with me on &lt;a href="https://www.instagram.com/_alpha_golf/?hl=en"&gt;Instagram&lt;/a&gt;. I'm here to help you with any questions you may have regarding Java or any other topic. Keep learning and exploring, and don't hesitate to reach out whenever you need assistance or clarification. Happy coding!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>java</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Java Collections Framework - A Quick and In-Depth Look (Part - 1)</title>
      <dc:creator>Aman Gupta</dc:creator>
      <pubDate>Mon, 18 Sep 2023 11:30:03 +0000</pubDate>
      <link>https://dev.to/alphaaman/java-collections-framework-a-quick-and-in-depth-look-part-1-2mi0</link>
      <guid>https://dev.to/alphaaman/java-collections-framework-a-quick-and-in-depth-look-part-1-2mi0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Hey folks, the Collections Framework is a really important thing in Java. Think of it as a treasure chest where you can store and manage your data. It includes interfaces like Collection, Map, and Iterator. Inside the Collection interface, you'll find interfaces like List, Set, and Queue, which organize data based on different properties.&lt;/p&gt;

&lt;p&gt;For example, if you want to store data together, you can use List. If you need unique values, go for Set. And if you want to prioritize elements, Queue is your choice.&lt;/p&gt;

&lt;p&gt;After that, there are classes like ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet that implement these interfaces.&lt;/p&gt;

&lt;p&gt;So, the Collections Framework is a powerful tool that helps you with data management. Learning it is crucial if you're into Java coding.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why do we need to use Java Collections
&lt;/h3&gt;

&lt;p&gt;Now, picture this: when you're coding, you often need to store data or perform operations on it, like searching, deleting, or modifying. That's where the Collections Framework comes into play. It saves you the hassle of creating your own data structures because all these things are already available.&lt;/p&gt;

&lt;p&gt;Imagine you're preparing for an interview or participating in a coding contest. Now, let's say you have a problem where you need to shift the element of nth index of an array to its right for m times. Doing this work using a loop can make it complex, time-consuming, and performance-inefficient. So Java Collections not only saves you time, but the data structures and algorithms involved are highly optimized. This means they work really efficiently.&lt;/p&gt;

&lt;h3&gt;
  
  
  Collections Hierarchy
&lt;/h3&gt;

&lt;p&gt;The Java Collections Framework features a structured hierarchy that facilitates a quick understanding of the relationships between classes and interfaces.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4x338gi5q7p1gut4wze.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4x338gi5q7p1gut4wze.png" alt="Collection Hirarchy"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Collections Methods
&lt;/h3&gt;

&lt;p&gt;The Java Collections Framework provides a wide range of methods to manipulate and work with collections of objects.&lt;/p&gt;

&lt;p&gt;Here is some methods are listed below:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Return Type&lt;/th&gt;
&lt;th&gt;Parameter&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;add(E e)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;E e&lt;/td&gt;
&lt;td&gt;Adds an element to the collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;addAll(Collection&amp;lt;? extends E&amp;gt; c)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;Collection&amp;lt;? extends E&amp;gt; c&lt;/td&gt;
&lt;td&gt;Adds all elements from another collection to the current collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove(Object o)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;Object o&lt;/td&gt;
&lt;td&gt;Removes the first occurrence of the specified element from the collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;removeAll(Collection&amp;lt;?&amp;gt; c)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;Collection&amp;lt;?&amp;gt; c&lt;/td&gt;
&lt;td&gt;Removes all elements in the current collection that are also in another collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;size()&lt;/td&gt;
&lt;td&gt;int&lt;/td&gt;
&lt;td&gt;N/A&lt;/td&gt;
&lt;td&gt;Returns the number of elements in the collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;iterator()&lt;/td&gt;
&lt;td&gt;Iterator&lt;/td&gt;
&lt;td&gt;N/A&lt;/td&gt;
&lt;td&gt;Returns an iterator to iterate through the elements.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;isEmpty()&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;N/A&lt;/td&gt;
&lt;td&gt;Checks if the collection is empty.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;contains(Object o)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;Object o&lt;/td&gt;
&lt;td&gt;Checks if the collection contains a specified element.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;containsAll(Collection&amp;lt;?&amp;gt; c)&lt;/td&gt;
&lt;td&gt;boolean&lt;/td&gt;
&lt;td&gt;Collection&amp;lt;?&amp;gt; c&lt;/td&gt;
&lt;td&gt;Checks if the collection contains all elements from another collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;clear()&lt;/td&gt;
&lt;td&gt;void&lt;/td&gt;
&lt;td&gt;N/A&lt;/td&gt;
&lt;td&gt;Removes all elements from the collection.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Now we will see one by one every Interfaces.&lt;/p&gt;

&lt;h3&gt;
  
  
  Iterator Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;An iterator in Java is an interface that provides a way to access elements of a collection (like lists, sets, or maps) one at a time, without exposing the underlying details of the collection's structure. It allows you to traverse through the elements in a collection sequentially in forward direction only.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It has some important methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;&lt;strong&gt;hasNext()&lt;/strong&gt;&lt;/em&gt;: Checks if there are more elements to iterate over and returns a boolean value. &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;&lt;strong&gt;next()&lt;/strong&gt;&lt;/em&gt;: Returns the next element in the collection.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;remove()&lt;/em&gt;&lt;/strong&gt;: Removes the last element returned by &lt;code&gt;next()&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is a small program to demostrate use of Iterator&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;


&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Iterator&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;IteratorExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create an ArrayList to store student names&lt;/span&gt;
        &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;studentList&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add student names to the ArrayList&lt;/span&gt;
        &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Aman"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Virat"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Rohit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Jasprit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Create an iterator to go through the student names&lt;/span&gt;
        &lt;span class="nc"&gt;Iterator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;iterator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Use a while loop to iterate through the ArrayList&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;hasNext&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Get the next student name from the iterator&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;studentName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

            &lt;span class="c1"&gt;// Check if the student's name is "Jasprit"&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;studentName&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Jasprit"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// If it is "Jasprit," remove this student from the list&lt;/span&gt;
                &lt;span class="n"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
                &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Removed student: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;studentName&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Print the current student name to the console&lt;/span&gt;
                &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Student Name: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;studentName&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the updated list after removing "Jasprit"&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Updated Student List: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;studentList&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  List Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The List interface represents an ordered collection of elements. It allows duplicate elements and provides methods to access, insert, update, and remove elements at specific positions within the list.The classes ArrayList, LinkedList, Vector, and Stack implements the List Interface.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here is some common methods used in list interface :&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;add(E element)&lt;/td&gt;
&lt;td&gt;Appends the specified element to the end.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;add(int index, E element)&lt;/td&gt;
&lt;td&gt;Inserts the element at the specified position.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;get(int index)&lt;/td&gt;
&lt;td&gt;Returns the element at the specified position.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;set(int index, E element)&lt;/td&gt;
&lt;td&gt;Replaces the element at the specified position.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove(int index)&lt;/td&gt;
&lt;td&gt;Removes the element at the specified position.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;indexOf(Object o)&lt;/td&gt;
&lt;td&gt;Returns the index of the first occurrence.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;lastIndexOf(Object o)&lt;/td&gt;
&lt;td&gt;Returns the index of the last occurrence.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;subList(int from, int to)&lt;/td&gt;
&lt;td&gt;Returns a view of a portion of the list.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  ArrayList
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;An ArrayList in Java is a dynamic and ordered collection that can grow or shrink in size as needed. It is used to store and manage a list of elements. ArrayList allows for easy insertion, retrieval, and removal of elements, making it a versatile data structure for working with collections of data in Java programs. It provides the benefits of an array with the added flexibility of automatic resizing, making it a popular choice for many programming tasks.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd1temmxhp98n2uiot3ci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd1temmxhp98n2uiot3ci.png" alt="ArrayList"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Think of an ArrayList in Java like having a list of items you need for a trip – you can add more stuff as you remember, remove things if you change your mind, and easily find an item by just knowing its place in the list. So, an ArrayList is like your trusty bag for storing and managing a bunch of items, and it's super handy when you're working with lots of data in your Java programs.&lt;/p&gt;

&lt;p&gt;Here is a program to demonstrate ArrayList in Java:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Iterator&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.List&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ArrayListExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create an ArrayList of integers&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add elements to the list&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Access elements by index&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;secondNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Accessing the second element (20)&lt;/span&gt;

        &lt;span class="c1"&gt;// Update an element&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;set&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Replacing the first element (10) with 15&lt;/span&gt;

        &lt;span class="c1"&gt;// Remove an element&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Removing the third element (30)&lt;/span&gt;

        &lt;span class="c1"&gt;// Check if an element is in the list&lt;/span&gt;
        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;containsTwenty&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;contains&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// false&lt;/span&gt;

        &lt;span class="c1"&gt;// Returns the size of the list&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Size is now 2&lt;/span&gt;

        &lt;span class="c1"&gt;// Create an iterator&lt;/span&gt;
        &lt;span class="nc"&gt;Iterator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;iterator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the elements of the list &lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;hasNext&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;iterator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  LinkedList
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A Linked List is a linear data structure in Java that consists of a sequence of elements, where each element points to the next one in the sequence. It's made up of nodes, where each node holds both data and a reference (or link) to the next node in the list. Unlike an array, a Linked List can efficiently insert or remove elements at any position in the list, making it a flexible choice for certain data manipulation tasks.Linked Lists are often used when dynamic data storage and efficient insertions and deletions are required in Java programs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F90wvil8ytvpdw8382zhw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F90wvil8ytvpdw8382zhw.png" alt="Linked List"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagine a train with multiple compartments, each connected to the next through a small door. These compartments can represent a real-life example of a linked list. Each compartment (node) holds passengers (data) and has a door (pointer) that connects it to the next compartment. Passengers can easily enter or leave any compartment, and the train conductor can add or remove compartments when needed. This linked structure allows for efficient operations, such as adding a new compartment in the middle of the train or removing a specific compartment, making it a useful concept for tasks that involve dynamic data management, like a train ride with ever-changing passenger counts.&lt;/p&gt;

&lt;p&gt;Here is a program to demonstrate LinkedList:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;


&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Scanner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Define a Node class to represent elements in the linked list&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;    &lt;span class="c1"&gt;// Data stored in the node&lt;/span&gt;
    &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// Reference to the next node&lt;/span&gt;

    &lt;span class="c1"&gt;// Constructor to initialize a node with data&lt;/span&gt;
    &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Initially, the next node is set to null&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedListExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Function to insert a new node at the end of the linked list&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// If the linked list is empty, create a new node and set it as the head&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Traverse the list to find the last node&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a new node with the given data and add it to the end of the list&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Function to delete a node with the specified data from the linked list&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// If the linked list is empty, nothing to delete&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;data&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// If the head node contains the data, update the head to the next node&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;data&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Traverse the list to find the node to be deleted&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Update the next reference to skip the node to be deleted&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;display&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Function to display the elements of the linked list&lt;/span&gt;
        &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Traverse the list and print each element&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;data&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;" -&amp;gt; "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"null"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Scanner&lt;/span&gt; &lt;span class="n"&gt;scanner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Scanner&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;in&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;Node&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Initialize the linked list as empty&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Display menu options&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Linked List Operations:"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1. Insert"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"2. Delete"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"3. Display"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"4. Quit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Enter your choice: "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;choice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;nextInt&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

            &lt;span class="k"&gt;switch&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;choice&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;// Insert operation&lt;/span&gt;
                    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Enter element to insert: "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;insertData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;nextInt&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
                    &lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;insertData&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
                &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;// Delete operation&lt;/span&gt;
                    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Enter element to delete: "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;deleteData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;nextInt&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
                    &lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;delete&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;deleteData&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
                &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;// Display operation&lt;/span&gt;
                    &lt;span class="n"&gt;display&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
                &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;// Exit the program&lt;/span&gt;
                    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Exiting program."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                    &lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;close&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
                &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;// Invalid choice&lt;/span&gt;
                    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Invalid choice. Try again."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Vector
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A Vector in Java is a dynamic, resizable array-like data structure.It's similar to an ArrayList but is synchronized, which means it is thread-safe. Vectors can grow or shrink in size as needed, making them suitable for situations where the size of the collection may change dynamically. They are primarily used when you need a collection that can be accessed by multiple threads without the risk of data corruption.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbq7inl1xb506ce3r82k3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbq7inl1xb506ce3r82k3.png" alt="Vector"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Think of a Vector like a line of people waiting for their turn to do something. People can join the line at the end, and others can leave from the front. The Vector keeps everyone in an orderly queue and makes sure there are no clashes if multiple people try to join or leave at the same time. It's like a well-organized waiting line, ensuring fairness and order.&lt;/p&gt;

&lt;p&gt;Here is a program to demonstrate Vector:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;


&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Vector&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VectorExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Create a Vector to store integers&lt;/span&gt;
        &lt;span class="nc"&gt;Vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add elements to the Vector&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Access elements by index&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;secondNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Accessing the second element (20)&lt;/span&gt;

        &lt;span class="c1"&gt;// Update an element&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;set&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Replacing the first element (10) with 15&lt;/span&gt;

        &lt;span class="c1"&gt;// Remove an element&lt;/span&gt;
        &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Removing the third element (30)&lt;/span&gt;

        &lt;span class="c1"&gt;// Check if an element is in the Vector&lt;/span&gt;
        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;containsTwenty&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;contains&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// true&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the size of the Vector&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Size is now 2&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the elements of the Vector&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Stack
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A stack in Java is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It is the subclass of Vector and operates like a collection of items where you can only add or remove elements from the top, similar to a stack of plates. Elements are added to the top of the stack and removed from the top as well. This means that the last element added to the stack is the first one to be removed. Stacks are often used for tasks that require keeping track of the order of elements, such as managing function calls in recursion, undo functionality in applications, or browser history navigation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6p7up2ouue6b33a0j8g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6p7up2ouue6b33a0j8g.png" alt="Stack"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Think of a stack like a stack of trays in a cafeteria. You add trays to the top, and when someone wants a tray, they take the one from the top. It's a "Last-In-First-Out" (LIFO) system. In programming, it's similar; you add and remove items from the top of the stack, often used for tracking function calls, undo operations, or backtracking in algorithms, ensuring the last item added is the first to be processed or removed.&lt;/p&gt;

&lt;p&gt;Here's a simple Java program that demonstrates the basic operations of a stack (push, pop, and peek):&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Stack&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;StackExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Push elements onto the stack&lt;/span&gt;
        &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;push&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Apple"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;push&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Banana"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;push&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Cherry"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the stack&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Stack: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Pop an element from the stack&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;poppedElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;pop&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Popped Element: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;poppedElement&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Updated Stack: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Peek at the top element without removing it&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;topElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;peek&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Top Element: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;topElement&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Stack after Peek: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we will look into Queue Interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  Queue Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The Queue interface in Java represents a collection that holds elements in a linear order and allows adding elements at one end (enqueue) and removing elements from the other end (dequeue). It follows the "first-in-first-out" (FIFO) principle, similar to a real-world queue. Queues are often used for tasks like managing tasks in a printer queue or processing tasks in a concurrent system.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5p6q9i2r7ty7np4kca8v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5p6q9i2r7ty7np4kca8v.png" alt="Queue Interface"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  PriorityQueue Class
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The PriorityQueue class in Java is an implementation of the Queue interface that provides a priority-based ordering of elements. Elements in a PriorityQueue are ordered based on their natural order or according to a specified comparator. The element with the highest priority (according to the defined order) is always at the front and will be the first to be removed when dequeued. This makes PriorityQueue suitable for tasks like task scheduling, job processing, or managing elements with priorities.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ezh0qvifyub2827ncp0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ezh0qvifyub2827ncp0.png" alt="PriorityQueue"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's a brief example of using a PriorityQueue with integers:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PriorityQueueExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;priorityQueue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Enqueue elements with different priorities&lt;/span&gt;
        &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Print the priority queue&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Priority Queue: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Dequeue elements (highest priority first)&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;dequeuedElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Dequeued Element: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dequeuedElement&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Updated Priority Queue: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;priorityQueue&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example, we create a PriorityQueue of integers, enqueue elements with varying priorities, and then dequeue elements. The PriorityQueue automatically orders elements in ascending order by default (lowest value first). &lt;/p&gt;

&lt;h3&gt;
  
  
  Deque Interface
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The Deque (pronounced as "deck") interface in Java stands for "Double Ended Queue." It is a linear collection that supports adding and removing elements from both ends, i.e., both the front and the rear. A Deque interface extends the Queue interface, adding methods for operations at both ends of the queue, making it versatile for various data manipulation scenarios.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can use a Deque in situations where you need to efficiently insert or remove elements from the front and rear of a collection, such as implementing stacks, queues, or double-ended queues. Java provides several implementations of the Deque interface, including ArrayDeque and LinkedList.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2orusxrmflwzj6ju1tfv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2orusxrmflwzj6ju1tfv.png" alt="Deque"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  ArrayDeque
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;An ArrayDeque in Java is a double-ended queue (Deque) implemented as a resizable array. It allows you to add and remove elements from both ends efficiently, making it a versatile choice for various data structure operations. Unlike a traditional array, an ArrayDeque can dynamically resize itself to accommodate elements as they are added. This data structure is often used in scenarios where you need a queue or stack-like behavior, and it provides constant time (O(1)) performance for basic operations like adding and removing elements from both ends.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here's a brief example of using a ArrayDeque:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.ArrayDeque&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Deque&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DoubleEndedQueueExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Deque&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;printerQueue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayDeque&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// Add print jobs to the rear of the queue&lt;/span&gt;
        &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Document1.pdf"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Rear&lt;/span&gt;
        &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Document2.pdf"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Document3.pdf"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Print jobs are processed from the front of the queue&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;currentJob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Front&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Printing: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;currentJob&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Add an urgent print job to the front of the queue&lt;/span&gt;
        &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offerFirst&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"UrgentDocument.pdf"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Front&lt;/span&gt;

        &lt;span class="c1"&gt;// Print remaining jobs&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(!&lt;/span&gt;&lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;currentJob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;printerQueue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Printing: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;currentJob&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example, we use an ArrayDeque as a Deque to manage a double-ended queue for print jobs. We add jobs to the rear using offer() and to the front using offerFirst(). Print jobs are processed from the front using poll(). This demonstrates the versatility of the Deque interface for handling data from both ends.&lt;/p&gt;

&lt;p&gt;In this blog, we've explored the foundational elements of the Java Collections Framework, focusing on the List and Queue interfaces. We've seen how this powerful framework simplifies data management by providing a wide range of ready-made data structures and algorithms. The List interface allows us to work with ordered collections, while the Queue interface is ideal for managing items in a First-In-First-Out (FIFO) manner.&lt;/p&gt;

&lt;p&gt;Stay tuned for our next blog, where we'll dive deeper into other aspects of the Java Collections Framework, expanding your knowledge and empowering you to tackle a wider array of data management challenges.&lt;/p&gt;

&lt;p&gt;Do let me know if you have any queries in comments or you can DM me on &lt;a href="https://www.instagram.com/_alpha_golf/?hl=en" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Also you can see my blog on Building a Role-Based Access Control System with JWT in Spring Boot &lt;a href="https://dev.to/alphaaman/building-a-role-based-access-control-system-with-jwt-in-spring-boot-a7l"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;br&gt;
Happy Coding 😇&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>java</category>
      <category>learning</category>
    </item>
    <item>
      <title>Building a Role-Based Access Control System with JWT in Spring Boot</title>
      <dc:creator>Aman Gupta</dc:creator>
      <pubDate>Tue, 12 Sep 2023 11:30:11 +0000</pubDate>
      <link>https://dev.to/alphaaman/building-a-role-based-access-control-system-with-jwt-in-spring-boot-a7l</link>
      <guid>https://dev.to/alphaaman/building-a-role-based-access-control-system-with-jwt-in-spring-boot-a7l</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Welcome to my blog, where we'll embark on an exciting journey into the realm of web application security! If you're new to the world of Spring Boot or just beginning to explore the intricacies of authentication and authorization, you've come to the right place. In this inaugural article, I'm thrilled to share my take on a topic that resonates with developers of all levels: Building a Role-Based Access Control System with JWT in Spring Boot.&lt;/p&gt;

&lt;p&gt;In this blog series, we'll dive deep into the world of Spring Security and explore how JSON Web Tokens (JWT) can amplify its capabilities. I'll guide you step by step, from laying the foundation with a solid Spring Boot setup, all the way to implementing role-based access control using JWT tokens.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this blog, we'll cover the following topics:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating Different Roles and Assigning it to Users&lt;/li&gt;
&lt;li&gt;Registering Users and Administrators&lt;/li&gt;
&lt;li&gt;Generating JWT Tokens and Authentication&lt;/li&gt;
&lt;li&gt;Performing Role-Based Actions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Prerequisites&lt;/em&gt;&lt;br&gt;
Before we dive into the exciting world of building a role-based access control system with JWT in Spring Boot, let's ensure that you have the necessary tools and environment ready. Here's what you'll need to get started:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Java Development Kit (JDK)&lt;/code&gt;: Make sure you have a compatible version of JDK installed on your machine. Spring Boot usually works well with JDK 8 or higher.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Integrated Development Environment (IDE)&lt;/code&gt;: Choose an IDE that suits your preferences. IntelliJ IDEA and Eclipse are popular choices for Spring Boot development.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Maven or Gradle&lt;/code&gt;: You'll need either Maven or Gradle as a build tool to manage your project dependencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting up the Environment:&lt;/strong&gt;&lt;br&gt;
Spring Boot Project Initialization: Create a new Spring Boot project using either Spring Initializr web tool &lt;a href="https://start.spring.io/"&gt;here&lt;/a&gt; or your IDE's project creation wizard. &lt;/p&gt;

&lt;p&gt;Here is my setup you can follow:&lt;br&gt;
Project: Maven&lt;br&gt;
Spring Boot Version:2.7.3 (if not available then use 3.1.3 then change it later in pom.xml)&lt;br&gt;
Java Version:17&lt;br&gt;
Dependencies:&lt;br&gt;
1.Spring Data JPA&lt;br&gt;
2.Spring web&lt;br&gt;
3.Spring Security&lt;br&gt;
4.MySQL Driver&lt;br&gt;
5.JSON WEB TOKEN &lt;/p&gt;

&lt;p&gt;You will not find JSON web Token there you have to add it manually&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
     &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
     &amp;lt;artifactId&amp;gt;jjwt&amp;lt;/artifactId&amp;gt;
     &amp;lt;version&amp;gt;0.9.1&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is full pom.xml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&amp;gt;
    &amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;
    &amp;lt;parent&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-parent&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;2.7.3&amp;lt;/version&amp;gt;
        &amp;lt;relativePath/&amp;gt; &amp;lt;!-- lookup parent from repository --&amp;gt;
    &amp;lt;/parent&amp;gt;
    &amp;lt;groupId&amp;gt;com.alpha&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;alpha&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.0.1-SNAPSHOT&amp;lt;/version&amp;gt;
    &amp;lt;name&amp;gt;alpha&amp;lt;/name&amp;gt;
    &amp;lt;description&amp;gt;Demo project for Spring Boot Role based Authentication using JWT &amp;lt;/description&amp;gt;
    &amp;lt;properties&amp;gt;
        &amp;lt;java.version&amp;gt;17&amp;lt;/java.version&amp;gt;
    &amp;lt;/properties&amp;gt;
    &amp;lt;dependencies&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-security&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;mysql&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;mysql-connector-java&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-test&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;jjwt&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;0.9.1&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.security&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-security-test&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
    &amp;lt;/dependencies&amp;gt;
    &amp;lt;build&amp;gt;
        &amp;lt;plugins&amp;gt;
            &amp;lt;plugin&amp;gt;
                &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
                &amp;lt;artifactId&amp;gt;spring-boot-maven-plugin&amp;lt;/artifactId&amp;gt;
            &amp;lt;/plugin&amp;gt;
        &amp;lt;/plugins&amp;gt;
    &amp;lt;/build&amp;gt;
&amp;lt;/project&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;application.properties&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jwt.token.validity=18000
jwt.signing.key=YourSignInKey
jwt.authorities.key=roles
jwt.token.prefix=Bearer
jwt.header.string=Authorization

spring.datasource.url=jdbc:mysql://localhost:3306/yourdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.user.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
server.port=8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a configuration file for a Spring Boot application.  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first line sets the validity duration for JSON Web Tokens (JWT) to 18000 seconds (5 hours). &lt;/li&gt;
&lt;li&gt;The second line specifies the signing key to be used for generating and validating JWTs. &lt;/li&gt;
&lt;li&gt;The third line defines the key for extracting authorities/roles from a JWT. &lt;/li&gt;
&lt;li&gt;The fourth line sets the prefix for JWT tokens to "Bearer". &lt;/li&gt;
&lt;li&gt;The fifth line specifies the header string to be used for JWT tokens in HTTP requests. &lt;/li&gt;
&lt;li&gt;The next few lines configure the MySQL database connection for the application, including the URL, username, and password. &lt;/li&gt;
&lt;li&gt;The line &lt;code&gt;spring.jpa.show-sql=true&lt;/code&gt; enables the display of SQL statements executed by Hibernate. &lt;/li&gt;
&lt;li&gt;The line &lt;code&gt;spring.jpa.hibernate.ddl-auto=update&lt;/code&gt; configures Hibernate to automatically update the database schema based on the entity classes. &lt;/li&gt;
&lt;li&gt;The line &lt;code&gt;spring.user.datasource.driver-class-name=com.mysql.jdbc.Driver&lt;/code&gt; specifies the driver class for the user datasource. &lt;/li&gt;
&lt;li&gt;The line &lt;code&gt;spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect&lt;/code&gt; sets the Hibernate dialect for MySQL. &lt;/li&gt;
&lt;li&gt;The last line sets the server port to 8080. &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;"As you can see, here is the clear folder structure."&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src
└── main
    ├── java
    │   └── com
    │       └── alpha
    │           ├── config (Package)
    │           │   ├── JwtAuthenticationFilter.java
    │           │   ├── PasswordEncoder.java
    │           │   ├── TokenProvider.java
    │           │   ├── UnauthorizedEntryPoint.java
    │           │   └── WebSecurityConfig.java
    │           ├── controller (Package)
    │           │   └── UserController.java
    │           ├── dao (Package)
    │           │   ├── RoleDao.java
    │           │   └── UserDao.java
    │           ├── model (Package)
    │           │   ├── AuthToken.java
    │           │   ├── LoginUser.java
    │           │   ├── Role.java
    │           │   ├── User.java
    │           │   └── UserDto.java
    │           ├── service (Package)
    │           │   ├── impl
    │           │   │   ├── RoleServiceImpl.java
    │           │   │   └── UserServiceImpl.java
    │           │   ├── RoleService.java
    │           │   └── UserService.java
    │           └── AlphaApplication.java
    └── resources
        └── application.properties

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's get started!&lt;/p&gt;

&lt;p&gt;Now we will start with understanding the config package&lt;/p&gt;

&lt;p&gt;Spring Security is a powerful and highly customizable security framework provided by the Spring Framework for Java applications. Its primary purpose is to handle authentication, authorization, and various security aspects in web and enterprise applications. Spring Security is often used to secure web applications, RESTful APIs, and other components of a software system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authentication:&lt;/strong&gt;&lt;br&gt;
Authentication is the process of confirming the identity of a person or entity. It ensures that the person or entity is who they claim to be before granting access to something. It's like checking someone's ID before allowing them to enter a secure area.&lt;br&gt;
Imagine a professional cricket match. Before a player can step onto the field, they must prove their identity. They do this by showing their official player card with their name, photo, and a unique ID number. The match officials, like the umpires and team captains, examine the card to ensure it matches the player's appearance and is on the list of authorized players. Once confirmed, the player is authenticated and allowed to participate in the game.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authorization:&lt;/strong&gt;&lt;br&gt;
Authorization comes after authentication and determines what actions or resources an authenticated person or entity is allowed to access or perform. It specifies the level of access and control based on roles, permissions, or rules.&lt;/p&gt;

&lt;p&gt;Once a cricket player is authenticated and on the field, authorization kicks in. Each player has a specific role (e.g., batsman, bowler, fielder) with associated actions they can perform. For example, a bowler is authorized to bowl, a batsman is authorized to bat, and a wicketkeeper is authorized to keep wickets. The coach or captain may have special authorization to make strategic decisions during the match, like changing the batting order or field placements.&lt;/p&gt;

&lt;p&gt;lets move on to our config files one by one &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CORSFilter :&lt;/strong&gt; &lt;br&gt;
CORSFilter class is responsible for handling CORS-related settings in a web application. It intercepts incoming HTTP requests, adds the necessary CORS headers to the response, and then allows the request to continue processing using chain.doFilter(req, res). This filter helps control and secure how resources on the server are accessed by different origins in a web application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class implements the Filter interface, which is part of the Java Servlet API. Filters are used to perform actions on HTTP requests and responses as they pass through the application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
doFilter method :-
This method is required when implementing the Filter interface. It is called for each incoming HTTP request.
Inside this method, the code is responsible for adding necessary CORS headers to the HTTP response.
CORS headers are used to control and define the policy for cross-origin requests. They specify who can access the resources of a web page and what operations are permitted from different origins.
The code in this method sets various CORS headers, such as &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt;, &lt;code&gt;Access-Control-Allow-Methods&lt;/code&gt;, and others. These headers dictate which domains are allowed to access the resources, which HTTP methods are permitted, and other CORS-related policies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;init&lt;/code&gt; method is used for initialization tasks that the filter may need when it's first created.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;destroy&lt;/code&gt; method is called when the filter is being removed or shut down. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WebSecurityConfig&lt;/strong&gt; &lt;br&gt;
 This class is responsible for configuring security settings, such as authentication, authorization, and request filtering, in a Spring Boot web application. It also integrates custom components, like the JwtAuthenticationFilter, to handle specific security &lt;br&gt;
requirements. This configuration is a common setup for securing RESTful APIs or web applications using Spring Security.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private UnauthorizedEntryPoint unauthorizedEntryPoint;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder.encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/users/authenticate", "/users/register").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationFilter();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;@Configuration:&lt;/code&gt; Indicates that this class contains configuration settings for the application.&lt;br&gt;
&lt;code&gt;@EnableWebSecurity:&lt;/code&gt; Enables Spring Security features for the web application.&lt;br&gt;
&lt;code&gt;@EnableGlobalMethodSecurity(prePostEnabled = true):&lt;/code&gt; Enables method-level security annotations such as &lt;code&gt;@PreAuthorize&lt;/code&gt; and &lt;code&gt;@PostAuthorize&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;@Resource:&lt;/code&gt; Injects the &lt;code&gt;UserDetailsService&lt;/code&gt; bean, likely responsible for user-related operations.&lt;br&gt;
&lt;code&gt;@Autowired:&lt;/code&gt; Injects instances of &lt;code&gt;PasswordEncoder&lt;/code&gt; and &lt;code&gt;UnauthorizedEntryPoint&lt;/code&gt; beans, which are used for password hashing and handling unauthorized access, respectively.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;configure(AuthenticationManagerBuilder auth) Method:&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This method configures the authentication manager.&lt;/li&gt;
&lt;li&gt;It specifies that the &lt;code&gt;userDetailsService&lt;/code&gt; bean should be used for user authentication and sets the password encoder.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;configure(HttpSecurity http) Method:&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This method configures the HTTP security settings.&lt;/li&gt;
&lt;li&gt;It includes settings for CORS (Cross-Origin Resource Sharing), CSRF (Cross-Site Request Forgery), and URL permissions.&lt;/li&gt;
&lt;li&gt;It specifies which URLs are accessible without authentication ("/users/authenticate" and "/users/register") and requires authentication for all other requests.&lt;/li&gt;
&lt;li&gt;It sets an authentication entry point for handling unauthorized access and defines the session management policy as STATELESS.&lt;/li&gt;
&lt;li&gt;The addFilterBefore method adds a custom &lt;code&gt;JwtAuthenticationFilter&lt;/code&gt; before the &lt;code&gt;UsernamePasswordAuthenticationFilter&lt;/code&gt; to handle JWT (JSON Web Token) authentication.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;authenticationManagerBean() Method:&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This method declares an AuthenticationManager bean, which is used for user authentication.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;JwtAuthenticationFilter Bean:&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This method declares a bean for the JwtAuthenticationFilter, which is a custom filter used for JWT-based authentication.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;TokenProvider&lt;/strong&gt; &lt;br&gt;
This class is responsible for handling JWTs in a Spring Boot application's security flow. It can generate tokens, extract user information from tokens, validate tokens, and create authentication tokens for users based on the information stored in the JWTs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class TokenProvider implements Serializable {

    @Value("${jwt.token.validity}")
    public long TOKEN_VALIDITY;

    @Value("${jwt.signing.key}")
    public String SIGNING_KEY;

    @Value("${jwt.authorities.key}")
    public String AUTHORITIES_KEY;

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public &amp;lt;T&amp;gt; T getClaimFromToken(String token, Function&amp;lt;Claims, T&amp;gt; claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(SIGNING_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public String generateToken(Authentication authentication) {
         String authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));

        return Jwts.builder()
                .setSubject(authentication.getName())
                .claim(AUTHORITIES_KEY, authorities)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY*1000))
                .signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) &amp;amp;&amp;amp; !isTokenExpired(token));
    }

    UsernamePasswordAuthenticationToken getAuthenticationToken(final String token, final Authentication existingAuth, final UserDetails userDetails) {

        final JwtParser jwtParser = Jwts.parser().setSigningKey(SIGNING_KEY);

        final Jws&amp;lt;Claims&amp;gt; claimsJws = jwtParser.parseClaimsJws(token);

        final Claims claims = claimsJws.getBody();

        final Collection&amp;lt;? extends GrantedAuthority&amp;gt; authorities =
                Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());

        return new UsernamePasswordAuthenticationToken(userDetails, "", authorities);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;@Component:&lt;/code&gt; Marks this class as a Spring component, allowing it to be automatically scanned and registered as a bean in the Spring application context.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;getUsernameFromToken(String token): This method extracts the username (subject) from a JWT token.&lt;/li&gt;
&lt;li&gt;getExpirationDateFromToken(String token): Retrieves the expiration date from a JWT token.&lt;/li&gt;
&lt;li&gt;getClaimFromToken(String token, Function claimsResolver): A generic method to extract claims from a JWT token.&lt;/li&gt;
&lt;li&gt;getAllClaimsFromToken(String token): Parses and retrieves all claims (payload) from a JWT token.&lt;/li&gt;
&lt;li&gt;isTokenExpired(String token): Checks whether a JWT token has expired based on its expiration date.&lt;/li&gt;
&lt;li&gt;generateToken(Authentication authentication): Generates a new JWT token based on the provided Authentication object. It includes the subject (username), authorities, issuance time, and expiration time.&lt;/li&gt;
&lt;li&gt;validateToken(String token, UserDetails userDetails): Validates a JWT token against the provided UserDetails. It checks if the token's subject matches the user's username and if the token is not expired.&lt;/li&gt;
&lt;li&gt;getAuthenticationToken(final String token, final Authentication existingAuth, final UserDetails userDetails): This method parses a JWT token to create an Authentication object containing the user's authorities. It's used for authenticating users based on JWT tokens.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;JwtAuthenticationFilter&lt;/strong&gt; &lt;br&gt;
JwtAuthenticationFilter is responsible for intercepting incoming requests, extracting JWTs from request headers, and authenticating users based on the tokens. It ensures that authenticated users have their security context set, allowing them to access protected resources within the application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${jwt.header.string}")
    public String HEADER_STRING;

    @Value("${jwt.token.prefix}")
    public String TOKEN_PREFIX;

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenProvider jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String header = req.getHeader(HEADER_STRING);
        String username = null;
        String authToken = null;

        if (header != null &amp;amp;&amp;amp; header.startsWith(TOKEN_PREFIX)) {
            authToken = header.replace(TOKEN_PREFIX, "");

            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
            } catch (IllegalArgumentException e) {
                logger.error("Error occurred while retrieving Username from Token", e);
            } catch (ExpiredJwtException e) {
                logger.warn("The token has expired", e);
            } catch (SignatureException e) {
                logger.error("Authentication Failed. Invalid username or password.");
            }
        } else {
            logger.warn("Bearer string not found, ignoring the header");
        }

        if (username != null &amp;amp;&amp;amp; SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = jwtTokenUtil.getAuthenticationToken(authToken, SecurityContextHolder.getContext().getAuthentication(), userDetails);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
                logger.info("User authenticated: " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(req, res);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This class extends &lt;code&gt;OncePerRequestFilter&lt;/code&gt;, which ensures that this filter is applied only once per request.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;doFilterInternal&lt;/code&gt; Method:This method is the core of the filter and is called for each incoming HTTP request.&lt;/li&gt;
&lt;li&gt;The method first checks if a JWT is present in the request header and if it starts with the defined token prefix ("Bearer ").&lt;/li&gt;
&lt;li&gt;If a valid token is found, it attempts to extract the username from the token using the TokenProvider class.&lt;/li&gt;
&lt;li&gt;It catches exceptions for various token-related errors, such as token expiration (&lt;code&gt;ExpiredJwtException&lt;/code&gt;) and invalid signatures (&lt;code&gt;SignatureException&lt;/code&gt;), and logs them.&lt;/li&gt;
&lt;li&gt;If a valid username is obtained from the token and there is no existing authentication context, it loads the user details from the &lt;code&gt;UserDetailsService&lt;/code&gt; based on the username.&lt;/li&gt;
&lt;li&gt;It then validates the token against the user details using the &lt;code&gt;TokenProvider&lt;/code&gt;. If the token is valid, it creates an &lt;code&gt;UsernamePasswordAuthenticationToken&lt;/code&gt; containing the user details and sets the authentication details.&lt;/li&gt;
&lt;li&gt;Finally, it sets the authenticated user's security context using &lt;code&gt;SecurityContextHolder&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;After handling authentication, the filter continues the request processing by invoking &lt;code&gt;chain.doFilter(req, res)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;BCryptPasswordEncoder&lt;/strong&gt;&lt;br&gt;
This bean can be used throughout the application for securely hashing and verifying passwords, especially in the context of user authentication and security. It's a common practice to configure and manage password encoding components like this in Spring applications to enhance &lt;code&gt;security&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class PasswordEncoder {

    @Bean
    public BCryptPasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;BCryptPasswordEncoder&lt;/code&gt; is a popular password hashing library in the Spring Security framework. It's used to securely hash and verify passwords.&lt;/li&gt;
&lt;li&gt;In this configuration, the &lt;code&gt;BCryptPasswordEncoder&lt;/code&gt; bean is created and returned by the &lt;code&gt;encoder()&lt;/code&gt; method. This bean can then be injected into other parts of the application, such as Spring Security configurations, to handle password encoding and decoding.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;UnauthorizedEntryPoint&lt;/strong&gt;&lt;br&gt;
UnauthorizedEntryPoint class is responsible for handling unauthorized access to protected resources in a Spring Security-enabled application. When an unauthenticated user attempts to access a protected resource, this class sends an HTTP response with a status code of 401, indicating that the request lacks valid authentication. This response informs the client that they need to provide proper authentication credentials to access the resource.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;


@Component
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthenticated");
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class implements the &lt;code&gt;AuthenticationEntryPoint&lt;/code&gt; interface, which is part of Spring Security. The &lt;code&gt;AuthenticationEntryPoint&lt;/code&gt; interface is responsible for handling authentication-related exceptions, particularly unauthorized access.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;commence&lt;/code&gt; method is the main method of this class, and it's called when an authentication exception occurs during an HTTP request.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It takes three parameters:&lt;/p&gt;

&lt;p&gt;1.&lt;code&gt;HttpServletRequest request&lt;/code&gt;: Represents the incoming HTTP &lt;br&gt;
   request.&lt;br&gt;
 2.&lt;code&gt;HttpServletResponse response&lt;/code&gt;: Represents the HTTP response &lt;br&gt;
   that will be sent back to the client.&lt;br&gt;
 3.&lt;code&gt;AuthenticationException authException&lt;/code&gt;: Represents the &lt;br&gt;
   authentication exception that occurred, typically due to &lt;br&gt;
   unauthorized access.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In this method, it sends an HTTP response with a status code of &lt;code&gt;401 Unauthorized&lt;/code&gt; and a message of "Unauthenticated." This is a standard response for indicating that the request lacks valid authentication credentials or authorization.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;okay lets start with our model classes&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User&lt;/strong&gt;&lt;br&gt;
The User class represents a user entity with attributes like username, password, email, phone, name, and roles. It also defines a many-to-many relationship with the Role entity, allowing users to have multiple roles.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.model;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import java.util.Set;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;

    @Column
    private String username;

    @Column
    @JsonIgnore
    private String password;

    @Column
    private String email;

    @Column
    private String phone;

    @Column
    private String name;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "USER_ROLES",
            joinColumns = {
            @JoinColumn(name = "USER_ID")
            },
            inverseJoinColumns = {
            @JoinColumn(name = "ROLE_ID") })
    private Set&amp;lt;Role&amp;gt; roles;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set&amp;lt;Role&amp;gt; getRoles() {
        return roles;
    }

    public void setRoles(Set&amp;lt;Role&amp;gt; roles) {
        this.roles = roles;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This defines a &lt;code&gt;many-to-many&lt;/code&gt; relationship between the User entity and the Role entity. Users can have multiple roles, and roles can be associated with multiple users.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@ManyToMany&lt;/code&gt; annotation indicates a many-to-many relationship.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;fetch = FetchType.EAGER&lt;/code&gt; attribute specifies that roles should be eagerly fetched when loading a user.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;cascade = CascadeType.ALL&lt;/code&gt; attribute specifies that if operations like persist, merge, remove, etc., are performed on a User &lt;code&gt;entity&lt;/code&gt;, the same operations should be cascaded to its associated Role entities.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@JoinTable&lt;/code&gt; annotation is used to define the name of the join table that holds the relationship between users and roles. It specifies the columns used for joining the tables.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Role&lt;/strong&gt;&lt;br&gt;
the Role class represents a user role entity with attributes like name and description. It is designed to be persisted in a database table and can be associated with users through a many-to-many relationship, as indicated by the User entity's relationship mapping that references Role.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.model;

import javax.persistence.*;

@Entity
public class Role {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;

    @Column
    private String name;

    @Column
    private String description;

    // Getter for id
    public long getId() {
        return id;
    }

    // Setter for id
    public void setId(long id) {
        this.id = id;
    }

    // Getter for name
    public String getName() {
        return name;
    }

    // Setter for name
    public void setName(String name) {
        this.name = name;
    }

    // Getter for description
    public String getDescription() {
        return description;
    }

    // Setter for description
    public void setDescription(String description) {
        this.description = description;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the Role class represents a user role entity with attributes like name and description. It is designed to be persisted in a database table and can be associated with users through a many-to-many relationship, as indicated by the User entity's relationship mapping that references Role.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AuthToken&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.model;

/**
 * Represents an authentication token.
 */
public class AuthToken {
    private String token;

    /**
     * Constructs a new AuthToken object.
     */
    public AuthToken() {
    }

    /**
     * Constructs a new AuthToken object with the specified token.
     * 
     * @param token the authentication token
     */
    public AuthToken(String token) {
        this.token = token;
    }

    /**
     * Returns the authentication token.
     * 
     * @return the authentication token
     */
    public String getToken() {
        return token;
    }

    /**
     * Sets the authentication token.
     * 
     * @param token the authentication token to be set
     */
    public void setToken(String token) {
        this.token = token;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;LoginUser&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.model;

public class LoginUser {
    private String username;
    private String password;

    // Getters and Setters for username
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    // Getters and Setters for password
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;UserDto&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.model;

public class UserDto {

    private String username;
    private String password;
    private String email;
    private String phone;
    private String name;


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User getUserFromDto(){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setName(name);

        return user;
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;DAO&lt;/code&gt; is a Spring Data JPA repository interface typically used for performing CRUD (Create, Read, Update, Delete) operations on the  entity class. Let's break down its key components:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UserDao&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.dao;

import com.alpha.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends CrudRepository&amp;lt;User, Long&amp;gt; {
    User findByUsername(String username);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;RoleDao&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.dao;

import com.alpha.model.Role;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleDao extends CrudRepository&amp;lt;Role, Long&amp;gt; {
    Role findRoleByName(String name);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use &lt;code&gt;JPARepository&lt;/code&gt; also.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Service Layer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We will now proceed to define service interfaces for our User and Role services. These service interfaces will serve as blueprints for the actual service implementations and will encapsulate the core business logic.&lt;/p&gt;

&lt;p&gt;As a best practice, using interfaces for service definitions promotes separation of concerns and allows for easy switching of implementations, such as when using mocking frameworks for testing.&lt;br&gt;
&lt;code&gt;RoleService&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.service;

// Importing the Role model
import com.alpha.model.Role;

// Declaring the RoleService interface
public interface RoleService {
    // Method to find a Role by its name
    Role findByName(String name);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;UserService&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.service;

import com.alpha.model.User;
import com.alpha.model.UserDto;

import java.util.List;

public interface UserService {

    // Saves a user
    User save(UserDto user);

    // Retrieves all users
    List&amp;lt;User&amp;gt; findAll();

    // Retrieves a user by username
    User findOne(String username);

    User createEmployee(UserDto user);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we will implement our service logic &lt;br&gt;
&lt;strong&gt;RoleServiceImpl&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.service.impl;

import com.alpha.dao.RoleDao;
import com.alpha.model.Role;
import com.alpha.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value = "roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public Role findByName(String name) {
        // Find role by name using the roleDao
        Role role = roleDao.findRoleByName(name);
        return role;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;UserServiceImpl&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.alpha.dao.UserDao;
import com.alpha.model.Role;
import com.alpha.model.User;
import com.alpha.model.UserDto;
import com.alpha.service.RoleService;
import com.alpha.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service(value = "userService")
public class UserServiceImpl implements UserDetailsService, UserService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private BCryptPasswordEncoder bcryptEncoder;

    // Load user by username
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("Invalid username or password.");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority(user));
    }

    // Get user authorities
    private Set&amp;lt;SimpleGrantedAuthority&amp;gt; getAuthority(User user) {
        Set&amp;lt;SimpleGrantedAuthority&amp;gt; authorities = new HashSet&amp;lt;&amp;gt;();
        user.getRoles().forEach(role -&amp;gt; {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        });
        return authorities;
    }

    // Find all users
    public List&amp;lt;User&amp;gt; findAll() {
        List&amp;lt;User&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();
        userDao.findAll().iterator().forEachRemaining(list::add);
        return list;
    }

    // Find user by username
    @Override
    public User findOne(String username) {
        return userDao.findByUsername(username);
    }

    // Save user
    @Override
    public User save(UserDto user) {

        User nUser = user.getUserFromDto();
        nUser.setPassword(bcryptEncoder.encode(user.getPassword()));

        // Set default role as USER
        Role role = roleService.findByName("USER");
        Set&amp;lt;Role&amp;gt; roleSet = new HashSet&amp;lt;&amp;gt;();
        roleSet.add(role);

        // If email domain is admin.edu, add ADMIN role
        if(nUser.getEmail().split("@")[1].equals("admin.edu")){
            role = roleService.findByName("ADMIN");
            roleSet.add(role);
        }

        nUser.setRoles(roleSet);
        return userDao.save(nUser);
    }

    @Override
    public User createEmployee(UserDto user) {
        User nUser = user.getUserFromDto();
        nUser.setPassword(bcryptEncoder.encode(user.getPassword()));

        Role employeeRole = roleService.findByName("EMPLOYEE");
        Role customerRole = roleService.findByName("USER");

        Set&amp;lt;Role&amp;gt; roleSet = new HashSet&amp;lt;&amp;gt;();
        if (employeeRole != null) {
            roleSet.add(employeeRole);
        }
        if (customerRole != null) {
            roleSet.add(customerRole);
        }

        nUser.setRoles(roleSet);
        return userDao.save(nUser);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;lets create our controller class&lt;/p&gt;

&lt;p&gt;The initial step for a user is to complete the registration process. At a minimum, users are required to provide a username and password. By invoking the service method to save the user, this essential step is completed.&lt;/p&gt;

&lt;p&gt;To access the application's APIs securely, users must include a server-generated JWT (JSON Web Token). All the necessary groundwork for this has been laid out in our &lt;code&gt;TokenProvider&lt;/code&gt;. We utilize the &lt;code&gt;generateToken&lt;/code&gt; method and include the resulting token in the response, ensuring secure access to the APIs.&lt;br&gt;
&lt;strong&gt;UserController&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;UserController&lt;/code&gt; class handles user-related HTTP requests, including registration and authentication. It also demonstrates role-based access control for specific resources. The actual business logic for user operations is delegated to the UserService and &lt;code&gt;TokenProvider&lt;/code&gt; components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.alpha.controller;

import com.alpha.config.TokenProvider;
import com.alpha.model.AuthToken;
import com.alpha.model.LoginUser;
import com.alpha.model.User;
import com.alpha.model.UserDto;
import com.alpha.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenProvider jwtTokenUtil;

    @Autowired
    private UserService userService;

    /**
     * Generates a token for the given user credentials.
     *
     * @param loginUser The user's login credentials.
     * @return A response entity containing the generated token.
     * @throws AuthenticationException if authentication fails.
     */
    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity&amp;lt;?&amp;gt; generateToken(@RequestBody LoginUser loginUser) throws AuthenticationException {
        final Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginUser.getUsername(),
                        loginUser.getPassword()
                )
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        final String token = jwtTokenUtil.generateToken(authentication);
        return ResponseEntity.ok(new AuthToken(token));
    }

    /**
     * Saves a new user.
     *
     * @param user The user to be saved.
     * @return The saved user.
     */
    @RequestMapping(value="/register", method = RequestMethod.POST)
    public User saveUser(@RequestBody UserDto user){
        return userService.save(user);
    }

    /**
     * Returns a message that can only be accessed by users with the 'ADMIN' role.
     *
     * @return A message that can only be accessed by admins.
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value="/adminping", method = RequestMethod.GET)
    public String adminPing(){
        return "Only Admins Can Read This";
    }

    /**
     * Returns a message that can be accessed by any user.
     *
     * @return A message that can be accessed by any user.
     */
    @PreAuthorize("hasRole('USER')")
    @RequestMapping(value="/userping", method = RequestMethod.GET)
    public String userPing(){
        return "Any User Can Read This";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value="/create/employee", method = RequestMethod.POST)
    public User createEmployee(@RequestBody UserDto user){
        return userService.createEmployee(user);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value="/find/all", method = RequestMethod.GET)
    public List&amp;lt;User&amp;gt; getAllList(){
        return userService.findAll();
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value="/find/by/username", method = RequestMethod.GET)
    public User getAllList(@RequestParam String username){
        return userService.findOne(username);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These methods demonstrate role-based access control using Spring Security's &lt;code&gt;@PreAuthorize&lt;/code&gt; annotation. &lt;code&gt;adminPing&lt;/code&gt; can be accessed only by users with the 'ADMIN' role, while &lt;code&gt;userPing&lt;/code&gt; can be accessed by users with the 'USER' role.&lt;/p&gt;

&lt;p&gt;Before testing your apis you need to add some roles into your db&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO role (id, description, name) VALUES (1, 'Admin role', 'ADMIN');
INSERT INTO role (id, description, name) VALUES (2, 'Employee role', 'EMPLOYEE');
INSERT INTO role (id, description, name) VALUES (3, 'User role', 'USER');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally you can test your apis in postman&lt;br&gt;
I have created collection for &lt;a href="https://blue-flare-124005.postman.co/workspace/Spring-learning~a70a9e71-4aaf-4e10-aef0-f5ad15d16832/collection/27657088-4734fb4b-4e9c-44e7-a9dd-7985677b43c5?action=share&amp;amp;creator=27657088"&gt;postman&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is the whole code is in my &lt;a href="https://github.com/alphaaman/Spring-RBAC-Using-JWT"&gt;github&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you find any doubt feel free to contact me on  &lt;a href="https://www.instagram.com/_alpha_golf/?hl=en"&gt;Instagram&lt;/a&gt;&lt;br&gt;
Thanks for reading !&lt;br&gt;
Happy Coding !&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>api</category>
      <category>jwt</category>
      <category>rolebasedauthorization</category>
    </item>
  </channel>
</rss>
