diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..7377f72 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ['https://www.buymeacoffee.com/gauravkukade', 'https://www.paypal.com/paypalme/gauravkukade']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.gitignore b/.gitignore index 8312df0..a00a331 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ _site *.swp .sass-cache *~ +_drafts diff --git a/CNAME b/CNAME deleted file mode 100644 index 7d9346c..0000000 --- a/CNAME +++ /dev/null @@ -1 +0,0 @@ -coderolls.com \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 3c09ea9..7a391b4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ GEM remote: https://rubygems.org/ specs: - addressable (2.7.0) + addressable (2.8.0) public_suffix (>= 2.0.2, < 5.0) colorator (1.1.0) concurrent-ruby (1.1.6) @@ -53,7 +53,7 @@ GEM mercenary (0.3.6) pathutil (0.16.2) forwardable-extended (~> 2.6) - public_suffix (4.0.5) + public_suffix (4.0.6) rb-fsevent (0.10.4) rb-inotify (0.10.1) ffi (~> 1.0) @@ -65,6 +65,7 @@ GEM sass-listen (4.0.0) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) + wdm (0.1.1) PLATFORMS ruby @@ -79,6 +80,7 @@ DEPENDENCIES kramdown kramdown-parser-gfm rouge + wdm (>= 0.1.0) BUNDLED WITH - 2.2.11 + 2.4.21 diff --git a/README.md b/README.md index c2205b3..6841921 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,15 @@

-

codeRolls blog

+

coderolls blog

[Live Demo](https://coderolls.github.io) #### Copyright -Copyright (C) 2019 codeRolls, https://codeRolls.com +Copyright (C) 2024 coderolls, https://coderolls.com -CodeRolls is a blog about java programming language and related technologies. All post are copyright property of Guarva Kukade (@gauravkukade). If you want to read the blog post please visit coderolls.com +CodeRolls is a blog about java programming language and related technologies. All post are copyright property. If you want to read the blog post please visit coderolls.com -You can not copy these blogposts, you should right your own. πŸ™‚ - -Thank you! +You can not copy the blogpost. diff --git a/_config.yml b/_config.yml index 7263aea..3c00e95 100644 --- a/_config.yml +++ b/_config.yml @@ -6,6 +6,7 @@ logo: 'assets/images/logo.png' favicon: 'assets/images/logo.png' baseurl: '' google_analytics: 'UA-122932713-1' +google_analytics_measurement_id: 'G-5JMBR710R0' disqus: 'coderolls' mailchimp-list: 'https://coderolls.us4.list-manage.com/subscribe/post?u=91e4893f731db2a4807928752&id=76d82df79a' include: ["_pages"] @@ -14,13 +15,14 @@ permalink: /:title/ # Authors authors: gaurav: - name: Gaurav Kukade - display_name: Gaurav Kukade - gravatar: 4cb49146376b1ef2b46181f2388655ca - email: gaurav@coderolls.com - web: https://www.linkedin.com/in/gauravkukade/ - twitter: https://twitter.com/gdkukade - description: "Hi πŸ‘‹πŸΌ I'm Gaurav Kukade, a software developer. I write tutorials for Java programming language and related technologies." + name: coderolls Staff + display_name: coderolls Staff + avatar: 'assets/images/coderolls_display.svg' + # gravatar: 4cb49146376b1ef2b46181f2388655ca + email: hello@coderolls.com + web: https://coderolls.com + twitter: https://twitter.com/coderolls + description: "Hi πŸ‘‹πŸΌ, At coderolls we write tutorials about Java programming language and related technologies." # Plugins plugins: @@ -60,4 +62,7 @@ adsense-data-ad-slot: "1363087678" # Lazy Images ("enabled" or "disabled") lazyimages: "enabled" +# hide future post +future: false + exclude: [changelog.md, LICENSE.txt, README.md, Gemfile, Gemfile.lock] diff --git a/_drafts/2022-11-07-java-reverse-array.md b/_drafts/2022-11-07-java-reverse-array.md new file mode 100644 index 0000000..ef830c1 --- /dev/null +++ b/_drafts/2022-11-07-java-reverse-array.md @@ -0,0 +1,14 @@ +--- +layout: post +title: "How To Reverse an Array in Java?" +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In this tutorial, we will see how to reverse an array in Java?" +--- + + + +--- + +Please write your thoughts in the comment section below. \ No newline at end of file diff --git a/_includes/featuredbox.html b/_includes/featuredbox.html index 0586630..c2cdf50 100644 --- a/_includes/featuredbox.html +++ b/_includes/featuredbox.html @@ -3,6 +3,7 @@
+ +
@@ -44,7 +48,7 @@

{{ post.excerpt | strip_html | truncatewords:25 }}

{{ author.display_name }}
{% endif %} - +
diff --git a/_includes/mailchimp_newsletter_box.html b/_includes/mailchimp_newsletter_box.html new file mode 100644 index 0000000..43f599d --- /dev/null +++ b/_includes/mailchimp_newsletter_box.html @@ -0,0 +1,22 @@ +
+
+
+
Join Newsletter
+ Get the latest tutorials right in your inbox. We never spam! +
+
+
+
+
+ + + + + + +
+
+
+
+
+
\ No newline at end of file diff --git a/_includes/page-side-bar-coffee.html b/_includes/page-side-bar-coffee.html new file mode 100644 index 0000000..762c9af --- /dev/null +++ b/_includes/page-side-bar-coffee.html @@ -0,0 +1,14 @@ +
+
Buy me a coffee
+ +

Thank you for your support! Your donation helps me to maintain and improve coderolls.

+ + + + + +

+ +

🏑 Home

+ +
diff --git a/_includes/page-sidebar-coffee.html b/_includes/page-sidebar-coffee.html new file mode 100644 index 0000000..762c9af --- /dev/null +++ b/_includes/page-sidebar-coffee.html @@ -0,0 +1,14 @@ +
+
Buy me a coffee
+ +

Thank you for your support! Your donation helps me to maintain and improve coderolls.

+ + + + + +

+ +

🏑 Home

+ +
diff --git a/_includes/postbox.html b/_includes/postbox.html index 80160e2..0601707 100644 --- a/_includes/postbox.html +++ b/_includes/postbox.html @@ -40,7 +40,7 @@

{{ post.excerpt | strip_html | truncatewords:30 }}

{{ author.display_name }}
{% endif %} - +
@@ -48,4 +48,4 @@

{{ post.excerpt | strip_html | truncatewords:30 }}

- \ No newline at end of file + diff --git a/_includes/related_posts.html b/_includes/related_posts.html new file mode 100644 index 0000000..f3a5037 --- /dev/null +++ b/_includes/related_posts.html @@ -0,0 +1,37 @@ + diff --git a/_includes/related_posts_sidebar.html b/_includes/related_posts_sidebar.html new file mode 100644 index 0000000..d669cda --- /dev/null +++ b/_includes/related_posts_sidebar.html @@ -0,0 +1,38 @@ + diff --git a/_layouts/default.html b/_layouts/default.html index 0281446..2694357 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -22,6 +22,17 @@ {% endif %} + + + + + {% if jekyll.environment == 'production' %} @@ -40,7 +51,7 @@ @@ -56,7 +67,9 @@ {{ site.name }} - + +

{{ site.name }}

+ @@ -72,19 +85,20 @@ {% else %} - + {% include search-lunr.html %} @@ -104,14 +118,15 @@
- + @@ -124,7 +139,7 @@

{{ site.name }}

================================================== -->
- {{site.title}}   Never miss a story from us, subscribe to our newsletter + {{site.title}}   Never miss a tutorial from us, subscribe to our newsletter
@@ -170,15 +185,15 @@

Explore Copyright Β© {{ site.time | date: "%Y" }} {{ site.name }}    - About    + About    - Contact    + Contact    - Privacy    + Privacy    - Terms    + Terms    - +

@@ -208,6 +223,9 @@

Explore + + + @@ -227,5 +245,9 @@

Explore {% endif %} + + + + diff --git a/_layouts/post.html b/_layouts/post.html index 4c5e026..388834b 100644 --- a/_layouts/post.html +++ b/_layouts/post.html @@ -10,10 +10,16 @@
- -
+ + + +
+ {% include related_posts_sidebar.html %} +
{% assign author = site.authors[page.author] %} @@ -60,39 +66,41 @@

{{ page.title }}

{% if page.beforetoc %}

{{page.beforetoc}}

{% endif %} + +
+
+
+
+ +
+
+
+
+ {% include toc.html html=content %} +
+
+
+
+ {% endif %} {{content}} - + + + {% include related_posts.html %} + + {% if site.mailchimp-list %} -
-
-
-
Join Newsletter
- Get the latest news right in your inbox. We never spam! -
-
-
- -
- - - - - - -
- -
-
-
-
+ {% include mailchimp_newsletter_box.html %} {% endif %} - +
@@ -106,7 +114,7 @@
Join Newsletter

- + {% if page.last_modified_at %} (Updated: ) {% endif %} @@ -142,10 +150,10 @@

Join Newsletter
@@ -154,6 +162,7 @@
Join Newsletter
+

@@ -205,13 +206,13 @@ Since Apache Commons Lang library' is the most commonly used library, there are ``` -If you want to check if an array contains a value using the Apache commons Lang Library utility functions, you can do it as given below. +If you want to check if an array contains a value using the Apache Commons Lang Library utility functions, you can do it as given below. ```java import org.apache.commons.lang3.ArrayUtils; /** - * A java program to check if an array contains a value suing the + * A Java program to check if an array contains a value using the * Apache common lang library's ArrayUtils.contains() method * * @author Gaurav Kukade at coderolls.com @@ -221,36 +222,36 @@ public class ArrayUtilsExample { public static void main(String[] args) { - // check in primitive ( int[]) array + // search in primitive ( int[]) array int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int intToCheck = 8; boolean containsInt = ArrayUtils.contains(numbers, intToCheck); if(containsInt){ - System.out.println("The numbers array contians the value '"+intToCheck+"'."); + System.out.println("The numbers array contains the value '"+intToCheck+"'."); }else { - System.out.println("The numbers array does not contian the value '"+intToCheck+"'."); + System.out.println("The numbers array does not contain the value '"+intToCheck+"'."); } - // check in String array + // search in String array String[] names = {"gaurav", "shubham", "krishna", "mayur"}; String stringToCheck = "gaurav"; boolean containsString = ArrayUtils.contains(names, stringToCheck); if(containsString) { - System.out.println("String value '"+stringToCheck+"' is present in names array."); + System.out.println("String value '"+stringToCheck+"' is present in the names array."); }else { - System.out.println("String value '"+stringToCheck+"' is not present in names array."); + System.out.println("String value '"+stringToCheck+"' is not present in the names array."); } } } ``` Output: ``` -The numbers array contians the '8' value. -String value 'gaurav' is present in names array. +The numbers array contains the '8' value. +String value 'gaurav' is present in the names array. ``` Check the above code as [GitHub Gist](https://gist.github.com/gauravkukade/a93dd0faec3bebd75fa9833d5089d482) @@ -274,7 +275,7 @@ boolean stringPresentInArray = Arrays.stream(names).anyMatch("mayur"::equals);; ### 2. For Primitive Array -To check if a primitive array contains a value, we can use the simple for loop and add a equals condition in the loop. +To check if a primitive array contains a value, we can use the simple for loop and add an equal condition in the loop. ```java int[] numbers = {1, 2, 3, 4, 5, 6, 7}; @@ -287,7 +288,7 @@ for(int number: numbers) { } } ``` -From Java 8, we can use classes like `IntStream`, `DoubleStream` or `LongStream` to check whether an array contains `int`, `double` or `long` value respectively. +From Java 8, we can use classes like `IntStream`, `DoubleStream` or `LongStream` to check whether an array contains `int`, `double` or `long` values respectively. ```java int[] numbers = {1, 2, 3, 4, 5, 6, 7}; boolean contains = IntStream.of(numbers).anyMatch(x -> x == 3); @@ -306,22 +307,7 @@ boolean containsString = ArrayUtils.contains(names, "gaurav"); ``` I hope this article will help you to check if an array contains a value in Java. -If you have any other ways to check check if an array contains a value or element using java programming language, please comment below. +If you have any other ways to check if an array contains a value or element using java programming language, please comment below. You can check my YouTube channel [here](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w) - -### Related Articles - -- [How To Get Current Timestamp In Java?](https://coderolls.com/how-to-get-current-timestamps-in-java/) - -- [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) - -- [How to convert String to Integer in Java](https://coderolls.com/convert-string-to-int/) - -- [How To Convert StringBuilder To String In Java?](https://coderolls.com/convert-stringbuilder-to-string-in-java/) - -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) - diff --git a/_posts/array/2023-12-11-print-array-in-java.md b/_posts/array/2023-12-11-print-array-in-java.md new file mode 100644 index 0000000..eae30ba --- /dev/null +++ b/_posts/array/2023-12-11-print-array-in-java.md @@ -0,0 +1,169 @@ +--- +layout: post +title: "Java Program To Print An Array." +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In this tutorial, we will see how to print an array In Java." +--- + +In this tutorial, we will see how to print an array In Java. + +We can print an array using the following 3 ways + +1. Print an array using for loop +2. Print an array using `Arrays.toString()` +3. Print a multi-dimensional array using ` Arrays.deepToString()` +4. Print an array using Java 8 Streams + +## 1. Print an array using for loop + +Here, we are iterating over an array and printing each element. + +**Java Program** + +```java +/** + * Java program to print an array using for loop + * By coderolls.com + */ +public class PrintArray { + + public static void main(String[] args) { + int[] arr = {1, 5, 6, 9, 2, 6, 9, 6, 3, 2, 1}; + + System.out.println("Elements of the array are given below: "); + for (int i: arr) { + System.out.println(i); + } + } +} +``` + +**Output** + +``` +Elements of the array are given below: +1 +5 +6 +9 +2 +6 +9 +6 +3 +2 +1 +``` + +## 2. Print an array using `Arrays.toString()` + +We have a ready-made method to print an array in Java. + +The `Arrays.toString()` method expects an array to be printed as an input parameter and returns a string of array elements. + +Input param - array to be print + +Returns - array string + +**Java Program** + +```java +/** + * Java program to print an array using Arrays.toString() + * By coderolls.com + */ +public class PrintArray2 { + + public static void main(String[] args) { + int[] arr = {1, 5, 6, 9, 2, 6, 9, 6, 3, 2, 1}; + + System.out.println("Elements of the array are given below: "); + String srrString = Arrays.toString(arr); + System.out.println(srrString); + } +} +``` + +**Output** + +``` +Elements of the array are given below: +[1, 5, 6, 9, 2, 6, 9, 6, 3, 2, 1] +``` + + + +## 3. Print a multi-dimensional array using `Arrays.deepToString()` + +To print a multi-dimensional array we can use the ready-made `Arrays.deepToString()` method. + +**Java Program** + +{% raw %} + +```java +import java.util.Arrays; + +/** + * Java program to print a multi-dimensional array using Arrays.deepToString() + * By coderolls.com + */ +public class PrintArray3 { + + public static void main(String[] args) { + int[][] arr = {{1, 5, 8, 7}, {2, 6, 9, 6,}}; + + System.out.println("Elements of the multi-dimensional array are given below: "); + String srrString = Arrays.deepToString(arr); + System.out.println(srrString); + } +} +``` +{% endraw %} + +**Output** + +``` +Elements of the multi-dimensional array are given below: +[[1, 5, 8, 7], [2, 6, 9, 6]] +``` + +## 4. Print an array using Java 8 Streams + +In Java 8 Streams, we can use the `forEach()` method to print each element of an array. + +**Java Program** + +```java +import java.util.Arrays; + +/** + * Java program to print an array using Java 8 Streams forEach() method + * By coderolls.com + */ +public class PrintArray4 { + + public static void main(String[] args) { + int[] arr = {1, 5, 8, 7, 2, 6, 9, 6}; + + System.out.println("Elements of the array are given below: "); + Arrays.stream(arr).forEach(System.out::println); + } +} +``` + +**Output** + +``` +Elements of the array are given below: +1 +5 +8 +7 +2 +6 +9 +6 +``` diff --git a/_posts/collections/2022-08-05-arraylist-tutorials.md b/_posts/collections/2022-08-05-arraylist-tutorials.md new file mode 100644 index 0000000..11063ec --- /dev/null +++ b/_posts/collections/2022-08-05-arraylist-tutorials.md @@ -0,0 +1,41 @@ +--- +layout: post +title: "ArrayList Tutorials" +author: gaurav +categories: [Java Basics, Collections] +toc: false +description: "An index page for all ArrayList tutorials." +hidden: true +--- + +ArrayList is one of the most used collections in Java. Let's learn more about ArrayList using the series of tutorials listed below. + +## Introduction + +- [ArrayList In Java](https://coderolls.com/arraylist-in-java/) + +## Common Operations on ArrayList + +- [How To Add An Element To ArrayList In Java?](https://coderolls.com/add-element-in-arraylist/) +- [How To Change An Element In ArrayList?](https://coderolls.com/change-element-in-arraylist/) +- [How To Remove An Element From An ArrayList?](https://coderolls.com/remove-element-from-arraylist/) +- [Iterating the ArrayList In Java](https://coderolls.com/iterating-the-arraylist-in-java/) + +## ArrayList Methods + +- [ArrayList clear() method in Java](https://coderolls.com/arraylist-clear-method-in-java/) +- [ArrayList contains() method in Java](https://coderolls.com/arraylist-contains-method/) +- [How to convert ArrayList to Array In Java?](https://coderolls.com/convert-arraylist-to-array/) +- [ArrayList addAll() method in Java](https://coderolls.com/arraylist-addall-method-in-java/) +- [ArrayList get() method in Java](https://coderolls.com/arraylist-get-method/) +- [ArrayList removeRange() method in Java](https://coderolls.com/arraylist-removerange-method/) +- [ArrayList retainAll() method](https://coderolls.com/arraylist-retainall-method/) +- [subList() method of ArrayList class in java](https://coderolls.com/sublist-method-in-arraylist/) +- [ArrayList trimToSize() method](https://coderolls.com/arraylist-trimtosize-method/) +- [ArrayList indexOf() method](https://coderolls.com/arraylist-indexof-method/) +- [ArrayList lastIndexOf() method](https://coderolls.com/arraylist-lastindexof-method/) +- [ArrayList removeIf() method](https://coderolls.com/arraylist-removeif-method/) +- [ArrayList removeAll() method](https://coderolls.com/arraylist-removeall-method/) +- [ArrayList isEmpty() method in Java](https://coderolls.com/arraylist-isempty-method/) +- [ArrayList ensureCapacity() method in Java](https://coderolls.com/arraylist-ensurecapacity-method/) +- [ArrayList listIterator() method in Java](https://coderolls.com/arraylist-listiterator-method/) diff --git a/_posts/collections/2022-08-05-collections-tutorial.md b/_posts/collections/2022-08-05-collections-tutorial.md new file mode 100644 index 0000000..11043f2 --- /dev/null +++ b/_posts/collections/2022-08-05-collections-tutorial.md @@ -0,0 +1,13 @@ +--- +layout: post +title: "Collections Tutorial" +author: gaurav +categories: [Java Basics, Collections] +toc: false +description: "An index page for all collections tutorial." +hidden: true +--- + +- [ArrayList Tutorials](/arraylist-tutorials/) +- [LinkedList Tutorials](/linkedlist-tutorials/) + diff --git a/_posts/collections/2022-08-05-linkedlist-tutorials.md b/_posts/collections/2022-08-05-linkedlist-tutorials.md new file mode 100644 index 0000000..866302e --- /dev/null +++ b/_posts/collections/2022-08-05-linkedlist-tutorials.md @@ -0,0 +1,29 @@ +--- +layout: post +title: "LinkedList Tutorials" +author: gaurav +categories: [Java Basics, Collections] +toc: false +description: "An index page for all LinkedList tutorials." +hidden: true +--- + +LinkedList is one of the most used collections in Java. Let's learn more about ArrayList using the series of tutorials listed below. + +## Introduction + +- [LinkedList In Java](https://coderolls.com/linkedlist-in-java/) + +## LinkedList Methods + +- [How To Add Element At The Beginning Of LinkedList?](https://coderolls.com/linkedlist-addfirst-method/) +- [LinkedList addLast() Method](https://coderolls.com/linkedlist-addlast-method/) +- [How To Convert LinkedList To Array In Java?](https://coderolls.com/convert-linkedlist-to-array/) +- [How To Add Element To LinkedList?](https://coderolls.com/add-element-in-linkedlist/) +- [How To Remove Element From LinkedList?](https://coderolls.com/remove-element-from-linkedlist/) +- [How To Check If LinkedList Contains The ELement?](https://coderolls.com/check-if-linkedlist-contains-an-element/) +- [How To Get An Element From LinkedList?](https://coderolls.com/get-an-element-from-linkedlist/) +- [How To Get An Index of the Element Of LinkedList?](https://coderolls.com/get-an-index-of-element-of-linkedlist/) +- [How To Set An Element At A Particular Index In LinkedList?](https://coderolls.com/set-element-at-an-index-in-linkedlist/) +- [How To Iterate LinkedList In Java?](https://coderolls.com/iterate-linkedlist-in-java/) +- [LinkedList listIterator() method in Java](https://coderolls.com/linkedlist-listiterator/) diff --git a/_posts/collections/arraylist/2021-11-24-arraylist-in-java.md b/_posts/collections/arraylist/2021-11-24-arraylist-in-java.md new file mode 100644 index 0000000..5db6e5a --- /dev/null +++ b/_posts/collections/arraylist/2021-11-24-arraylist-in-java.md @@ -0,0 +1,221 @@ +--- +layout: post +title: "ArrayList In Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see ArrayList in Java. How to create an ArrayList? Its various types of constructors for creating an ArrayList object. Also, some important features with an example." +--- +In this article, we will see ArrayList in Java. How to create an ArrayList? Its various types of constructors for creating an ArrayList object. Also, some important features with an example. + +## Introduction + +ArrayList is a class in the Collections Framework. It is present in `java.util` package. + +The **ArrayList internally uses a dynamic array** for storing the elements. So ArrayList is more flexible than the array. + +The `ArrayList` class inherits the `AbstractList `class and it implements the `List` Interface. + +Unlike Array, we need not fix the length of ArrayList at the time of initialization. As we add or remove elements from the ArrayList, it can grow and shrink dynamically. + +The load factor for the ArrayList is 0.75F. + +The default initial capacity is 10. + +Load factor = 0.75 * 10 = 7 + +So when we try to add the 7th element to the ArrayList, it will create a new array double the size of the old array i.e. 20. Also, it will copy the old array in the new array and then add the element in a new array. + +## Constructors in the ArrayList + +To create an ArrayList, we need to create an object of the ArrayList class. To create an object ArrayList provides three types of constructor + +1. `ArrayList()` + +2. `ArrayList(Collection c)` + +3. `ArrayList(int initialCapacity)` + +Let's see all one by one + +### 1. ArrayList() + +This is a simple constructor to create an ArrayList object with a default capacity of ten (10). + +```java +ArrayList arrayList = new ArrayList(); +``` + +Above creating an empty array list object. The default initial capacity is 10. + +### 2. ArrayList(Collection c) + +This constructor constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. + +```java + +ArrayList anotherCollection = new ArrayList(); +anotherCollection.add("example"); + +// 2nd constructor example is the below line of code +ArrayList arrayList = new ArrayList(anotherCollection); +``` + +### 3. ArrayList(int initialCapacity) + +This constructor constructs an empty list with the specified initial capacity. + +```java +ArrayList arrayList = new ArrayList(20); +``` + +Above, I am creating an empty array list object with it's initial capacity as 20. + +**Note:** +```java +ArrayList arrayList = new ArrayList(20); +``` +In the above code the `` represents Generics and I am creating an `arrayList` object which will be storing String type of objects only. It will give us a compile-time error if we try to add any other type of object to the `arrayList`. + +By default, Collections are heterogeneous i.e. they can save all types of objects in one collection. By using Generics I am making it homogeneous i.e. it will store only specified types of objects in that particular collection. + + +## Methods in ArrayList + +{:class="table table-bordered"} +|Method | Description | +|:------| :---------- | +|[`add(E e)`](https://coderolls.com/add-element-in-arraylist/)|This method adds an element to the end of the list.| +|[`add(int index, E element)`](https://coderolls.com/add-element-in-arraylist/)|This method adds an element to the list at the specifed `index`.| +|[`addAll(Collection c)`](https://coderolls.com/arraylist-addall-method-in-java/)|This method adds the elements of the specified collection to the end of the ArrayList.| +|[`addAll(int index, Collection c)`](https://coderolls.com/arraylist-addall-method-in-java/)|This method adds the elements of the specified collection at the specified index `index`.| +|[`get(int index)`](https://coderolls.com/arraylist-get-method/)|This method is used to get the ArrayList element by it’s index `index`.| +|[`set(int index, E element)`](https://coderolls.com/change-element-in-arraylist/)|This method sets the sepecified element at the specifed `index`.| +|[`remove(Object o)`](https://coderolls.com/remove-element-from-arraylist/)|This method removes the specified object from the ArrayList.| +|[`remove(int index)`](https://coderolls.com/remove-element-from-arraylist/)|This method removes the object at specified index from the ArrayList.| +|[`removeIf(Predicate filter)`](http://coderolls.com/arraylist-removeif-method/)|This method removes all of the elements of the ArrayList that satisfy the given predicate.| +|[`removeAll(Collection c)`](http://coderolls.com/arraylist-removeall-method/)|This method removes from this list all of its elements that are contained in the specified collection.| +|[`iterator()`](https://coderolls.com/remove-element-from-arraylist/)|This method provides the Iterator to iterate over an ArrayList.| +|[`clear()`](http://coderolls.com/arraylist-clear-method-in-java/)|This method removes all the elements from the list and makes it empty.| +|[`isEmpty()`](http://coderolls.com/arraylist-isempty-method/)|This method returns true if this list contains no elements.| +|[`contains()`](http://coderolls.com/arraylist-contains-method/)|This method is used for checking if the specified element exists in the given list or not.| +|[`toArray()`](http://coderolls.com/convert-arraylist-to-array/)|This method returns an array containing all of the elements in this ArrayList in proper sequence.| +|[`toArray(T[] a)`](http://coderolls.com/convert-arraylist-to-array/)|This method returns `T []` i.e. An array of the specified type `T` can be returned.| +|[`removeRange(int fromIndex, int toIndex)`](http://coderolls.com/arraylist-removerange-method/)|This method is used for removing the range of elements from the subclasses of the ArrayList class. The [`removeRange(int fromIndex, int toIndex)` method](http://coderolls.com/arraylist-removerange-method/) is a protected method.| +|[`retainAll(Collection c)`](http://coderolls.com/arraylist-retainall-method/)|This method retains all the elements of the collection passed as a parameter in the list.| +|[`trimToSize()`](http://coderolls.com/arraylist-trimtosize-method/)|This method trims the capacity of this ArrayList instance to be the list's current size.| +|[`indexOf(Object o)`](http://coderolls.com/arraylist-indexof-method/)|This method returns the index of the first occurrences of the object specified. It returns -1 if the specified object `o` is not present in the list.| +|[`lastIndexOf(Object o)`](http://coderolls.com/arraylist-lastIndexof-method/)|This method returns the index of the last occurrences of the object specified. It returns -1 if the specified object `o` is not present in the list.| +|[`ensureCapacity()`](http://coderolls.com/arraylist-ensurecapacity-method/)|This method increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.| +|[`listIterator()`](http://coderolls.com/arraylist-listiterator-method/)|This method returns a *fail-fast* list iterator over the elements in this list (in proper sequence).| + + + +## Features + +### 1. ArrayList maintains the insertion order. + +I have given a simple Java program below that shows, ArrayList maintains the insertion order. + +```java +import java.util.ArrayList; + +/** + * A Java program showing an ArrayList maintains the insertion order. + * + * @author coderoll.com + * + */ +public class ArrayListExample { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + arrayList.add("Gaurav"); + arrayList.add("Shyam"); + arrayList.add("Saurav"); + arrayList.add("Samiksha"); + arrayList.add("Rina"); + + System.out.println(arrayList); + } +} +``` +**Output** +``` +[Gaurav, Shyam, Saurav, Samiksha, Rina] +``` + +#### Explanation + +1. In the above program, I have created an `arrayList` object with a type one constructor. So the default initial capacity of arrayList is 10. +2. I have added 5 string objects using the `add()` method one by one. +3. I have printed the `arrayList` object using a sysout statement. Here we can observe that all the strings are in the same order that they are inserted in the code. So we can say that the `ArrayList` maintains the insertion order. + +### 2. ArrayList allows the duplicate elements. + +I have given a simple Java program below that shows, that ArrayList allows duplicate elements. + +```java +import java.util.ArrayList; + +public class ArrayListDuplicate { + + public static void main(String[] args) { + ArrayList arrayList = new ArrayList(); + + arrayList.add("Gaurav"); + arrayList.add("Shyam"); + arrayList.add("Saurav"); + arrayList.add("Samiksha"); + arrayList.add("Rina"); + arrayList.add("Rina"); //adding a duplicate string object + + System.out.println(arrayList); + + } +} +``` +**Output** + +``` +[Gaurav, Shyam, Saurav, Samiksha, Rina, Rina] +``` +#### Explanation + +1. In the above program, I have created an `arrayList` object with a type one constructor. So the default initial capacity of arrayList is 10. +2. I have added 6 string objects using the `add()` method one by one. You can observe the 5th and 6th String objects are the same. i.e duplicate (`"Rina"` ) +3. On printing the `arrayList`, we can see the 5th as well as 6th String object (`"Rina"` ) on the console. That means `ArrayList` will allow the duplicate elements. + +## Common Operations on ArrayList + +### 1. Adding an element in the ArrayList + +When we create an ArrayList Object, we can add an element to the ArrayList using the `add(Object o)` method and `add(int index, Object o)` method. + +Read more and check example Java programs about adding an element to the ArrayList in this blog: [How To Add An Element To ArrayList In Java?](https://coderolls.com/add-element-in-arraylist/) + +### 2. Changing an element of the ArrayList + +When you create an ArrayList object and add elements to it, sometimes you need to change the element at a particular index. You can do it using the `set(int index, E element)`. + +Read more and check example Java programs about changing the element of ArrayList in this blogpost: [How To Change An Element In ArrayList?](https://coderolls.com/change-element-in-arraylist/) + +### 3. Removing an element of the ArrayList + +If you want to remove the element from the ArrayList, you can use the remove(Object o) method or remove(int index) method. + +Read more and check an example Java program about removing an element from the ArrayList on this blogpost: [How To Remove An Element From An ArrayList?](http://coderolls.com/remove-element-from-arraylist/) + +### 4. Iterating over an ArrayList + +There are multiple ways to iterate over an ArrayList. You can use the traditional for loop or for-each loop or Iterator. + +I have covered all the ways of iterating the ArrayList in Java with all the examples at [Iterating the ArrayList In Java](http://coderolls.com/iterating-the-arraylist-in-java/) + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-in-java). + +Let me know your thoughts or suggestions in the comment section below. diff --git a/_posts/collections/arraylist/2021-11-27-add-element-in-arraylist.md b/_posts/collections/arraylist/2021-11-27-add-element-in-arraylist.md new file mode 100644 index 0000000..92fba95 --- /dev/null +++ b/_posts/collections/arraylist/2021-11-27-add-element-in-arraylist.md @@ -0,0 +1,136 @@ +--- +layout: post +title: "How To Add An Element To ArrayList In Java?" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to add an element in ArrayList. Also, we will see how we can add an element at a particular index in ArrayList." +--- + +In this article, we will see how to add an element in [ArrayList](https://coderolls.com/arraylist-in-java/). Also, we will see how we can add an element at a particular index in ArrayList. + +## Introduction + +We can add an element to the end of [ArrayList](https://coderolls.com/arraylist-in-java/) using the `add(E e)` method. + +To add an element to a particular index, we can use the `add(int index, E element)` method. + +Let's see these two methods one by one. + +## 1. `add(E e)` + +The method signature for this method is given below. + +```java +public boolean add(E e) +``` + +This method appends the specified element `e` to the end of the list. + +This method returns `true` if the element is added to the list otherwise, it returns `false`. + +Let's see a Java program to add an element to the list using the above method. + +```java + +import java.util.ArrayList; + +/** + * A Java program to add an element to the list. + * + * The add(E e) method will add an element to + * the end of the ArrayList. + * + * @author coderolls.com + * + */ +public class ArrayListExample { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //adding elements to the arrayList + arrayList.add("Gaurav"); + arrayList.add("Shyam"); + + System.out.println(arrayList);// [Gaurav, Shyam] + + // adding an element to the arrayList + // element will be added to the end of the arrayList + arrayList.add("Saurav"); + + System.out.println(arrayList); // [Gaurav, Shyam, Saurav] + + } +} +``` +Output: +``` +[Gaurav, Shyam] +[Gaurav, Shyam, Saurav] +``` + +## 2. `add(int index, E element)` + +The method signature for this method is given below. + +```java +public boolean add(int index, E element) +``` + +This method adds the specified element `element` at the specified index `index`. + +This method has a return type as `void` so, it will not return anything. + +Below, we will see a Java program to add an element at the specified index in ArrayList. + +```java +import java.util.ArrayList; + +/** + * A Java program to add an element at the specific index. + * + * The add(int index, E element) method will add + * an element at the specified index in ArrayList. + * + * @author coderolls.com + * + */ +public class ArrayListAddExample { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //adding elements to the arrayList using the normal add method + arrayList.add("Gaurav"); + arrayList.add("Shyam"); + + System.out.println(arrayList);// [Gaurav, Shyam] + + // adding an element to the arrayList at index 1 + arrayList.add(1, "Saurav"); + + System.out.println(arrayList); // [Gaurav, Saurav, Shyam] + } +} +``` +Output: + +``` +[Gaurav, Shyam] +[Gaurav, Saurav, Shyam] +``` + +## Conclusion + +We can add an element to the [ArrayList](https://coderolls.com/arraylist-in-java/) using the `add()` method in two ways. +1. `add(E e)` - It will add an element to the end of the ArrayList +2. `add(int index, E element)`- This method will add an element to the specified index + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/add-element-in-arraylist). + +If you know of any other ways, you can write a comment below. diff --git a/_posts/collections/arraylist/2021-11-30-change-element-in-arraylist.md b/_posts/collections/arraylist/2021-11-30-change-element-in-arraylist.md new file mode 100644 index 0000000..a5b4057 --- /dev/null +++ b/_posts/collections/arraylist/2021-11-30-change-element-in-arraylist.md @@ -0,0 +1,89 @@ +--- +layout: post +title: "How To Change An Element In ArrayList?" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to change an element in ArrayList." +--- + +This article will show how to change an element in [ArrayList](https://coderolls.com/arraylist-in-java/). + +## Introduction + +In the previous tutorial, we have seen [how we can add an element to the ArrayList](https://coderolls.com/add-element-in-arraylist/). But, if we wish to change an element from the ArrayList, we can use the `set()` method. + +We know that `ArrayList` is an indexed collection. So we can access any particular element by its index and change it. + +## `set() ` method + +The `set()` method has a signature as `public E set(int index, E element)`. + +This method accepts the index as `int` and an element that needs to be set at that particular index. + +The `set()` method has a return type as `E` which means it will return an element. **The `set()` method returns the element previously at the specified position.** + +Below, we will see a Java program to change (set) an element in `ArrayList`. + +```java +package com.gaurav.ExProject.ArrayList; + +import java.util.ArrayList; + +/** + * A Java program to change an element at + * particular index in ArrayList. + * + * We can use 'public E set(int index, E element)' method + * to change an element. + * + * @author coderolls.com + * + */ +public class ArrayListSetExample { + + public static void main(String[] args) { + ArrayList arrayList = new ArrayList(); + + //adding elements to the arrayList using the normal add() method + arrayList.add("Gaurav"); + arrayList.add("Shyam"); + arrayList.add("Pradnya"); + + System.out.println(arrayList);// [Gaurav, Shyam, Pradnya] + + // change an element at index 1 + arrayList.set(1, "Saurav"); + + System.out.println(arrayList); // [Gaurav, Saurav, Pradnya] + } +} +``` +Output: +``` +[Gaurav, Shyam, Pradnya] +[Gaurav, Saurav, Pradnya] +``` + +### Explanation + +1. In the above program, I have added three strings (`"Gaurav"`, `"Shyam"`, `"Pradnya"`) to the `arrayList`. We can see this by printing the `arrayList`. +2. I want to change the element at index `1`. So, I have provided the index as `1`, and the new element i.e. String `"Saurav"` as arguments to the `set()` method. +3. On printing the `arrayList` again, we can see the change element at index `1`. + +## Conclusion + +So we can change the element in [ArrayList](https://coderolls.com/arraylist-in-java/) at a particular index by using the `set()` method. + +The set method signature is as follows +``` +public E set(int index, E element) +``` + +The `set()` returns the previously present element in the `ArrayList`. + +So, we have seen [how to add an element](https://coderolls.com/add-element-in-arraylist/) and [how to change an element in the ArrayList](https://coderolls.com/change-element-in-arraylist/), next we will see how we can [remove an element from ArrayList](https://coderolls.com/remove-element-from-arraylist/) in Java. + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/change-element-in-arraylist). diff --git a/_posts/collections/arraylist/2021-12-02-remove-element-from-arraylist.md b/_posts/collections/arraylist/2021-12-02-remove-element-from-arraylist.md new file mode 100644 index 0000000..a42e6dc --- /dev/null +++ b/_posts/collections/arraylist/2021-12-02-remove-element-from-arraylist.md @@ -0,0 +1,346 @@ +--- +layout: post +title: "How To Remove An Element From An ArrayList?" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to remove an element from an ArrayList." +--- +In this article, we will see how to remove an element from an [ArrayList In Java](https://coderolls.com/arraylist-in-java/). +## Introduction + +We have seen [how we can add an element to an ArrayList](http://coderolls.com/add-element-in-arraylist/) and [how we can change the elements of an ArrayList](https://coderolls.com/change-element-in-arraylist/), now we will see how we can remove an element from an ArrayList. + +To remove an element from an ArrayList, we use the `remove()` method. + +Using the ' Remove (Object o)` method, we can remove the specified object from an ArrayList. + +Using the `remove(int index)` method, we can remove the object at the specified index from an ArrayList. + +Let's see both methods one by one. + +## 1. Remove an element from an ArrayList using the `remove(Object o)` method + +The `remove(Object o)` method removes the first occurrences of the specified object from the ArrayList. + +If the specified object `o` is not present in the ArrayList, the ArrayList remains unchanged. + +The method signature is as `public boolean remove(Object o)` + +The `remove(Object o)` method has a return type as a `boolean`. It returns `true` if it found an occurrence of the specified object and if it removes. Otherwise, it returns `false`. + +We will see a Java program to remove an element from the ArrayList using the `remove(Object o)` method. + +### Example 1 + +```java +import java.util.ArrayList; + +/** + * A Java program to remove an element from ArrayList + * using the remove(Object o) method. + * + * @author coderolls.com + * + */ +public class ArrayListRemoveExample { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //adding elements to the ArrayList using the normal add() method + arrayList.add("Red"); + arrayList.add("Green"); + arrayList.add("Pink"); + + System.out.println("ArrayList before removing an element"+ arrayList); // ArrayList before removing an element[Red, Green, Pink] + + //Remove "Pink" from the ArrayList + arrayList.remove("Pink"); + + System.out.println("ArrayList after removing an element"+ arrayList);// ArrayList after removing an element[Red, Green] + } +} +``` +Output: +``` +ArrayList before removing an element[Red, Green, Pink] +ArrayList after removing an element[Red, Green] +``` +### Example 2 + +In the above example, we have removed the string object. In this example, we will take an employee object. The Employee.java will look like the given below + +```java +/** + * An employee class for ArrayList remove example + * @author coderolls.com + * + */ +public class Employee { + + private int id; + + private String name; + + private int salary; + + // a constructor will all the fields + public Employee(int id, String name, int salary) { + this.id = id; + this.name = name; + this.salary = salary; + } + + // getters and setters for the variables + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getSalary() { + return salary; + } + + public void setSalary(int salary) { + this.salary = salary; + } + + // Override to string method to print student objects + @Override + public String toString() { + return "{"+this.getId()+", "+ this.getName()+ ", "+this.getSalary()+"}"; + } +} + +``` + +Now, we will create an ArrayList of the above employee objects and try to remove them from the arraylist using `remove(Object o)`. + +```java +import java.util.ArrayList; +/** + * A Java program to remove an object from ArrayList + * using the remove(int index) method. + * + * @author coderolls.com + * + */ +public class ArrayListRemoveObjectExample { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //create Employee objects + Employee john = new Employee(100, "John Doe", 20000); + Employee nathasha = new Employee(101, "Natasha Putin", 28000); + Employee remo = new Employee(102, "Remo Smith", 40000); + + //adding employee objects to the arrayList using the normal add method + arrayList.add(john); + arrayList.add(nathasha); + arrayList.add(remo); + + System.out.println("ArrayList before removing an employee Object:\n"+ arrayList); + + //Remove object using the remo0ve(Object o) method + //Remove employee nathasha from the arrayList + arrayList.remove(nathasha); + + System.out.println("\nArrayList after removing an employee Object:\n"+ arrayList); + } +} +``` +Output: +``` +ArrayList before removing an employee Object: +[{100, John Doe, 20000}, {101, Natasha Putin, 28000}, {102, Remo Smith, 40000}] + +ArrayList after removing an employee Object: +[{100, John Doe, 20000}, {102, Remo Smith, 40000}] +``` + +## 2. Remove an element from an ArrayList using the `remove(int index)` method + +The `remove(int index)` removes an element at the specified position from the ArrayList. + +The method signature is as `public E remove(int index)` + +Once we remove an element from the ArrayList using the `remove(int index)` method, the remaining elements after the specified index get shifted left and its indices are updated. + +The return type is an `E`. It returns the element that was removed from the list. + +We will see a Java program to remove an element from the ArrayList by passing its index as an argument to the `remove(int index)` method. + +### Example 1 + +```java +import java.util.ArrayList; + +/** + * A Java program to remove an element from ArrayList + * using the remove(int index) method. + * + * @author coderolls.com + * + */ +public class ArrayListRemoveExample2 { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //adding elements to the arrayList using normal add method + arrayList.add("Apple"); + arrayList.add("Orange"); + arrayList.add("Guava"); + arrayList.add("Banana"); + + System.out.println("ArrayList before removing an element"+ arrayList); + // ArrayList before removing an element[Apple, Orange, Guava, Banana] + + //Remove the element at the specified index i.e. 2 + //Remove "Guava" from the arrayList + arrayList.remove(2); + + System.out.println("ArrayList after removing an element"+ arrayList); + // ArrayList after removing an element[Apple, Orange, Banana] + } +} +``` +Output: +``` +ArrayList before removing an element[Apple, Orange, Guava, Banana] +ArrayList after removing an element[Apple, Orange, Banana] +``` + +### Example 2 + +In the above example, we have removed the string object. In this example, we will take an employee object. The Employee.java will look like the given below + +```java +/** + * An employee class for ArrayList remove example + * @author coderolls.com + * + */ +public class Employee { + + private int id; + + private String name; + + private int salary; + + // a constructor will all the fields + public Employee(int id, String name, int salary) { + this.id = id; + this.name = name; + this.salary = salary; + } + + // getters and setters for the variables + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getSalary() { + return salary; + } + + public void setSalary(int salary) { + this.salary = salary; + } + + // Override to string method to print student objects + @Override + public String toString() { + return "{"+this.getId()+", "+ this.getName()+ ", "+this.getSalary()+"}"; + } +} + +``` + +Now, we will create an arraylist of the above employee objects and try to remove them from the arraylist using `remove(int index)`. +```java +import java.util.ArrayList; + +/** + * A Java program to remove an object from ArrayList + * using the remove(int index) method. + * + * @author coderolls.com + * + */ +public class ArrayListRemoveObjectExample2 { + + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList(); + + //create Employee objects + Employee john = new Employee(100, "John Doe", 20000); + Employee nathasha = new Employee(101, "Natasha Putin", 28000); + Employee remo = new Employee(102, "Remo Smith", 40000); + + //adding employee objects to the arrayList using the normal add method + arrayList.add(john); + arrayList.add(nathasha); + arrayList.add(remo); + + System.out.println("ArrayList before removing an employee Object:\n"+ arrayList); + + //Remove object using the remove(int index) method + //Remove employee nathasha from the arrayList, so pass Natasha's index + arrayList.remove(1); + + System.out.println("\nArrayList after removing an employee Object:\n"+ arrayList); + } +} +``` +Output: +``` +ArrayList before removing an employee Object: +[{100, John Doe, 20000}, {101, Natasha Putin, 28000}, {102, Remo Smith, 40000}] + +ArrayList after removing an employee Object: +[{100, John Doe, 20000}, {102, Remo Smith, 40000}] +``` + +## Conclusion + +We can remove an element from the ArrayList in two ways. + +1. `remove(Object o)` - we can remove the specified object from the ArrayList +2. `remove(int index)` - We can remove an element at the position (index) specified + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/remove-element-from-arraylist). + +If you know any other way, please comment below. diff --git a/_posts/collections/arraylist/2021-12-04-iterating-the-arraylist-in-java.md b/_posts/collections/arraylist/2021-12-04-iterating-the-arraylist-in-java.md new file mode 100644 index 0000000..a0a0373 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-04-iterating-the-arraylist-in-java.md @@ -0,0 +1,377 @@ +--- +layout: post +title: "Iterating the ArrayList In Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to iterate through an ArrayList in Java. We will see the various to iterate like for loop, Iterator Interface, For-Each method with Lambda expression etc" +--- +In this article, we will see how to iterate through an [ArrayList In Java](https://coderolls.com/arraylist-in-java/). We will see the various to iterate like for loop, Iterator Interface, For-Each method with Lambda expression etc + +## Introduction +ArrayList is a very common class from the Collections framework for storing elements. + +When we store objects in ArrayList, they preserve the insertion order. Also, ArrayList allows us to add duplicate elements too. + +As we use ArrayList to store and retrieve the objects, sometimes we need to iterate over them. And today, we will see how we can iterate through ArrayList in Java. + +There are multiple ways to iterate over the ArrayList. We will see the following ways +1. Iterating the ArrayList using basic for loop +2. Iterating the ArrayList using Enhanced For Loop i.e. For-each loop +3. Iterating the ArrayList using while loop +4. Iterating the ArrayList using Iterator +5. Iterating the ArrayList using Java 8 forEach() Method + +So let's see all the options one by one. + +## 1. Iterating the ArrayList using basic for loop + +We can write a simple for loop for the ArrayList and access the elements of the ArrayList using the get() method. + +I will write a simple java program to show how we can iterate through ArrayList using the basic for loop. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to iterate through ArrayList + * using the basic for loop. + * + * @author coderolls.com + * + */ +public class ArrayListIterateExample1 { + + public static void main (String[] args) { + + List list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Iterating through ArrayList using the basic for loop.......\n"); + + for(int i =0; i list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Iterating through ArrayList using enhanced for loop i.e. For-each loop.......\n"); + + for(String str:list){ + //we got an item 'str' in the loop + System.out.println("Object form the ArrayList is " + str); + } + } +} +``` + +Output: +``` +Iterating through ArrayList using enhanced for loop i.e. For-each loop....... + +The object from the ArrayList is Monday +The object from the ArrayList is Tuesday +The object from the ArrayList is Wednesday +The object from the ArrayList is Thursday +The object from the ArrayList is Friday +The object from the ArrayList is Saturday +The object from the ArrayList is Sunday +``` +### Explanation + +1. In the above Java program, I have created an empty ArrayList of String. +2. I have added a few String objects to the ArrayList. i.e `list` +3. I have written an enhanced for loop i.e. for each loop for the `list`. +4. Using the for-each loop, we can operate over each object of the `list`, as shown in the above program, we got `str` in the loop. +5. Finally, I have simply printed the `str` objects. + +## 3. Iterating the ArrayList using a while loop + +We can iterate over an ArrayList using the while loop. + +The program to iterate over an ArrayList using the while loop is given below. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to iterate through an ArrayList + * using a while loop. + * + * @author coderolls.com + * + */ +public class ArrayListIterateExample3 { + + public static void main (String[] args) { + + List list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Iterating through ArrayList using while loop.......\n"); + + int i=0; + // while loop condition will be true till i is less the the list size + while (list.size()>i) { + System.out.println("Object form the ArrayList at "+ i + " is " + list.get(i)); + i++; + } + } +} +``` +Output: + +``` +Iterating through ArrayList using while loop....... + +The object from the ArrayList at 0 is Monday +The Object from the ArrayList at 1 is Tuesday +The object from the ArrayList at 2 is Wednesday +The object from the ArrayList at 3 is Thursday +The object from the ArrayList at 4 is Friday +The object from the ArrayList at 5 is Saturday +The object from the ArrayList at 6 is Sunday +``` +### Explanation +1. In the above Java program, I have created an empty ArrayList of String. +2. I have added a few String objects to the ArrayList i.e `list` +3. Before starting the for loop, I have initialized a variable `i` with a value as `0`. +4. I have written a simple while to loop to check the condition for `i` is less than the size of the list i.e. `list.size()` +5. If the above condition is true, we will enter in the loop, and we can access the particular object of the list using the `get(int index)` method. +6. After accessing/operating on the object, we are incrementing the variable `i` by one i.e. `i++` +7. Once the value of `i` becomes greater than or equal to the list size, the condition will be false and we will not be able to enter in the loop. + +## 4. Iterating the ArrayList using Iterator + +Iterator is an interface in Java. We can use an Iterator to iterate over a collection. + +It is present in the `java.util` package. + +If we want to iterate over an ArrayList using an iterator, we should invoke the iterator() method on the ArrayList object to get the iterator reference as given below +```java +// list is an ArrayList object +Iterator iterator = list.iterator(); +``` +Iterator has three important methods. They are given below. + +`hasNext()` - This method checks if the collection has any object available next, if found it will return true else false + +`next()` - This method returns the next object from the ArrayList. + +`remove()` - This method removes the object from the ArrayList + +I have given a Java program below to iterate over an ArrayList using the iterator interface. We will be using the `hasNext()` and `next()` methods in the program. + +```java +import java.util.Iterator; +import java.util.ArrayList; +import java.util.List; +/** + * A Java program to iterate through an ArrayList + * using the Iterator interface. + * + * @author coderolls.com + * + */ +public class ArrayListIterateExample4 { + + public static void main (String[] args) { + + List list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Iterating through ArrayList using Iterator interface........\n"); + + // getting an iterator + Iterator iterator = list.iterator(); + + // hasNext() returns true only if the object is available at the next call + while (iterator.hasNext()) { + //next() returns an object, we can cast it to the required type + String str = (String) iterator.next(); + System.out.println("Object form the ArrayList is " + str); + } + } +} +``` +Output: +``` +Iterating through ArrayList using Iterator interface........ + +The object from the ArrayList is Monday +The object from the ArrayList is Tuesday +The object from the ArrayList is Wednesday +The object from the ArrayList is Thursday +The object from the ArrayList is Friday +The object from the ArrayList is Saturday +The object from the ArrayList is Sunday +``` +### Explanation + +1. In the above Java program, I have created an empty ArrayList of String. +2. I have added a few String objects to the ArrayList i.e `list` +3. I have invoked the `iterator()` method on the `list` to get an iterator. +4. I have written a simple while loop with the condition `iterator.hasNext()`. It returns true only if the object is available. +5. Once we enter the loop, we can use the `iterator.next()` method to get the object. +6. We can cast it to the required datatype and use it in the loop. +7. The `hasNext()` method returns true till the list has the object i.e. till the last object of the list and after that, it will return false. And we will not enter in the loop. + +### Note : +It is always recommended to use the `Iterator.remove()` method for removing an element from a list while iterating on it. Also, we have the `remove()` method in the ArrayList class, if you use the `ArrayList.remove()` method to remove an element while iterating over the list, you will get the `ConcurrentModificationException`. + + +## 5. Iterating the ArrayList using Java 8 forEach() Method + +In Java 8, we got the new `forEach()` method to iterator over collections. + +Inside the `forEach()` method, we can write the lambda expression for the Consumer functional interface. + +I have given a sample Java program below to iterate over the ArrayList using the `forEach()` method. + +```java + +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to iterate through an ArrayList + * using forEach method and lambda expression. + * + * @author coderolls.com + * + */ +public class ArrayListIterateExample4 { + + public static void main (String[] args) { + + List list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Iterating through ArrayList using forEach method and lambda expression........\n"); + + // add lambda expression in the foreach method + list.forEach(s -> System.out.println("Object form the ArrayList is "+ s)); + } +} +``` +Output: +``` +Iterating through ArrayList using forEach method and lambda expression........ + +The object from the ArrayList is Monday +The object from the ArrayList is Tuesday +The object from the ArrayList is Wednesday +The object from the ArrayList is Thursday +The object from the ArrayList is Friday +The object from the ArrayList is Saturday +The object from the ArrayList is Sunday +``` +### Explanation + +1. In the above Java program, I have created an empty ArrayList of String. +2. I have added a few String objects to the ArrayList. i.e `list` +3. I have invoked the `forEach()` method on the `list`, and added the following lambda expression to simply print the string objects ` +s -> System.out.println("Object form the ArrayList is "+ s)`. + +## Conclusion + +We can iterate over ArrayList using the following ways. + +1. Iterating the ArrayList using basic for loop +2. Iterating the ArrayList using Enhanced For Loop i.e. For-each loop +3. Iterating the ArrayList using a while loop +4. Iterating the ArrayList using Iterator +5. Iterating the ArrayList using Java 8 forEach() Method + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/iterating-the-arraylist-in-java). + +If you know any other way to iterate through ArrayList, please write it down in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-10-arraylist-clear-method-in-java.md b/_posts/collections/arraylist/2021-12-10-arraylist-clear-method-in-java.md new file mode 100644 index 0000000..7d39cdc --- /dev/null +++ b/_posts/collections/arraylist/2021-12-10-arraylist-clear-method-in-java.md @@ -0,0 +1,104 @@ +--- +layout: post +title: "ArrayList clear() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see the clear() method of ArrayList in Java. This method is used to remove all the elements of the current ArrayList." +--- + +In this article, we will see the `clear()` method of [ArrayList in Java](https://coderolls.com/arraylist-in-java/). This method is used to remove all the elements of the ArrayList. + +## Introduction + +We use [ArrayList](https://coderolls.com/arraylist-in-java/) in day-to-day Java programming. ArrayList is an ordered collection and it allows duplicate elements. + + We have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://127.0.0.1:4000/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/) and [`iterate()`](http://coderolls.com/iterating-the-arraylist-in-java/) + +Today we will see the `clear()` method of the ArrayList class in Java. + +## ArrayList `clear()` method in java + +It has a method signature as given below. +```java +public void clear() +``` + +When we invoke the clear() method on an ArrayList, it removes all of the elements from this list. + +So, the list will be empty after the successful invocation of the clear method on the list. + +It has a return type as a `void`. This means this method does not return anything. + +Also, it does not accept any parameter. + +Let's see an example Java program that uses the `clear()` method to remove all the elements of the list. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to remove all the elements + * of ArrayList using the clear() method. + * + * @author coderolls.com + * + */ +public class ArrayListClearMethodExample { + + public static void main(String[] args) { + + //Create an ArrayList cities + List cities = new ArrayList(); + + // add string objects in 'cities' + cities.add("New York City"); + cities.add("Los Angeles"); + cities.add("Mountain View"); + cities.add("Austin"); + cities.add("Atlanta"); + + // printing the cities + System.out.println("Before invoking the clear() method"); + System.out.println("Cities: "+ cities); //print the ArrayList with elements + System.out.println("cities size: "+ cities.size()); + + //invoke the clear() method on arraylist + cities.clear(); + System.out.println("\nAfter invoking the clear() method"); + System.out.println("Cities: "+ cities); // empty ArrayList + System.out.println("cities size: "+ cities.size()); + } +} +``` +Output: +``` +Before invoking the clear() method +Cities: [New York City, Los Angeles, Mountain View, Austin, Atlanta] +cities size: 5 + +After invoking the clear() method +Cities: [] +cities size: 0 +``` +### Explanation: + +1. I have created an ArrayList object `cities` +2. I have added a few String objects to the `cities` +3. I have printed the `cities` to see the String objects present in it. Also, I have printed the size of the `cities`. We can see its size is `5` since we have added the 5 String objects in it. +4. Invoke the `clear()` method on the `cities` to remove all its elements. +5. When we print the cities ArrayList again, we can not see any String objects present in it. Also, the size of `cities` is `0`, so we can say the `clear()` method made it empty. + +## Conclusion + +When we invoke the `clear()` method on the ArrayList, it removes all the elements from this Arraylist and makes it empty. +``` +arrayList.clear() +``` + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-clear-method-in-java). + +If you know anything else about the `clear()` method of the [ArrayList class](https://coderolls.com/arraylist-in-java/), kindly write it in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-12-arraylist-contains-method.md b/_posts/collections/arraylist/2021-12-12-arraylist-contains-method.md new file mode 100644 index 0000000..d4907ad --- /dev/null +++ b/_posts/collections/arraylist/2021-12-12-arraylist-contains-method.md @@ -0,0 +1,95 @@ +--- +layout: post +title: "ArrayList contains() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see the contains() method of ArrayList in Java. This method is used to check if the list contains the specified element." +--- +In this article, we will see the `contains()` method of [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method is used to check if the list contains the element. + +## Introduction + +[ArrayList](https://coderolls.com/arraylist-in-java/) is an ordered collection and it allows duplicate elements. It is widely used to store and retrieve data. + +We have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](http://coderolls.com/iterating-the-arraylist-in-java/) and [`clear()`](http://coderolls.com/arraylist-clear-method-in-java/). Today we will see the `contains()` method. + +If we need to check if any element is present in the list or not, we can use the `contains()` method from the ArrayList class in Java. + +## ArrayList `contains()` method + +It has a method signature as given below. +```java +public boolean contains(Object o) +``` + +This method is used to check if the ArrayList contains the specified element. + +This method accepts a single parameter of type `Object` + +- **`o`: -** an Object `o` whose presence in this list is to be tested + +This method has a return type as a `boolean`. It returns `true` if the list contains the specified element. Otherwise, it returns `false`. + +I have given a Java program to check if the list contains the specified element using the ArrayList `contains()` method. + +```java +import java.util.ArrayList; +import java.util.List; +/** + * A Java program to check if the ArrayList + * contains the specified element. + * + * @author coderolls.com + * + */ +public class ArrayListContainsMethodExample { + + public static void main(String[] args) { + + //create an empty ArrayList object 'states' + List states = new ArrayList(); + + //add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + + //check if states contain Florida + boolean isPresent1 = states.contains("Florida"); + System.out.println("Is Florida present in the list: "+ isPresent1); + + //check if states contain Alaska + boolean isPresent2 =states.contains("Alaska"); + System.out.println("\nIs Alaska present in the list: "+ isPresent2); + } +} +``` +Output: +``` +Is Florida present in the list: true + +Is Alaska present in the list: false +``` +### Explanation +1. I have created an ArrayList object `states`. +2. I have added a few String objects in the `states`. +3. I have checked if the list `states` contains the `Florida` string object using the `contains()` method. Since `Florida` is present in the `states` list, it returns `true`. +4. I have captured the return value for the first `contains()` method in the `isPresent1` boolean variable. When we print the `isPresent1`, it has a value `true`. +5. Next time, I checked if the `states` list contains the `Alaska` using the `contains()` method. Since `Alaska` is not present in the `states` list, it returns `false` +6. I have captured the return value for the second `contains()` method in the `isPresent2` boolean variable. When we print the `isPresent2`, it has a value `false`. + + +## Conclusion + +The ArrayList `contains()` method is used to check if the list contains the specified element. + +This method returns `true` if the specified element is present in the list. Otherwise, it returns `false` + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-contains-method). + +If you know anything other than this, kindly write in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-14-convert-arraylist-to-array.md b/_posts/collections/arraylist/2021-12-14-convert-arraylist-to-array.md new file mode 100644 index 0000000..388f345 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-14-convert-arraylist-to-array.md @@ -0,0 +1,185 @@ +--- +layout: post +title: "How to convert ArrayList to Array In Java?" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to convert an ArrayList to an Array in Java." +--- +In this article, we will see how to convert an ArrayList to an Array in Java. + +## Introduction + +[ArrayList in Java](https://coderolls.com/arraylist-in-java/) is an ordered collection. Also, ArrayList allows the duplicate elements. + +We have see the ArrayList method like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https//coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](http://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](http://coderolls.com/arraylist-clear-method-in-java/) and [`contains()`](http://coderolls.com/arraylist-contains-method). + +ArrayList mostly provides all the regular operations that need to be performed on Array. So convert ArrayList to Array only when your use case requires it. + +We can convert an ArrayList to an Array in Java using the `toArray()` method. + +There are two methods to convert an ArrayList to an Array. They are given below. + +1. `public Object[] toArray()` method +2. `public T[] toArray(T[] a)` method + +Let's see both methods one by one. + +## 1. `public Object[] toArray()` method + +The `toArray()` method returns an array containing all of the elements in this ArrayList in proper sequence. + +The method signature is given below. + +```java +public Object[] toArray() +``` + +As shown in the above method signature, the return type of this method is `Object[]`. It returns an array that contains all the elements of the ArrayList in proper sequence. + +I have given an example Java program to convert an ArrayList to an Array. It converts an ArrayList of String to Object Array i.e. `Object []`. + +```java +/** + * A Java program to convert an ArrayList to an array using + * toArray method. + * + * toArray() method returns Object[] + * + * @author coderolls.com + * + */ +public class ArrayListToArray { + + public static void main(String[] args) { + ArrayList arrayList = new ArrayList(); + + //adding elements to the ArrayList + arrayList.add("Meta"); + arrayList.add("Apple"); + arrayList.add("Amazon"); + arrayList.add("Netflix"); + arrayList.add("Microsoft"); + arrayList.add("Google"); + + System.out.println("ArrayList: \n"+ arrayList); + + // convert ArrayList to array + Object[] objects = arrayList.toArray(); + + System.out.println("\nArray:"); + + //we will receive the object array, so iterate on it to print each element + for(Object obj:objects) { + System.out.println(obj); + } + } +} +``` +Output: +``` +ArrayList: +[Meta, Apple, Amazon, Netflix, Microsoft, Google] + +Array: +Meta +Apple +Amazon +Netflix +Microsoft +Google +``` +## 2. `public T[] toArray(T[] a)` method + +This method also returns an array that contains all the elements of the ArrayList in proper sequence. + +The method signature is as given below. + +```java +public T[] toArray(T[] a) +``` + +As shown in the method signature, this method accepts one parameter. + + - **`T[] a`:-** A new array of type T, into which the elements of the list are to be stored. If the specified array is not enough to store all the elements of the ArrayList, a new array of the same type will be created. + +This method returns `T []` i.e. An array of the specified type can be returned. + +I have given a sample Java program to convert an ArrayList to an array. Here, we will be converting an ArrayList of type String to String Array i.e. `String []`. + +```java +import java.util.ArrayList; + +/** + * A Java program to convert an ArrayList to an array using + * toArray method. + * + * toArray(T[] a) method returns T[] + * + * @author coderolls.com + * + */ +public class ArrayListToArray2 { + + public static void main(String[] args) { + ArrayList arrayList = new ArrayList(); + + //adding elements to the ArrayList + arrayList.add("Meta"); + arrayList.add("Apple"); + arrayList.add("Amazon"); + arrayList.add("Netflix"); + arrayList.add("Microsoft"); + arrayList.add("Google"); + + System.out.println("ArrayList: \n"+ arrayList); + + // convert ArrayList to array + // pass a new String array of the ArrayList size as a param to toArray + //String[] elements = arrayList.toArray(new String[arrayList.size()]); + + //kindly read the 'Important Note' below + String[] elements = arrayList.toArray(new String[0]); + + + System.out.println("\nArray:"); + //we will receive the string array, so iterate on it to print each element + for(String str:elements) { + System.out.println(str); + } + } +} +``` +Output: +``` +ArrayList: +[Meta, Apple, Amazon, Netflix, Microsoft, Google] + +Array: +Meta +Apple +Amazon +Netflix +Microsoft +Google +``` + +### Important Note: + +The code above used new String[arrayList.size()] as a parameter to a `toArray()` method. However, [this blogpost from Aleksey ShipilΡ‘v](https://shipilev.net/blog/2016/arrays-wisdom-ancients/) reveals that due to JVM optimizations, using new String[0] is better now. + + +## Conclusion + +We can convert an ArrayList to an Array in Java using the `toArray()` method. + +There are two versions of the `toArray()` method. + +1. `public Object[] toArray()` method +2. `public T[] toArray(T[] a)` method + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/convert-arraylist-to-array). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-16-arraylist-addall-method-in-java.md b/_posts/collections/arraylist/2021-12-16-arraylist-addall-method-in-java.md new file mode 100644 index 0000000..637e425 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-16-arraylist-addall-method-in-java.md @@ -0,0 +1,183 @@ +--- +layout: post +title: "ArrayList addAll() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see how to add another collection element in the ArrayList. Also, we will see how to add another collection element from any particular index in ArrayList." +--- +In this article, we will see how to add other collection elements in the ArrayList. Also, we will see how to add other collection elements from any particular index in ArrayList. + +## Introduction + + [ArrayList](https://coderolls.com/arraylist-in-java/) is a widely used class from the Collection framework in Java. ArrayList used a dynamic array internally to store the elements. + +When we add objects to [ArrayList](https://coderolls.com/arraylist-in-java/), it maintains the insertion order. So, ArrayList is an ordered collection. + +Also, duplicate objects are allowed in ArrayList. + +Sometimes we need to add the elements of another collection to the ArrayList. The arrayList call provides the `addAll()` method to add the elements of the collection. + +The `addAll()` method has two overload type +1. `addAll(Collection c)` +2. `addAll(int index, Collection c)` + +The first ArrayList method adds the elements of the specified collection to the end of the ArrayList. + +The second ArrayList method adds the elements of the specified collection at the specified index. + +Let's see both the methods one by one. + +## 1. Add a collection in ArrayList using the `addAll(Collection c)` method + +The `addAll(Collection c)` method adds all the elements of the specified collection to the end of the ArrayList. + +The method signature for this method is given below. +```java +public boolean addAll(Collection c) +``` +The method signature shows that this method accepts one parameter of type Collection. + +- **`c` : -** any collection obejct + +It has a return type as `boolean` i.e. this method returns `true` if the ArrayList as a result of the call (if elements from other collections are added to the ArrayList), otherwise it returns false. + +This method may throw [NullPointerException](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html "class in java.lang") if the specified collection is empty + +I have given a java program to add elements of a collection to ArrayList using the `addAll(Collection c)` method. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to add all elements of the specified collection + * to the end of the ArrayList + * + * @author Gaurav Kukade at coderolls.com + * + */ +public class ArrayListAddAllExample { + + public static void main(String[] args) { + // ArrayList contains actresses + List actresses1 = new ArrayList(); + + actresses1.add("Natalie Portman"); + actresses1.add("Abigail Anderson"); + actresses1.add("Jennifer Lawrence"); + + System.out.println("Actresses collection 1: \n"+ actresses1 ); + + // ArrayList contains actresses + List actresses2 = new ArrayList(); + + actresses2.add("Angelina Jolie"); + actresses2.add("Scarlett Johansson"); + + System.out.println("Actresses collection 2: \n"+ actresses2); + + // Add actresses2 collections all elements to actresses1 collection using addAll()method + actresses1.addAll(actresses2); + + System.out.println("Actresses : \n"+ actresses1); + } +} +``` +Output: +``` +Actresses collection 1: +[Natalie Portman, Abigail Anderson, Jennifer Lawrence] +Actresses collection 2: +[Angelina Jolie, Scarlett Johansson] +Actresses : +[Natalie Portman, Abigail Anderson, Jennifer Lawrence, Angelina Jolie, Scarlett Johansson] +``` + +## 2. Add a collection in ArrayList at a particular index using the `addAll(int index, Collection c)` method + +The `addAll(int index, Collection c)` method adds all the elements of the specified collection to the ArrayList from the specified `index`. + +The method signature for this method is as given below. +```java +public boolean addAll(int index, Collection c) +``` + +This method accepts two parameters, +- **`c`: -** a collection `c` whose elements need to be added to the ArrayList +- **`index`: -** an `index` of type `int`, it specifies the position in ArrayList from collection `c`'s elements will be added. + +It returns `true` if the ArrayList got changed, otherwise `false` + +This method may throw the following exceptions +- [IndexOutOfBoundsException](https://docs.oracle.com/javase/8/docs/api/java/lang/IndexOutOfBoundsException.html "class in java.lang") - if the index is out of range (index < 0 || index > arraList.size()) +- [NullPointerException](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html "class in java.lang"), if the specified collection is empty + +I have given a Java program to add elements of a collection to ArrayList at a particular index using the `addAll(Collection c)` method. +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to add all elements of the specified collection + * to the ArrayList from a particular index + * + * @author coderolls.com + * + */ +public class ArrayListAddAllExample2 { + + public static void main(String[] args) { + // ArrayList containing entrepreneurs + List entrepreneurs1 = new ArrayList(); + + entrepreneurs1.add("Bill Gates"); + entrepreneurs1.add("Steve Jobs"); + entrepreneurs1.add("Jeff Bezos"); + entrepreneurs1.add("Richard Branson"); + entrepreneurs1.add("Mark Cuban"); + + System.out.println("Entrepreneurs Collection 1: \n"+ entrepreneurs1 ); + + // ArrayList containing entrepreneurs + List entrepreneurs2 = new ArrayList(); + + entrepreneurs2.add("Mark Zuckerberg"); + entrepreneurs2.add("Larry Page"); + entrepreneurs2.add("Larry Ellison"); + + System.out.println("Entrepreneurs collection 2: \n"+ entrepreneurs2); + + // Add entrepreneurs2 collections all elements to entrepreneurs1 Collection + // starting from index 2 + entrepreneurs1.addAll(2, entrepreneurs2); + + System.out.println("Entrepreneurs : \n"+ entrepreneurs1); + } +} +``` +Output: +``` +Entrepreneurs Collection 1: +[Bill Gates, Steve Jobs, Jeff Bezos, Richard Branson, Mark Cuban] +Entrepreneurs Collection 2: +[Mark Zuckerberg, Larry Page, Larry Ellison] +Entrepreneurs : +[Bill Gates, Steve Jobs, Mark Zuckerberg, Larry Page, Larry Ellison, Jeff Bezos, Richard Branson, Mark Cuban] +``` + +## Conclusion + +We can add elements of a collection to the ArrayList using the `addAll()` method in two ways. + +1. `addAll(Collection c)` - it adds elements of the specified collection to the end of ArrayList +2. `addAll(int index, Collection c)` - it adds elements of the specified collection to the ArrayList from the specified position (index) + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-addall-method-in-java). + +Please write your thoughts in the commend section below. + + + diff --git a/_posts/collections/arraylist/2021-12-18-arraylist-get-method.md b/_posts/collections/arraylist/2021-12-18-arraylist-get-method.md new file mode 100644 index 0000000..9da32fa --- /dev/null +++ b/_posts/collections/arraylist/2021-12-18-arraylist-get-method.md @@ -0,0 +1,106 @@ +--- +layout: post +title: "ArrayList get() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this article, we will see the `get()` method of the ArrayList class in Java. This method is used to get an ArrayList element by its index." +--- + +In this article, we will see the `get()` method of [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method is used to get an ArrayList element by its index. + +## Introduction + +ArrayList is a widely used class to store and retrieve data in a collection framework. + +ArrayList is an ordered collection i.e. it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +When we [iterate over an ArrayList](https://coderolls.com/iterating-the-arraylist-in-java/) using a for loop, the variable `i` will be the current index of the list. We can use the variable `i` in the `get(int index)` method to get the element at index `i`. + +We have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/) and [`contains()`](https://coderolls.com/arraylist-contains-method). + +Today we will see the `get()` method. + +## ArrayList `get(int index)` method + +The `get()` method is used to get the ArrayList element by its index. + +The method signature is given below. +```java +public E get(int index) +``` + +As shown in the above method signature, it returns the element `E` from the ArrayList. + +It accepts the single parameter `index` of type `int`. + +I have given an example Java program to get an ArrayList element by its index using the `get()` method. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to get the element by + * its index using the get() method + * + * @author Gaurav Kukade at coderolls.com + */ +public class ArrayListGetExample { + + public static void main(String[] args) { + List list = new ArrayList(); + + list.add("Monday"); + list.add("Tuesday"); + list.add("Wednesday"); + list.add("Thursday"); + list.add("Friday"); + list.add("Saturday"); + list.add("Sunday"); + + System.out.println("Arraylist:"+ list); + + // get element at index 3 + String element = list.get(3); + System.out.println("\nThe element at index 3 is "+ element); + + System.out.println("\nUsing the get() method in for loop: \n"); + + // using the get(0 method in for loop + for(int i=0; i { + + public static void main(String[] args) { + + MyArrayList myArrayList = new MyArrayList(); + + myArrayList.add("Monday"); + myArrayList.add("Tuesday"); + myArrayList.add("Wednesday"); + myArrayList.add("Thursday"); + myArrayList.add("Friday"); + myArrayList.add("Saturday"); + myArrayList.add("Sunday"); + + System.out.println("ArrayList before removing a range of elements:\n"+ myArrayList); + + myArrayList.removeRange(2, 4); + + System.out.println("\nArrayList after removing a range of elements:\n"+ myArrayList); + } +} +``` + +Output: + +``` +ArrayList before removing a range of elements: +[Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] + +Arraylist after removing a range of elements: +[Monday, Tuesday, Friday, Saturday, Sunday] +``` + +## Conclusion + +We can use the `removeRange(int fromIndex, int toIndex)` method **to remove the range of elements from the subclass of ArrayList.** This range will start from the element at index `fromIndex` to the element before the `toIndex` index. + + **The parameter `fromIndex` is inclusive and `toIndex` is exclusive.** + +--- +### Important Note: +The `removeRange(int fromIndex, int toIndex)` method is **protected method** in ArrayList. A protected method is accessed in class, subclasses and in a package, but not public. + +--- + +The example java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-removerange-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-22-arraylist-retainall-method.md b/_posts/collections/arraylist/2021-12-22-arraylist-retainall-method.md new file mode 100644 index 0000000..43c2f0c --- /dev/null +++ b/_posts/collections/arraylist/2021-12-22-arraylist-retainall-method.md @@ -0,0 +1,176 @@ +--- +layout: post +title: "ArrayList retainAll() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "Let's see the retainAll() method of the Arraylist class in Java." +--- + +Let's see the `retainAll()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). + +This method is used to retain all the elements in of the collection in the list. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +ArrayList is an ordered collection i.e. it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +Also, We have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method) and [`removeRange()` ](https://coderolls.com/arraylist-removerange-method) method. + +Today we will see the `retainAll()` method. + + +## ArrayList `retainAll(Collection c)` method + +The `retainAll()` method retains all the elements of the collections passed as a parameter in the list. + +That means it will remove all elements from the list other than the ones that are present in the collection that is passed as a parameter. + +The method signature is given below. + +```java +public boolean retainAll(Collection c) +``` + +As shown in the method signature, it accepts only one parameter i.e. `Collection c`. It is a collection of the objects that we have to retain in the list. + +Also, the `retainAll()` method has a return type as a `boolean`. It returns `true` only if the list is changed as a result of the method call otherwise `false`. + +Let's see the Java program for a better understanding. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to explain the retainAll() method of the ArrayList class. + * + * @author coderolls.com + * + */ +public class ArrayListRetainAllExample { + + public static void main(String[] args) { + //create an empty ArrayList of Integer to retain elements + List numbers1 = new ArrayList(); + + //add number to the list + numbers1.add(4); + numbers1.add(5); + numbers1.add(6); + + //create an empty ArrayList of Integer + List numbers2 = new ArrayList(); + + // add the number to the list + numbers2.add(1); + numbers2.add(2); + numbers2.add(3); + numbers2.add(4); + numbers2.add(5); + numbers2.add(6); + numbers2.add(7); + numbers2.add(8); + numbers2.add(9); + + System.out.println("Lists before the method call"); + System.out.println("numbers1: "+ numbers1); + System.out.println("numbers2: "+ numbers2); + + //retain all the elements of numbers1 in the list numbers2 + numbers2.retainAll(numbers1); + + System.out.println("\nLists after the method call"); + System.out.println("numbers1: "+ numbers1); + System.out.println("numbers2: "+ numbers2); + } +} +``` + +Output: + +``` +Lists before the method call +numbers1: [4, 5, 6] +numbers2: [1, 2, 3, 4, 5, 6, 7, 8, 9] + +Lists after the method call +numbers1: [4, 5, 6] +numbers2: [4, 5, 6] +``` +### Exceptions thrown by `retainAll()` Methods +This method may throw the `ClassCastException` and `NullPointerException`. + +#### `ClassCastException` +This method may throw the `ClassCastException`, if the class of an element of this list is incompatible with the specified collection. (optional) + +#### `NullPointerException` +This method may throw the `NullPointerException`, if this list contains a null element and the specified collection does not permit null elements (optional) or if the specified collection is null. + +The Java example for the `NullPointerException` is given below. + +```java +import java.util.ArrayList; +import java.util.List; +/** + * A Java program to show the NullPointerException in retainAll() method + * of the ArrayList class. + * + * @author coderolls.com + * + */ +public class RetainAllNullPointerExceptionExample { + + public static void main(String[] args) { + //create an empty ArrayList of Integer to retain elements + List numbers1 = null; + + //create an empty ArrayList of Integer + List numbers2 = new ArrayList(); + + //Add the number to the list + numbers2.add(1); + numbers2.add(2); + numbers2.add(3); + numbers2.add(4); + + System.out.println("Lists before the method call"); + System.out.println("numbers1: "+ numbers1); + System.out.println("numbers2: "+ numbers2); + + //retain all the elements of numbers1 in the list numbers2 + numbers2.retainAll(numbers1); + + System.out.println("\nLists after the method call"); + System.out.println("numbers1: "+ numbers1); + System.out.println("numbers2: "+ numbers2); + } +} +``` + +Output: +``` +Lists before the method call +numbers1: null +numbers2: [1, 2, 3, 4] +Exception in thread "main" java.lang.NullPointerException + at java.util.Objects.requireNonNull(Objects.java:203) + at java.util.ArrayList.retainAll(ArrayList.java:714) + at com.gaurav.ExProject.ArrayList.RetainAllClassCastExceptionExample.main(RetainAllClassCastExceptionExample.java:27) +``` +## Conclusion + +The `retainAll(Collection c)` method retains all the elements of the collection passed as a parameter in the list. + +```java +public boolean retainAll(Collection c) +``` + +This method returns `true` if the list is changed otherwise `false`. + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-retainall-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-24-sublist-method-in-arraylist.md b/_posts/collections/arraylist/2021-12-24-sublist-method-in-arraylist.md new file mode 100644 index 0000000..a702004 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-24-sublist-method-in-arraylist.md @@ -0,0 +1,185 @@ +--- +layout: post +title: "subList() method of ArrayList class in java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the subList() method of the ArrayList class in Java." +--- +In this tutorial, we will see the `subList()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method returns a view of the specified range within the list. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +ArrayList is an ordered collection i.e. it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +Also, we have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method) and [`retainAll()`](https://coderolls.com/arraylist-retainall-method) method. + +Today we will see the `subList(int fromIndex, int toIndex)` method. + + +## ArrayList `subList(int fromIndex, int toIndex)` method + +The `subList(int fromIndex, int toIndex)` method returns the view of the portion of this list between the specified **`fromIndex`, inclusive and `toIndex`, exclusive.** + +The method signature is given below. + +```java +public List subList(int fromIndex, int toIndex) +``` +As shown in the method signature, the subList() method accepts two parameters of type `int` i.e `fromIndex` and `toIndex` + +{:class=" table table-bordered"} +|Parameter|Description| +|:-------|:----| +|`fromIndex`|low endpoint (inclusive) of the subList| +|`toIndex`|high endpoint (exclusive) of the subList| + + +Let's see the Java program for a better understanding. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A java program to explain the subList() method of the ArrayList class in Java + * + * @author coderolls.com + * + */ +public class ArrayListSubListExample { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + + System.out.println("The states list: \n"+ states); + + //Sublist the states list from 1 to 3 index + List statesSubList = states.subList(1, 3); + + System.out.println("\nThe states sublist from index 1 (inclusive) to 3 (exclusive): \n"+ statesSubList); + } +} +``` + +Output: +``` +The states list: +[California, Texas, Florida, New Jersey, Washington] + +The states sublist from index 1 (inclusive) to 3 (exclusive): +[Texas, Florida] +``` +### Exceptions thrown by `subList()` Methods +This method may throw the `ClassCastException` and `NullPointerException`. + +#### `IndexOutOfBoundsException` +This method may throw the `ClassCastException`, if an endpoint index value is out of range. i.e. if `fromIndex` is less than `0` (`fromIndex < 0 `) or `toIndex` is greater than the size of the ArrayList (`toIndex > size`). + +The Java example for the `IndexOutOfBoundsException` is given below. + +```java +/** + * A Java program to explain the subList() methods + * IndexOutOfBoundsException exception case. + * + * @author coderolls.com + */ +public class SubListMethodExceptionExample1 { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + + System.out.println("The states list: \n"+ states); + + // will throw IndexOutOfBoundsException + List statesSubList = states.subList(1, 7); // will throw exception + + System.out.println("\nThe states sublist from index 1 (inclusive) to 3 (exclusive): \n"+ statesSubList); + } +} +``` + +Output: +``` +The states list: +[California, Texas, Florida, New Jersey, Washington] +Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 7 + at java.util.ArrayList.subListRangeCheck(ArrayList.java:1012) + at java.util.ArrayList.subList(ArrayList.java:1004) + at com.gaurav.ExProject.ArrayList.SubListMethodExceptionExample1.main(SubListMethodExceptionExample1.java:22) +``` + +#### `IllegalArgumentException` +This method may throw the `NullPointerException`, if the endpoint indices are out of order. i.e. if the `fromIndex` is greater than `toIndex` + +The Java example for the `IllegalArgumentException` is given below. + +```java +/** + * A Java program to explain the subList() methods + * IllegalArgumentException exception case. + * + * @author coderolls.com + */ +public class SubListMethodExceptionExample2 { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the arraylist + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + + System.out.println("The states list: \n"+ states); + + // will throw IllegalArgumentException + List statesSubList = states.subList(3, 1); + + System.out.println("\nThe states sublist from index 1 (inclusive) to 3 (exclusive): \n"+ statesSubList); + } +} +``` + +Output: +``` +The states list: +[California, Texas, Florida, New Jersey, Washington] +Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(3) > toIndex(1) + at java.util.ArrayList.subListRangeCheck(ArrayList.java:1014) + at java.util.ArrayList.subList(ArrayList.java:1004) + at com.gaurav.ExProject.ArrayList.SubListMethodExceptionExample2.main(SubListMethodExceptionExample2.java:28) +``` +## Conclusion + +```java +public List subList(int fromIndex, int toIndex) +``` +The `subList(int fromIndex, int toIndex)` method returns the view of the portion of this list between the specified **`fromIndex`, inclusive and `toIndex`, exclusive.** + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/sublist-method-in-arraylist). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-26-arraylist-trimtosize-method.md b/_posts/collections/arraylist/2021-12-26-arraylist-trimtosize-method.md new file mode 100644 index 0000000..2e41ca8 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-26-arraylist-trimtosize-method.md @@ -0,0 +1,63 @@ +--- +layout: post +title: "ArrayList trimToSize() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the trimToSize() method of the ArrayList class in Java." +--- +In this tutorial, we will see the `trimToSize()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). + +## Introduction + +In the last few tutorials, we are looking at various methods of the ArrayList class in Java. + +We have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method) and [`subList()`](https://coderolls.com/sublist-method-in-arraylist) method. + +ArrayList is a widely used class to store and retrieve data in a collection framework. + +ArrayList is an ordered collection i.e. it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +Today we will see the `trimToSize()` method. + +This method trims the capacity of this ArrayList instance to be the list's current size. + +## ArrayList `trimToSize()` method + +When we create a new ArrayList instance, it will get created with **the default initial capacity of 10**. + +```java +List states = new ArrayList(); +``` + +That means it reserves the 10 blocks in the memory to store the `arraylist` elements. So, if we add the 10 elements to the `arrayList`, the `arrayList` can potentially accommodate without reallocating its internal structures. + +But, if we just added two elements to the `arrayList`, the remaining blocks will remain empty and not used. + +```java +states.add("California"); +states.add("Texas"); +``` + +Here, we can use the `trimToSize()` method to trim the capacity of this `arrayList` instance to be the list's current size. + +```java +states.trimToSize(); +``` +So, if there are only two elements added to the list and we invoke `trimToSize()` on it, the capacity will be two only. It frees the remaining reserved blocks from the memory. + +The method signature is given below. +```java +public void trimToSize() +``` +This method does not accept any parameter and has a return type as a `void` i.e. it do not return anything. + +Also, no exception occurs while invoking this method. + +## Conclusion + +The `trimToSize()` method trims the capacity of this ArrayList instance to be the list's current size. + +--- + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-28-arraylist-indexof-method.md b/_posts/collections/arraylist/2021-12-28-arraylist-indexof-method.md new file mode 100644 index 0000000..085ac24 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-28-arraylist-indexof-method.md @@ -0,0 +1,90 @@ +--- +layout: post +title: "ArrayList indexOf() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the indexOf() method of the ArrayList class in Java." +--- +In this tutorial, we will see the `indexOf()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method returns the index of the first occurrence of the specified element in this list. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +Also, we have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method) and [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method) method. + +Today we will see the `indexOf(Object o)` method. + + +## ArrayList `indexOf(Object o)` method + +We know the important feature of the list is that it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +So, when we try to find any elements, there are chances that the same elements may present in the list multiple times at multiple indexes. + +The `indexOf(Object o)` method **returns the index of the first occurrences of the object specified**. It **returns -1 if the specified object `o` is not present** in the list. + +The method signature is given below. + +```java +public int indexOf(Object o) +``` +The `indexOf()` method accepts only one parameter, the `Object o` whose index of the first occurrence will be returned. + +The method has a return type as an `int`. It returns the index of the first occurrences of the object specified as an `int` . If the specified object `o` is not present in the list, it will return -1. + +Let's see the Java program for a better understanding. + +```java +/** + * A java program to explain the indexOf() method + * of the ArrayList class in Java. + * + * @author coderolls.com + */ +public class ArrayListIndexOfExample { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList, Florida multiple times + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Florida"); + + int index = states.indexOf("Florida"); + + //prints index of the first occurrences of Florida i.e. 2 + System.out.println("The index of Florida: "+ index); + + //trying to get the index of the element, which is not present + int index2 = states.indexOf("Alaska"); + + System.out.println("The index of Alaska: " + index2); + } +} +``` + +Output: +``` +The index of Florida: 2 +The index of Alaska: -1 +``` + +## Conclusion + +```java +public int indexOf(Object o) +``` +The `indexOf(Object o)` method **returns the index of the first occurrences of the object specified**. If the specified object `o` is not present in the list, it returns the -1. + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-indexof-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2021-12-30-arraylist-lastindexof-method.md b/_posts/collections/arraylist/2021-12-30-arraylist-lastindexof-method.md new file mode 100644 index 0000000..fe6b552 --- /dev/null +++ b/_posts/collections/arraylist/2021-12-30-arraylist-lastindexof-method.md @@ -0,0 +1,91 @@ +--- +layout: post +title: "ArrayList lastIndexOf() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the lastIndexOf() method of the ArrayList class in Java." +--- +In this tutorial, we will see the `lastIndexOf()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method returns the index of the last occurrence of the specified element in this list. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +Also, we have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method) and [`indexOf()`](https://coderolls.com/arraylist-trimtosize-method) method. + +Today we will see the `lastIndexOf(Object o)` method. + + +## ArrayList `lastIndexOf(Object o)` method + +We know the important feature of the list is that it maintains the insertion order of the elements. Also, it allows duplicate elements in the list. + +So, when we try to find any elements, there are chances that the same elements may present in the list multiple times at multiple indexes. + +The `lastIndexOf(Object o)` method **returns the index of the last occurrences of the object specified**. It **returns -1 if the specified object `o` is not present** in the list. + +The method signature is given below. + +```java +public int lastIndexOf(Object o) +``` +The `lastIndexOf()` method accepts only one parameter, the `Object o` whose index of the last occurrence will be returned. + +The method has a return type as an `int`. It returns the index of the last occurrences of the object specified as an `int` . If the specified object `o` is not present in the list, it will return -1. + +Let's see the Java program for a better understanding. + +```java +/** + * A Java program to explain the lastIndexOf() method + * of the ArrayList class in Java. + * + * @author Gaurav Kukade + */ +public class ArrayListLastIndexOfExample { + + public static void main(String[] args) { + + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList, Florida multiple times + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Florida"); + + int index = states.lastIndexOf("Florida"); + + //prints index of the last occurrences of Florida i.e. 6 + System.out.println("The last index of Florida: "+ index); + + //trying to get the index of the element, which is not present + int index2 = states.lastIndexOf("Alaska"); + + System.out.println("The index of Alaska: " + index2); + } +} +``` + +Output: +``` +The index of Florida: 6 +The index of Alaska: -1 +``` + +## Conclusion + +```java +public int lastIndexOf(Object o) +``` +The `lastIndexOf(Object o)` method **returns the index of the last occurrences of the object specified**. If the specified object `o` is not present in the list, it returns the -1. + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-lastindexof-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2022-01-01-arraylist-removeif-method.md b/_posts/collections/arraylist/2022-01-01-arraylist-removeif-method.md new file mode 100644 index 0000000..4e7782a --- /dev/null +++ b/_posts/collections/arraylist/2022-01-01-arraylist-removeif-method.md @@ -0,0 +1,98 @@ +--- +layout: post +title: "ArrayList removeIf() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the removeIf(Predicate filter) method of the ArrayList class in Java." +--- +In this tutorial, we will see the `removeIf(Predicate filter)` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method removes all of the elements of this collection that satisfy the given predicate. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +We have seen [how to remove elements from the ArrayList](https://coderolls.com/remove-element-from-arraylist/). Today, we will see how to remove elements from the ArrayList only if it satisfy the given predicate. + +Predicate is a predefined functional interface in from Java 8. It has a single abstract method `test()` which is used to test the given condition. + +Also, we have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method), [`indexOf()`](https://coderolls.com/arraylist-indexof-method) and [`lastIndexOf()`](https://coderolls.com/arraylist-lastindexof-method) method. + +Today we will see the `removeIf(Predicate filter)` method. + + +## ArrayList `removeIf(Predicate filter)` method + +The `removeIf(Predicate filter)` method removes all of the elements of this collection that satisfy the given predicate. + +The method signature is given below + +```java +public boolean removeIf(Predicate filter) +``` + +As shown in the method signature, this method accepts only one parameter `filter`. It is an instance of the Predicate Functional Interface. + +A predicate is a predefined functional Interface used to test the conditions. + +This method returns a `boolean` value. This method returns `true` if any elements from the ArrayList are removed. Otherwise, it returns `false`. + +Let's see an example Java program for the ArrayList `removeIf()` method. + +```java +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +/** + * A Java program showing an example for the removeIf() + * method of the ArrayList class in Java. + * + * @author coderolls.com + */ +public class ArrayListRemoveIfExample { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList, Florida multiple times + states.add("California"); + states.add("Texas"); + states.add("Florida"); + states.add("Florida"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Florida"); + + System.out.println("The states list before the removeIf() call: \n" + states); + + // a predicate for the condition + Predicate p = s -> s.equals("Florida"); + states.removeIf(p); // removes all elements which satisfy the predicate p + + System.out.println("\nThe states list after the removeIf() call: \n" + states); + } +} +``` + +Output: +``` +The states list before the removeIf() call: +[California, Texas, Florida, Florida, New Jersey, Washington, Florida] + +The states list after the removeIf() call: +[California, Texas, New Jersey, Washington] +``` + +## Conclusion + +The `removeIf(Predicate filter)` method removes all of the elements of the ArrayList that satisfy the given predicate. + +```java +public boolean removeIf(Predicate filter) +``` +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-removeif-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2022-01-02-arraylist-removeall-method.md b/_posts/collections/arraylist/2022-01-02-arraylist-removeall-method.md new file mode 100644 index 0000000..bf44bd6 --- /dev/null +++ b/_posts/collections/arraylist/2022-01-02-arraylist-removeall-method.md @@ -0,0 +1,176 @@ +--- +layout: post +title: "ArrayList removeAll() method" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this tutorial, we will see the removeAll(Collection c) method of the ArrayList class in Java." +--- +In this tutorial, we will see the `removeAll(Collection c)` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method removes from this list all of its elements that are contained in the specified collection. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +We have seen [how to remove elements from the ArrayList](https://coderolls.com/remove-element-from-arraylist/). Today, we will see how to remove all the elements from ArrayList specified in another collection. + +Previously, we have seen a few methods of the ArrayList class before like [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method), [`indexOf()`](https://coderolls.com/arraylist-indexof-method), [`lastIndexOf()`](https://coderolls.com/arraylist-lastindexof-method) and [`removeIf()`](https://coderolls.com/arraylist-removeIf-method) method. + +Today we will see the ` removeAll(Collection c)` method. + + +## ArrayList ` removeAll(Collection c)` method + +The ` removeAll(Collection c)` method removes from this list all of its elements that are contained in the specified collection. + +The method signature is given below + +```java +public boolean removeAll(Collection c) +``` + +As shown in the method signature, this method accepts only one parameter i.e. Collection `c`. + +This method returns a `boolean` value. This method returns `true` if the ArrayList got changed as a method call. Otherwise, it returns `false`. + +Let's see an example Java program for the ArrayList `removeAll()` method. + +```java +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +/** + * A Java program showing an example for the removeAll() + * method of the ArrayList class in Java. + * + * @author coderolls.com + */ +public class ArrayListRemoveAllExample { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList, Florida multiple times + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + states.add("Minnesota"); + states.add("Colorado"); + states.add("Missouri"); + states.add("Nevada"); + + //Create another ArrayList for items to be removed + List statesToBeRemoved = new ArrayList(); + statesToBeRemoved.add("Minnesota"); + statesToBeRemoved.add("Missouri"); + statesToBeRemoved.add("Montana"); + statesToBeRemoved.add("Michigan"); + + System.out.println("The states list before the removeAll() method call: \n" + states); + + // removes all elements specified in the ArrayList statesToBeRemoved + states.removeAll(statesToBeRemoved); + + System.out.println("\nThe states list after the removeAll() method call: \n" + states); + } +} +``` + +Output: +``` +The states list before the removeAll() method call: +[California, Texas, Montana, Arizona, Florida, Michigan, New Jersey, Washington, Ohio, Minnesota, Colorado, Missouri, Nevada] + +The states list after the removeAll() method call: +[California, Texas, Arizona, Florida, New Jersey, Washington, Ohio, Colorado, Nevada] +``` + +### Exceptions +We can get the following exceptions while invoking the `removeAll(Collection c)` method + +1. `ClassCastException` +2. `NullPointerException` + +#### `ClassCastException` +If the class of an element of this list is incompatible with the specified collection, we can get the `ClassCastException`. This is an option restriction. (Read more about [optional](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#optional-restrictions)) + +#### `NullPointerException` +If this list contains a null element and the specified collection does not permit null elements, we can get the `NullPointerException`. This is an option restriction. (Read more about [optional](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#optional-restrictions)). + +Or if the specified collection is null, we will surely get the `NullPointerException`. + +Let's see an example Java program to show the case of `NullPointerException` while invoking the `removeAll()` method. + +```java +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +/** + * A Java program showing a NullPointerException case + * for the removeAll() method of the ArrayList class in Java. + * + * @author coderolls.com + */ +public class ArrayListRemoveAllNullPointerException { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + List states = new ArrayList(); + + // add state in the ArrayList, Florida multiple times + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + states.add("Minnesota"); + states.add("Colorado"); + states.add("Missouri"); + states.add("Nevada"); + + //Create another ArrayList with a null value, + //so that removeAll will throw NullPointerException + List statesToBeRemoved =null; + + System.out.println("The states list before the removeAll() method call: \n" + states); + + // removes all elements specified in the ArrayList statesToBeRemoved + states.removeAll(statesToBeRemoved); + + System.out.println("\nThe states list after the removeAll() method call: \n" + states); + } +} +``` +Output: +``` +The states list before the removeAll() method call: +[California, Texas, Montana, Arizona, Florida, Michigan, New Jersey, Washington, Ohio, Minnesota, Colorado, Missouri, Nevada] +Exception in thread "main" java.lang.NullPointerException + at java.util.Objects.requireNonNull(Objects.java:203) + at java.util.ArrayList.removeAll(ArrayList.java:693) + at com.gaurav.ExProject.ArrayList.ArrayListRemoveAllNullPointerException.main(ArrayListRemoveAllNullPointerException.java:43) +``` + +## Conclusion + +The `removeAll(Collection c)` method removes from this list all of its elements that are contained in the specified collection. +```java +public boolean removeAll(Collection c) +``` +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-removeall-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2022-01-03-arraylist-isempty-method.md b/_posts/collections/arraylist/2022-01-03-arraylist-isempty-method.md new file mode 100644 index 0000000..18ba9fe --- /dev/null +++ b/_posts/collections/arraylist/2022-01-03-arraylist-isempty-method.md @@ -0,0 +1,98 @@ +--- +layout: post +title: "ArrayList isEmpty() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this short tutorial, we will see the isEmpty() method of the ArrayList class in Java. This method is used to check if the ArrayList is empty or not." +--- +In this tutorial, we will see the `isEmpty()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). This method is used to check if the ArrayList is empty or not. + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +In previous articles, we have various methods to perform operations on the ArrayList. + +A few methods of ArrayList class are [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method), [`indexOf()`](https://coderolls.com/arraylist-indexof-method) and [`lastIndexOf()`](https://coderolls.com/arraylist-lastindexof-method), [`removeIf()`](https://coderolls.com/arraylist-removeIf-method) and [`removeAll()`](https://coderolls.com/arraylist-removeall-method) method. + +Today we will see the `isEmpty()` method. + +## ArrayList `removeIf(Predicate filter)` method + +The `isEmpty()` method returns true if this list contains no elements. + +The `isEmpty()` method checks if the ArrayList is empty or not. If it does not find any elements in the ArrayList, it will return `true`, otherwise `false`. + +The method signature is given below + +```java +public boolean isEmpty() +``` + +This method does not accept any parameter. + +This method has a return type as a `boolean`. It returns true if ArrayList is empty. + +Let's see an example Java program for the ArrayList `isEmpty()` method. + +```java +import java.util.ArrayList; + +/** + * An example Java program for an isEmpty method + * of the ArrayList class in Java. + * + * @author Gaurav Kukade at coderolls + */ +public class ArrayListIsEmptyExample { + + public static void main(String[] args) { + //Create an ArrayList teams + ArrayList teams = new ArrayList(); + + //Add elements to the ArrayList teams + teams.add("LA Galaxy"); + teams.add("Orlando City FC"); + teams.add("Portland Timbers"); + teams.add("Columbus Crew"); + + boolean isTeamsEmpty = teams.isEmpty(); + if(isTeamsEmpty) { + System.out.println("Teams ArrayList is empty."); + } + else { + System.out.println("Teams ArrayList is not empty."); + } + + // create an ArrayList players + ArrayList players = new ArrayList(); + + boolean isPlayersEmpty = players.isEmpty(); + if(isPlayersEmpty) { + System.out.println("Players ArrayList is empty."); + } + else { + System.out.println("Players ArrayList is not empty."); + } + } +} +``` + +Output: +``` +Teams ArrayList is not empty. +Players ArrayList is empty. +``` + +## Conclusion + +The `isEmpty()` method returns true if this list contains no elements. + +```java +public boolean isEmpty() +``` +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-isempty-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2022-01-04-arraylist-ensurecapacity-method.md b/_posts/collections/arraylist/2022-01-04-arraylist-ensurecapacity-method.md new file mode 100644 index 0000000..6631b7b --- /dev/null +++ b/_posts/collections/arraylist/2022-01-04-arraylist-ensurecapacity-method.md @@ -0,0 +1,105 @@ +--- +layout: post +title: "ArrayList ensureCapacity() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this short tutorial, we will see the ensureCapacity(int minCapacity) method of the ArrayList class in Java." +--- + +In this tutorial, we will see the `ensureCapacity(int minCapacity)` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). + +## Introduction +ArrayList is a widely used class to store and retrieve data in a collection framework. + +Unlike an array, ArrayList can dynamically grow in size. + +In previous articles, we have various methods to perform operations on the ArrayList. + +A few methods of ArrayList class are [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method), [`indexOf()`](https://coderolls.com/arraylist-indexof-method) and [`lastIndexOf()`](https://coderolls.com/arraylist-lastindexof-method), [`removeIf()`](https://coderolls.com/arraylist-removeIf-method) and [`removeAll()`](https://coderolls.com/arraylist-removeall-method) method. + +Today we will see the `ensureCapacity(int minCapacity)` method. + +## ArrayList `ensureCapacity(int minCapacity)` method + +Before understanding the `ensureCapacity(int minCapacity)` method, we should know the [basics of the ArrayList class in Java](https://coderolls.com/arraylist-in-java/). + +ArrayList internally uses a dynamic array so it can grow dynamically. + +The Initial default capacity for the ArrayList is 10. And load factor is 0.75F. So, while adding the 7th element, the new ArrayList with double capacity is created, and the remaining elements of the array get added to a new array. + +When you have to ensure that your ArrayList should hold an `x` number of elements, you should invoke the `ensureCapacity(int x)` method on the ArrayList. + +So, This method increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. + +The method signature is as given below. +```java +public void ensureCapacity(int minCapacity) +``` + +This method accepts only one parameter, i.e. `minCapacity` of type `int` + +- **`minCapacity`** - the desired minimum capacity + +This method has a return type as a `void` which means it will not return anything. + +Let's see a Java program where I will invoke the `ensureCapacity(int minCapacity)` method on the ArrayList object. + +In ArrayList, class we do not have any method which gives us the current capacity, so I will be not able to show the increased capacity on the console, but since we are invoking the `ensureCapacity()` method, the capacity will be surely increased. + +```java +/** + * An example Java program for ensureCapacity(int MinCapacity) method + * of the ArrayList class in Java. + * @author Gaurav at coderolls.com + * + */ +public class ArrayListEnsureCapacityExample { + + public static void main(String[] args) { + // create an empty ArrayList object 'states' + ArrayList states = new ArrayList<>(); + + //Add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + states.add("Minnesota"); + states.add("Colorado"); + states.add("Missouri"); + states.add("Nevada"); + System.out.println("ArrayList Elements are: \n"+ states); + //We need to add more states, so we will ensure + //that ArrayList should hold 50 element + states.ensureCapacity(50); + + System.out.println("\nWe ensured that the arraylist should hold 50 elements."); + } +} +``` + +Output: +``` +ArrayList Elements are: +[California, Texas, Montana, Arizona, Florida, Michigan, New Jersey, Washington, Ohio, Minnesota, Colorado, Missouri, Nevada] + +We ensured that the ArrayList should hold 50 elements. +``` + +## Conclusion + +```java +public void ensureCapacity(int minCapacity) +``` +This method increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. + +--- +The example java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-ensurecapacity-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/arraylist/2022-01-05-arraylist-listiterator-method.md b/_posts/collections/arraylist/2022-01-05-arraylist-listiterator-method.md new file mode 100644 index 0000000..2e70259 --- /dev/null +++ b/_posts/collections/arraylist/2022-01-05-arraylist-listiterator-method.md @@ -0,0 +1,223 @@ +--- +layout: post +title: "ArrayList listIterator() method in Java" +author: gaurav +categories: [Collections, ArrayList] +toc: true +description: "In this short tutorial, we will see the listIterator() method of the ArrayList class in Java." +--- + +In this tutorial, we will see the `listIterator()` method of the [ArrayList class in Java](https://coderolls.com/arraylist-in-java/). + +## Introduction + +ArrayList is a widely used class to store and retrieve data in a collection framework. + +In previous articles, we have various methods to perform operations on the ArrayList. + +A few methods of ArrayList class are [`add()`](https://coderolls.com/add-element-in-arraylist/), [`addAll()`](http://https://coderolls.com/arraylist-addall-method-in-java/), [`remove()`](https://coderolls.com/remove-element-from-arraylist/), [`set()`](https://coderolls.com/change-element-in-arraylist/), [`iterate()`](https://coderolls.com/iterating-the-arraylist-in-java/), [`clear()`](https://coderolls.com/arraylist-clear-method-in-java/), [`contains()`](https://coderolls.com/arraylist-contains-method), [`get()`](https://coderolls.com/arraylist-get-method), [`removeRange()`](https://coderolls.com/arraylist-removerange-method), [`retainAll()`](https://coderolls.com/arraylist-retainall-method), [`trimToSize()`](https://coderolls.com/arraylist-trimtosize-method), [`indexOf()`](https://coderolls.com/arraylist-indexof-method) and [`lastIndexOf()`](https://coderolls.com/arraylist-lastindexof-method), [`removeIf()`](https://coderolls.com/arraylist-removeIf-method), [`removeAll()`](https://coderolls.com/arraylist-removeall-method), [`isEmpty`](https://coderolls.com/arraylist-isempty-method) and [`ensureCapacity()`](https://coderolls.com/arraylist-ensurecapacity-method) method. + +Today we will see the `listIterator()` method. This method provides the fail-fast iterator over elements of the list. + +There are two variations of the `listIterator()` method. + +1. `listIterator()` +2. `listIterator(int index)` + +## 1. ArrayList `listIterator()` method + +The `listIterator()` method returns a list iterator over the elements in this list (in proper sequence). + +The returned list iterator is [*fail-fast*](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#fail-fast). i.e When multiple threads try to update the list at a time, it will throw the `ConcurrentModificationExaception`. + +The method signature is as given below. + +```java +public ListIterator listIterator() +``` + +This method do not accept any parameter. + +It returns a `ListIterator` object instance. It will be a fail-fast iterator. + +Let's see an example Java program for the `listIterator()` method of the ArrayList. + +```java +import java.util.ArrayList; +import java.util.ListIterator; +/** + * An example Java program about the listIterator() + * method of the arrayList. + * + * @author coderolls.com + */ +public class ArrayListListIteratorExample { + + public static void main(String[] args) { + ArrayList states = new ArrayList<>(); + + // add state in the arraylist + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + + ListIterator itr = states.listIterator(); + + while(itr.hasNext()) { + String state = itr.next(); + System.out.println("The state: "+ state); + } + } +} +``` + +Output: +``` +The state: California +The state: Texas +The state: Montana +The state: Arizona +The state: Florida +The state: Michigan +The state: New Jersey +The state: Washington +The state: Ohio +``` + +## 2. ArrayList `listIterator(int index)` method + +This listIterator method returns a fail-fast ListIterator object instance over the elements of this arraylist (in proper sequence), starting from the position specified i.e. `index`. + +The specified index indicates the first element that would be returned by an initial call to [`next`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next--). An initial call to [`previous`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#previous--) would return the element with the specified index minus one. + +The method signature is given below. + +```java +public ListIterator listIterator(int index) +``` + +This method accepts only one parameter i.e `index`of type `int` + +- **`index`**- index of the first element to be returned from the list iterator (by a call to [`next`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next--)) + +Let's see an example Java program for the `listIterator()` method of the ArrayList. + +```java +import java.util.ArrayList; +import java.util.ListIterator; +/** + * An example Java program about the listIterator() + * method of the ArrayList. + * + * @author coderolls.com + */ +public class ArrayListListIteratorExample2 { + + public static void main(String[] args) { + ArrayList states = new ArrayList<>(); + + //Add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + + //given index 3, the iterator start from the element with index 3 + ListIterator itr = states.listIterator(3); + + while(itr.hasNext()) { + String state = itr.next(); + System.out.println("The state: "+ state); + } + } +} +``` +Output: +``` +The state: Arizona +The state: Florida +The state: Michigan +The state: New Jersey +The state: Washington +The state: Ohio +``` + +### Exception + +If the entered index is not within the range of ArrayList, we will get `IndexOutOfBoundsException` + +I have given a Java program below which shows the case of the +```java +import java.util.ArrayList; +import java.util.ListIterator; +/** + * An example Java program about the listIterator() + * method of the arrayList. + * + * @author coderolls.com + */ +public class ArrayListListIteratorException { + + public static void main(String[] args) { + + ArrayList states = new ArrayList<>(); + + //Add state in the ArrayList + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + + //Given index 120, it will throw IndexOutOfBoundsException + ListIterator itr = states.listIterator(120); + + while(itr.hasNext()) { + String state = itr.next(); + System.out.println("The state :"+ state); + } + } +} +``` +Output: +``` +Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 120 + at java.util.ArrayList.listIterator(ArrayList.java:816) + at com.gaurav.ExProject.ArrayList.ArrayListListIteratorException.main(ArrayListListIteratorException.java:27) +``` + +## Conclusion + +We have seen a `listIterator()` method of the ArrayList class. This method returns an iterator over the elements of the ArrayList in proper sequence. + +```java +public ListIterator listIterator() +``` + +The overloaded version of this method `listIterator(int index)` returns the iterator over elements of the ArrayList, starting from the position specified. i.e `index` + +Both method returns the fail-fast iterator. + +```java +public ListIterator listIterator(int index) +``` +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/arraylist/arraylist-listiterator-method). + +Please write your thoughts in the comment section below. diff --git a/_posts/collections/linkedlist/2022-01-25-linkedlist-in-java.md b/_posts/collections/linkedlist/2022-01-25-linkedlist-in-java.md new file mode 100644 index 0000000..33c74a3 --- /dev/null +++ b/_posts/collections/linkedlist/2022-01-25-linkedlist-in-java.md @@ -0,0 +1,215 @@ +--- +layout: post +title: "LinkedList In Java" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this article, we will see LinkedList in Java. How LinkedList is created? Its various types of constructors for creating a LinkedList object. Also, some important features with their respective example." +--- + +In this article, we will see LinkedList in Java. How LinkedList is created? Its various types of constructors for creating a LinkedList object. Also, some important features with their respective example. + +## Introduction + +The LinkedList class is present in the `java.util` package. LinkedList implements the **List** and **Deque** interfaces and extends the **AbstractSequentialList** class from the Collections. + +LinkedList allows duplicates and a null value. Also, it maintains the insertion order. + +LinkedList implements the Serializable and Cloneable interface. it does not implement the RandomAccess interface. + +LinkedList internally uses a doubly linked list data structure to store the objects. + +Hence, the element stored in the LinkedList acts as a separate object, and every element is connected by its addresses. So inserting and deleting the elements is an easy and efficient operation. And that's why LinkedList is preferred over arrays if our frequent operations are insertions and deletions. + +But as we discussed, every single element acts as a separate object. And it is linked by their addresses. + +We can not move directly to the desired element. First, we need to go to the head element, and then from the head element, we get the address of the next element, and so on till our desired element. + +It makes retrieving operations very inefficient and time-consuming, and that's why LinkedList is not preferred for storing and retrieving operations. + + + +## Constructors in the LinkedList + +LinkedList provides two types of constructors to create a new LinkedList object. + +1. LinkedList() +2. LinkedList(Collection c) + +### 1. LinkedList() + +This constructor constructs an empty List. + +```java +LinkedList list = new LinkedList(); +``` + +### 2.LinkedList(Collection c) + +This constructor constructs a LinkedList containing the elements of the specified collection, in the order they are returned by the collection's iterator. + +```java +List arrayList = new ArrayList(); +arrayList.add("John"); +arrayList.add("Mark"); +arrayList.add("Ruby"); +arrayList.add("Lucy"); + +//It constructs a LinkedList containing elements of the above ArrayList +List linkedList = new LinkedList(arrayList); +``` + +## Methods of the LinkedList + +{:class="table table-bordered"} + +| Methods | Description | +| :----------------------------------------------------------- | ------------------------------------------------------------ | +| [`add(Object o)`](https://coderolls.com/add-element-in-linkedlist/) | Appends the specified element to the end of a list. | +| [`add(int index, Object element)`](https://coderolls.com/add-element-in-linkedlist/) | Inserts the specified element at the specified position index in a list. | +| [`addFirst(E e)`](https://coderolls.com/linkedlist-addfirst-method/) | Inserts the specified element at the beginning of this list. | +| [`addLast(E e)`](https://coderolls.com/linkedlist-addlast-method/) | Inserts the specified element to the end of this list. | +| `size()` | Returns the number of elements in a list | +| [`contains(Object o)`](https://coderolls.com/check-if-linkedlist-contains-an-element/) | Return `true` if the list contains a specified element, else `false`. | +| [`remove()`](https://coderolls.com/remove-element-from-linkedlist/#1-remove) | Retrieves and removes the head (first element) of this list. | +| [`remove(Object o)`](https://coderolls.com/remove-element-from-linkedlist/#2-removeobject-o) | Removes the first occurrence of the specified element in a list. | +| [`remove(int index)`](https://coderolls.com/remove-element-from-linkedlist/#3-removeint-index) | Removes the element at the specified position in this list. | +| [`removeFirst()`](https://coderolls.com/remove-element-from-linkedlist/#4-removefirst) | Removes and returns the first element from this list. | +| [`removeLast()`](https://coderolls.com/remove-element-from-linkedlist/#5-removelast) | Removes and returns the last element from this list. | +| [`get(int index)`](https://coderolls.com/get-an-element-from-linkedlist/#1-getint-index) | Returns the element at the specified position in this list. | +| [`getFirst()`](https://coderolls.com/get-an-element-from-linkedlist/#2-getfirst) | Returns the first element in this list. | +| [`getLast()`](https://coderolls.com/get-an-element-from-linkedlist/#3-getlast) | Returns the last element in this list. | +| [`set(int index, E element)`](https://coderolls.com/set-element-at-an-index-in-linkedlist) | Replaces the element at the specified position in this list with the specified element. | +| [`indexOf(Object o)`](https://coderolls.com/get-an-index-of-element-of-linkedlist/#1-indexofobject-o) | Returns the index in a list of the first occurrence of the specified element, or -1 if the list does not contain specified element. | +| [`lastIndexOf(Object o)`](https://coderolls.com/get-an-index-of-element-of-linkedlist/#2-lastindexofobject-o) | Returns the index in a list of the last occurrence of the specified element, or -1 if the list does not contain specified element. | +| `listIterator(int index)` | Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. | +| [`toArray()`](https://coderolls.com/convert-linkedlist-to-array) | Returns an array containing all of the elements in this list in proper sequence. | +| `subList(int fromIndex, int toIndex)` | Returns a view of the portion of this list between the specified `fromIndex` (inclusive) and `toIndex` (exclusive). | + +## Features + +### 1. LinkedList maintains the insertion order. + +Let's see a simple Java program to prove that LinkedList maintains the insertion order. + +```java +import java.util.LinkedList; +/** + * A Java program to prove that LinkedList maintains insertion order + * @author coderolls.com + * + */ +public class LinkedListInsertionOrder { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("John"); + linkedList.add("Mark"); + linkedList.add("Ruby"); + linkedList.add("Lucy"); + linkedList.add("Vikram"); + + System.out.println(linkedList); + } +} +``` + +Output: + +``` +[John, Mark, Ruby, Lucy, Vikram] +``` + +#### Explanation + +1. I have created an empty LinkedList object `linkedList` of String. +2. I have added a few Strings to the `linkedList` +3. I have printed the `linkedList` object using the sysout statement. We can see the output strings are in the inserted order only. + +### 2. LinkedList allows the duplicate elements. + +I have given a simple java program to prove that LinkedList allows the duplicate elements. + +```java +import java.util.LinkedList; +/** + * A Java program to prove that LinkedList Allows Duplicates + * @author coderolls.com + * + */ +public class LinkedAllowDuplicates { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("John"); + linkedList.add("Mark"); + linkedList.add("Mark"); + linkedList.add("Mark"); + linkedList.add("Ruby"); + linkedList.add("Lucy"); + linkedList.add("Vikram"); + linkedList.add("Vikram"); + + System.out.println(linkedList); + } +} +``` + +Output: + +``` +[John, Mark, Mark, Mark, Ruby, Lucy, Vikram, Vikram] +``` + +#### Explanation + +1. I have created an empty LinkedList object `linkedList` of String. +2. I have added some Strings to the `linkedList`, a few of the String objects are duplicates. +3. I have printed the `linkedList` object using the sysout statement. We can see the output contains duplicate strings. + +### 3. LinkedList allows the null values. + +I have given a simple Java program below to show that LinkedList allows the null values. + +```java +import java.util.LinkedList; +/** + * A Java program to prove that LinkedList Allows null values + * @author coderolls.com + * + */ +public class LinkedAllowDuplicates { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("John"); + linkedList.add(null); + linkedList.add("Mark"); + linkedList.add(null); + linkedList.add("Ruby"); + linkedList.add("Lucy"); + linkedList.add("Vikram"); + linkedList.add(null); + + System.out.println(linkedList); + } +} +``` + +Output: + +``` +[John, null, Mark, null, Ruby, Lucy, Vikram, null] +``` + +#### Explanation + +1. I have created an empty LinkedList object `linkedList` of String. +2. I have added a few Strings to the `linkedList`. Also, I have added a few `null` values too. +3. I have printed the `linkedList` object using the sysout statement. We can see the output contains the null values. + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/linkedlist/linkedlist-in-java). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-03-linkedlist-addfirst-method.md b/_posts/collections/linkedlist/2022-02-03-linkedlist-addfirst-method.md new file mode 100644 index 0000000..9770f85 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-03-linkedlist-addfirst-method.md @@ -0,0 +1,76 @@ +--- +layout: post +title: "How To Add Element At The Beginning Of LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see the addFirst() method of the LinkedList class in Java with an example." +--- + +In this article, we will see the addFirst() method of the LinkedList class in Java with an example. + +## Introduction + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +To insert the elements with ease at the beginning of the LinkedList, the Language Developers have provided the `addFirst()` method. + +## LinkedList `addFirst()` Method + +The addFirst() method will insert the specified element at the beginning of this list. + +The method signature for `addFirst()` method is given below. + +```java +public void addFirst(E e) +``` + +Here, `e` is an element to be added at the beginning of the List. + +The return type of this method is `void`, it means, this method do not return anything. + +I have given a simple Java program for the `addFirst()` method below. + +```java +import java.util.LinkedList; + +public class LinkedListAddFirst { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Austin"); + linkedList.add("Boston"); + linkedList.add("Atlanta"); + linkedList.add("Madison"); + linkedList.add("Columbia"); + + System.out.println(linkedList); + + //Add an element at the beginning + linkedList.addFirst("Albany"); + System.out.println(linkedList); + } + +} +``` + +Output: + +``` +[Austin, Boston, Atlanta, Madison, Columbia] +[Albany, Austin, Boston, Atlanta, Madison, Columbia] +``` + +## Conclusion + +```java +public void addFirst(E e) +``` + +The `addFirst()` method will insert the specified element at the beginning of this list. + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/linkedlist/linkedlist-addfirst-method). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-03-linkedlist-addlast-method.md b/_posts/collections/linkedlist/2022-02-03-linkedlist-addlast-method.md new file mode 100644 index 0000000..c306b63 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-03-linkedlist-addlast-method.md @@ -0,0 +1,73 @@ +--- +layout: post +title: "LinkedList addLast() Method" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see the addLast() method of the LinkedList class in Java with an example." +--- +In this article, we will see the addLast() method of the LinkedList class in Java with an example. + +## Introduction + +LinkedList class is present in the java.util package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +To insert the elements at the end of the LinkedList, we can use the `addLast()` method. + +## LinkedList `addLast()` Method + +The `addLast()` method will insert the specified element at the end of this list. + +The `addLast()` method is equivalent to the add() method. + +The method signature for the `addLast()` method is given below. + +```java +public void addLast(E e) +``` + +The parameter `e` is an element to be added at the end of the List. + +The return type of this method is `void`, which means, this method does not return anything. + +I have given a simple Java program for the `addLast()` method below. + +```java +import java.util.LinkedList; + +public class LinkedListAddLast { + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Austin"); + linkedList.add("Boston"); + linkedList.add("Atlanta"); + linkedList.add("Madison"); + linkedList.add("Columbia"); + + System.out.println(linkedList); + + // add element at the end + linkedList.addLast("Albany"); + System.out.println(linkedList); + } +} +``` +Output: +``` +[Austin, Boston, Atlanta, Madison, Columbia] +[Austin, Boston, Atlanta, Madison, Columbia, Albany] +``` + +## Conclusion + +```java +public void addLast(E e) +``` +The `addLast()` method will insert the specified element at the end of this list. This method is equivalent to the `add()` method. +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/linkedlist/linkedlist-addLast-method). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-04-convert-linkedlist-to-array.md b/_posts/collections/linkedlist/2022-02-04-convert-linkedlist-to-array.md new file mode 100644 index 0000000..31d3ac4 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-04-convert-linkedlist-to-array.md @@ -0,0 +1,198 @@ +--- +layout: post +title: "How To Convert LinkedList To Array In Java?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see how to convert LinkedList to an array." +--- + +In this tutorial, we will see how to convert LinkedList to an array. + +## Introduction + +LinkedList class is present in the java.util package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +Sometimes, we need to convert LinkedList to an array. + +The LinkedList class has a `toArray()` method. We can convert LinkedList to an array using the `toArray()` method. + +**There are two versions of the `toArray()` method** + +1. `public Object[] toArray()` method +2. `public T[] toArray(T[] a)` method + +Let's see both methods one by one. + +## 1. Convert LinkedList To Array Using `public Object[] toArray()` Method + +We can use the `toArray()` method to convert LinkedList to an array. + +The method signature for the `toArray()` method is given below. + +```java +public Object[] toArray() +``` + +**As we can see from the method signature, this method returns an `Object[]` containing all of the elements in this list in proper sequence** + +When the `toArray()` method returns an array, the list does maintain any references to the returned array. And thus elements of the array are free to modify. + +This method acts as a bridge between array-based and collection-based APIs. + +I have given a Java program to convert LinkedList to an array using the `toArray()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to convert LinkedList to an array + * using the toArray() method. + * + * @author coderolls.com + * + */ +public class LinkedListToArray { + + public static void main(String[] args) { + + LinkedList linkedList = new LinkedList(); + linkedList.add("Walmart"); + linkedList.add("Amazon"); + linkedList.add("Apple"); + linkedList.add("Microsoft"); + linkedList.add("Google"); + linkedList.add("Uber"); + linkedList.add("Tesla"); + + System.out.println("Printing the linkedList: "); + System.out.println(linkedList); + + //Convert LinkedList to Object[] + Object[] arr = linkedList.toArray(); + + System.out.println("\nPrinting the object array elements: "); + for(Object obj:arr) { + System.out.println(obj.toString()); + } + } +} +``` + +Output: + +``` +Printing the linkedList: +[Walmart, Amazon, Apple, Microsoft, Google, Uber, Tesla] + +Printing the object array elements: +Walmart +Amazon +Apple +Microsoft +Google +Uber +Tesla +``` + + + +## 2.Convert LinkedList To Array Using `public T[] toArray(T[] a)` Method + +If you want your toArray() method to return a specific type of array, then you can use the `toArray(T[] a)` method. + +The method signature for this method is as given below. + +```java +public T[] toArray(T[] a) +``` + +This method accepts a type `T` array as an input parameter. It returns an array of type `T` containing all of the elements in this list in the proper sequence (from first to last element). + +If the list fits in the specified array, then it returns the same. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. + +If the size of the array is greater than the total size of the list `null` will be added after the last element of the list to the array. + +Please note that `toArray(new Object[0])` is identical in function to `toArray()`. + +I have given a simple Java program to convert LinkedList to an array using the `public T[] toArray(T[] a)` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to convert LinkedList to an array + * using the toArray(T[] a) method. + * + * @author coderolls.com + * + */ +public class LinkedListToArray2 { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Walmart"); + linkedList.add("Amazon"); + linkedList.add("Apple"); + linkedList.add("Microsoft"); + linkedList.add("Google"); + linkedList.add("Uber"); + linkedList.add("Tesla"); + + System.out.println("Printing the linkedList: "); + System.out.println(linkedList); + + //Convert LinkedList to String array + String[] arr = linkedList.toArray(new String[linkedList.size()]); + + System.out.println("\nPrinting the String array elements: "); + for(String str:arr) { + System.out.println(str); + } + } +} +``` + +Output: + +``` +Printing the linkedList: +[Walmart, Amazon, Apple, Microsoft, Google, Uber, Tesla] + +Printing the String array elements: +Walmart +Amazon +Apple +Microsoft +Google +Uber +Tesla +``` + +## Conclusion + +We can use the LinkedList `toArray()` method to convert LinkedList to an array. + +There are two overloaded versions of this method + +1. `public Object[] toArray()` method - Returns an Object array + +```java +// convert linkedList to Object[] +Object[] arr = linkedList.toArray(); +``` + +2. `public T[] toArray(T[] a)` method - Returns a specific type of array + +```java +// convert linkedList to String array +String[] arr = linkedList.toArray(new String[linkedList.size()]); +``` + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/linkedlist/convert-linkedlist-to-array). + +Let me know you thoughts or suggestions on the topic discussed above in comment section below. diff --git a/_posts/collections/linkedlist/2022-02-05-add-element-in-linkedlist.md b/_posts/collections/linkedlist/2022-02-05-add-element-in-linkedlist.md new file mode 100644 index 0000000..3e9ae09 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-05-add-element-in-linkedlist.md @@ -0,0 +1,164 @@ +--- +layout: post +title: "How To Add Element To LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this article, we will see, how to add an element to LinkedList. The LinkedList class provide various methods to add an element to the LnikedList. We will cover these methods with examples." +--- + +In this article, we will see, how to add an element to LinkedList. The LinkedList class provide various methods to add an element to the LnikedList. We will cover these methods with examples. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses doubly LinkedList for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +We can add an element to the LinkedList using the `add()` method. There are two types of the `add()` method. + +1. `add(E e)` +2. `add(int index,E element)` +2. addFirst(E e) +2. addLast(E e) + +The `add()` method will append an element to the end of the list. The `add(int index, E element)` method will add the element at the specified index `index`. + +Since LinkedList internally use a doubly LinkedList structure to store data, it provides two additional methods to add the elements using `addFirst(E e)` and `addLast(E e)` + +Let's see both the methods one by one. + +## 1. `add(E e)` + +The method signature for this is given below, + +`public boolean add(E e)`. + +This method appends the specified element `e` to the end of the list. + +This method returns `true` if the element is added to the list otherwise, it returns `false`. + +I have given a Java program to add an element to the end of the list using the `add(E e)` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to add an element to the LinkedList. + * + * The add(E e) method will add an element to + * the end of the LinkedList. + * + * @author coderolls.com + * + */ +public class LinkedListAddExample { + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + + //Adding elements to the LinkedList + linkedList.add("John"); + linkedList.add("Peter"); + + System.out.println(linkedList);// [John, Peter] + + //Adding an element to the LinkedList + //Element will be added to the end of the LinkedList + linkedList.add("Noah"); + + System.out.println(linkedList); // [John, Peter, Noah] + } +} +``` + +Output: + +``` +[John, Peter] +[John, Peter, Noah] +``` + +## 2. `add(int index, E element)` + +The method signature for this method is given below. + +````java +public void add(int index, E element) +```` + +This method adds the specified element `element` at the specified index `index`. + +This method has a return type as `void` so, it will not return anything. + +Below, we will see a Java program to add an element at the specified index in LinkedList. + +```java +import java.util.LinkedList; + +/** + * A Java program to add an element to the LinkedList + * at the specific index. + * + * The add(int index, E element) method will add + * an element at the specified index in LinkedList. + * + * @author coderolls.com + * + */ +public class LinkedListAddExample2 { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + + //adding elements to the linkedList using the normal add method + linkedList.add("John"); + linkedList.add("Peter"); + linkedList.add("Karan"); + + System.out.println(linkedList);// [John, Peter, Karan] + + // adding an element to the LinkedList at index 1 + linkedList.add(1, "Noah"); + + System.out.println(linkedList); // [John, Noah, Peter, Karan] + } +} +``` + +Output: + +``` +[John, Peter, Karan] +[John, Noah, Peter, Karan] +``` + + + +## 3. [`addFirst(E e)`](https://coderolls.com/linkedlist-addfirst-method/) + +We know that LinkedList internally uses the doubly linkedlist structure to store the data. To provide features like a doubly LinkedList, the LinkedList class has a special [`addFirst(E e)`](https://coderolls.com/linkedlist-addfirst-method/) method to add the element at the beginning of the list. + +I have written a separate detailed article about the [`addFirst(E e)`](https://coderolls.com/linkedlist-addfirst-method/) method. Read [How To Add Element At The Beginning Of LinkedList?](https://coderolls.com/linkedlist-addfirst-method/) + +## 4. [`addLast(E e)`](https://coderolls.com/linkedlist-addlast-method/) + +We know that LinkedList internally uses the doubly linkedlist structure to store the data. To provide features like a doubly linkedlist, the LinkedList class has a special [`addLast(E e)`](https://coderolls.com/linkedlist-addlast-method/) method to add the element to the end of the list. + +This method is equivalent to the `add(E e)` method. + +I have written a separate detailed article about the [`addLast(E e)`](https://coderolls.com/linkedlist-addlast-method/) method. Read [LinkedList addLast(E e) Method](https://coderolls.com/linkedlist-addlast-method/) + +## Conclusion + +We can add an element to the [LinkedList](https://coderolls.com/linkedlist-in-java/) using the `add()` method in two ways. + +1. `add(E e)` - It will add an element to the end of the LinkedList +2. `add(int index, E element)`- This method will add an element to the specified index +2. [`addFirst(E e)`](https://coderolls.com/linkedlist-addfirst-method/) - This method will add an element at the beginning of the list +2. [`addLast(E e)`](https://coderolls.com/linkedlist-addlast-method/) - This method will add an element to the end of the list + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/add-element-in-linkedlist). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-06-remove-element-from-linkedlist.md b/_posts/collections/linkedlist/2022-02-06-remove-element-from-linkedlist.md new file mode 100644 index 0000000..e1df17c --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-06-remove-element-from-linkedlist.md @@ -0,0 +1,378 @@ +--- +layout: post +title: "How To Remove Element From LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this article, we will see, how to remove an element from the LinkedList. The LinkedList class provide various methods to remove an element from the LinkedList. We will cover these methods with examples." +--- + +In this article, we will see, how to remove an element from the LinkedList. The LinkedList class provide various methods to remove an element from the LnikedList. We will cover these methods with examples. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses doubly LinkedList for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +The LinkedList class has the following methods to remove the object from the LinkedList. + +1. `remove()` +2. `remove(Object o)` +3. `remove(int index)` +4. `removeFirst()` +5. `removeLast()` + +Let's see all these methods one by one. + +## 1. `remove()` + +The `remove()` method **retrieves and removes the head (first element) of this list**. + +The method signature for the `remove()` method is given below. + +```java +public E remove() +``` + +This method **returns the head(first element) of this list**. And it does not accept any parameter. + +I have given a sample Java program to remove an element from the list using the `remove()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to remove a head element from + * the linkedList using the remove() method. + * + * @author coderolls.com + * + */ +public class LinkedListRemove { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + + linkedList.add("BHIM"); + linkedList.add("PayTM"); + linkedList.add("Freecharge"); + linkedList.add("PhonePe"); + linkedList.add("JioPay"); + + System.out.println("LinkedList before removing an element:"); + System.out.println(linkedList); + + // removes head(first element) i.e. removes BHIM + linkedList.remove(); + + System.out.println("\nLinkedList after removing an element using remove() method:"); + System.out.println(linkedList); + } +} +``` + +Output: + +``` +LinkedList before removing an element: +[BHIM, PayTM, Freecharge, PhonePe, JioPay] + +LinkedList after removing an element using remove(): +[PayTM, Freecharge, PhonePe, JioPay] +``` + +### Exceptions + +The `remove()` method throws [`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) if this list is empty. + +## 2. `remove(Object o)` + +The `remove(Object o)` method **removes the first occurrence of the specified element in a list, if it is present**. + +If the list does not contain the specified element, there will be no change in the list. + +The method signature for the `remove(Object o)` method is given below. + +```java +public boolean remove(Object o) +``` + +This method accepts a parameter Object `o`, which needs to be removed from the list. + +This method **returns a boolean value**. It will return **`true`** if the list got changed as a result of this method call, otherwise **`false`**. + +I have given a sample Java program to remove an element from the list using the `remove(int index)` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to remove the specified element from + * the linkedList using the remove(Object o) method. + * + * @author coderolls.com + * + */ +public class LinkedListRemoveObject { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + + linkedList.add("BHIM"); + linkedList.add("PayTM"); + linkedList.add("Freecharge"); + linkedList.add("PhonePe"); + linkedList.add("JioPay"); + + System.out.println("LinkedList before removing an element:"); + System.out.println(linkedList); + + // removes the specified element i.e. removes Freecharge + linkedList.remove("Freecharge"); + + System.out.println("\nLinkedList after removing an element using the remove(Object o) method:"); + System.out.println(linkedList); + } +} +``` + +Output: + +``` +LinkedList before removing an element: +[BHIM, PayTM, Freecharge, PhonePe, JioPay] + +LinkedList after removing an element using the remove(Object o) method: +[BHIM, PayTM, PhonePe, JioPay] +``` + +### Exceptions + +The `remove()` method throws [`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) if this list is empty. + +## 3. `remove(int index)` + +The `remove(int index)` method **removes the element at the specified position (`index`) in this list.** + +Once, this method removes the element, it shifts any subsequent elements to the left (subtracts one from their indices). + +The method signature for the `remove(Object o)` method is given below. + +```java +public E remove(int index) +``` + +This method **returns the element that was removed from the list**. + +I have given a sample Java program to remove an element from the list using the `remove(int index)` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to remove elements at the specified position i.e. index + * from the linkedList using the remove(int index) method. + * + * @author coderolls.com + */ +public class LinkedListRemoveObjectByIndex { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("BHIM"); + linkedList.add("PayTM"); + linkedList.add("Freecharge"); + linkedList.add("PhonePe"); + linkedList.add("JioPay"); + + System.out.println("LinkedList before removing an element:"); + System.out.println(linkedList); + + // removes the element at index 3 i.e. removes PhonePe + linkedList.remove(3); + + System.out.println("\nLinkedList after removing an element using the remove(int index) method:"); + System.out.println(linkedList); + } +} +``` + +Output: + +``` +LinkedList before removing an element: +[BHIM, PayTM, Freecharge, PhonePe, JioPay] + +LinkedList after removing an element using the remove(int index) method: +[BHIM, PayTM, Freecharge, JioPay] +``` + +### Exceptions + +The `remove(int index)` method throws [`IndexOutOfBoundsException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html) - if the index is out of range (`index < 0 || index >= size()`) + +## 4. `removeFirst()` + +The `removeFirst()` method **removes and returns the first element from this list**. + +The method signature for the `remove(Object o)` method is given below. + +```java +public E removeFirst() +``` + +This method does not accept any parameter and it will **return the first element from this list**. + +I have given a sample Java program to remove the first element from the list using the `removeFirst()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to remove the first element from + * the linkedList using the removeFirst() method. + * + * @author coderolls.com + * + */ +public class LinkedListRemoveFirst { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("BHIM"); + linkedList.add("PayTM"); + linkedList.add("Freecharge"); + linkedList.add("PhonePe"); + linkedList.add("JioPay"); + + System.out.println("LinkedList before removing an element:"); + System.out.println(linkedList); + + // removes first element i.e. removes BHIM + linkedList.removeFirst(); + + System.out.println("\nLinkedList after removing an element using the removeFirst() method:"); + System.out.println(linkedList); + } +} +``` + +Output: + +``` +LinkedList before removing an element: +[BHIM, PayTM, Freecharge, PhonePe, JioPay] + +LinkedList after removing an element using the removeFirst() method: +[PayTM, Freecharge, PhonePe, JioPay] +``` + +### Exceptions + +The `remove()` method throws [`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) if this list is empty. + +## 5. `removeLast()` + +The `removeLast()` method **removes and returns the last element from this list.** + +The method signature for the `removeLast()` method is given below. + +```java +public E removeLast() +``` + +This method does not accept any parameter and it will **return the last element from this list**. + +I have given a sample Java program to remove the last element from the list using the `removeLast()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to remove the last element from + * the linkedList using the removeLast() method. + * + * @author coderolls.com + * + */ +public class LinkedListRemoveLast { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("BHIM"); + linkedList.add("PayTM"); + linkedList.add("Freecharge"); + linkedList.add("PhonePe"); + linkedList.add("JioPay"); + + System.out.println("LinkedList before removing an element:"); + System.out.println(linkedList); + + // removes first element i.e. removes BHIM + linkedList.removeLast(); + + System.out.println("\nLinkedList after removing an element using the removeLast() method:"); + System.out.println(linkedList); + } +} +``` + +Output: + +``` +LinkedList before removing an element: +[BHIM, PayTM, Freecharge, PhonePe, JioPay] + +LinkedList after removing an element using the removeLast() method: +[BHIM, PayTM, Freecharge, PhonePe] +``` + +### Exceptions + +The `remove()` method throws [`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) if this list is empty. + +## Conclusion + +In the above tutorial, I have shared 5 methods to remove an element from the LinkedList. These 5 methods are as given below. + +1. `remove()` - Retrieves and removes the head (first element) of this list. + + ```java + //head (First element) will be removed from the LinkedList + linkedList.remove(); + ``` + +2. `remove(Object o)` - Removes the first occurrence of the specified element in a list. + + ```java + //'obj' will be removed form the linkedList + linkedList.remove(obj); + ``` + +3. `remove(int index)` - Removes the element at the specified position in this list. + + ```java + //The element at index 3 will be removed from the LinkedList + linkedList.remove(3); + ``` + +4. `removeFirst()` - Removes and returns the first element from this list. + + ```java + // first element will be removed from the LinkedList + linkedList.removeFirst(); + ``` + +5. `removeLast()` - Removes and returns the last element from this list. + + ```java + // last element will be removed from the LinkedList + linkedList.removeLast(); + ``` + +--- + +The example java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/remove-element-from-linkedlist). + +Let me know you thoughts or suggestions on the topic discussed above in comment section below. diff --git a/_posts/collections/linkedlist/2022-02-08-check-if-linkedlist-contains-an-element.md b/_posts/collections/linkedlist/2022-02-08-check-if-linkedlist-contains-an-element.md new file mode 100644 index 0000000..b2a2b81 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-08-check-if-linkedlist-contains-an-element.md @@ -0,0 +1,103 @@ +--- +layout: post +title: "How To Check If LinkedList Contains The ELement?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see, how to check if a LinkedList contains a particular element. LinkedList class provide a method to check if the specified element is present in the LinkedList or not. Let's see this method with an example." +--- + +In this short tutorial, we will see how to check if a LinkedList contains a particular element. LinkedList class provides a method to check if the specified element is present in the LinkedList or not. Let's see this method with an example. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +Sometimes we need to check if the element is present in the LinkedList or not. + +LinkedList provides the `contains(Object o)` method to check if the specified element is present in the LinkedList. + +## Check If LinkedList Contains The Elelement Using `contains(Object o)` Method + +The `contains(Object o)` method **returns true, if the list contains the specified element `o`.** + +It will use the `equals()` method to check if the element from the list and the specified object are the same or not. + +The method signature for the `contains()` method is given below. + +```java +public boolean contains(Object o) +``` + +I have given a Java program to check if the element is present in the LinkedList or not. + +```java +import java.util.LinkedList; + +/** + * A Java program to check if the element is present + * in the linkedList using the contains(Object o) method. + * + * @author coderolls.com + * + */ +public class LinkedListContains { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Uber"); + linkedList.add("Ola"); + linkedList.add("Didi"); + linkedList.add("Lyft"); + linkedList.add("Yandex"); + + System.out.println("LinkedList is as follows: \n"+ linkedList); + + //Checks if the linkedList contains "Ola" + //Returns true if present + boolean isOlaPresnet = linkedList.contains("Ola"); // true + + System.out.println("\nCheck if linkedList contains Ola: "+ isOlaPresnet); + + //Checks if the linkedList contains "Grab" + //Returns true if present + boolean isGrabPresnet = linkedList.contains("Grab"); // false + + System.out.println("\nCheck if linkedList contains Grab: "+ isGrabPresnet); + + } +} +``` + +Output: + +``` +LinkedList is as follows: +[Uber, Ola, Didi, Lyft, Yandex] + +Check if LinkedList contains Ola: true + +Check if LinkedList contains Grab: false +``` + +## Conclusion + +```java +public boolean contains(Object o) +``` + +We can use the `contains(Object o)` method to check if the specified element is present in the list or not. + +```java +// checks if the linkedList contains "Grab" +// returns true if present +boolean isGrabPresnet = linkedList.contains("Grab"); +``` + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/remove-element-from-linkedlist). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-09-get-an-element-from-linkedlist.md b/_posts/collections/linkedlist/2022-02-09-get-an-element-from-linkedlist.md new file mode 100644 index 0000000..03135eb --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-09-get-an-element-from-linkedlist.md @@ -0,0 +1,212 @@ +--- +layout: post +title: "How To Get An Element From LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this tutorial, we will see how to get an element from the LinkedList. LinkedList class provides various methods to get an element from the LinkedList. Let's see this method with an example." +--- + +In this tutorial, we will see how to get an element from the LinkedList. LinkedList class provides various methods to get an element from the LinkedList. Let's see this method as an example. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly Linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +LinkedList class provides the following method to an element from the list. + +1. `get(int index)` +2. `getFirst()` +3. `getLast()` + +## 1. `get(int index)` + +The `get(int index)` method **returns the element at the specified position (`index`) in this list.** + +The method signature is given below. + +```java +public E get(int index) +``` + +This method accepts a parameter `index` of type int, an index of the element that needs to be returned. + +I have given a Java program below to get an element from the LinkedList using the `get(int index) `method. + +```java +import java.util.LinkedList; + +/** + * A Java program to get an element from + * the LinkedList by its index. + * + * @author coderolls.com + */ +public class LinkedListGetElement { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Adidas"); + linkedList.add("Air"); + linkedList.add("Nike"); + linkedList.add("Puma"); + linkedList.add("Reebok"); + + System.out.println("LinkedList: "); + System.out.println(linkedList); + + // get element at index 3 + String element = linkedList.get(3); // Puma + + System.out.println("\nElement at index 3 is "+ element); + } +} +``` + +Output: + +``` +LinkedList: +[Adidas, Air, Nike, Puma, Reebok] + +Element at index 3 is Puma +``` + +## 2. `getFirst()` + +This method **returns the first element in this list.** + +The method signature is given below. + +```java +public E getFirst() +``` + +This method does not accept a parameter. + +I have given a Java program to get an element from the LinkedList using the `getFirst()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to get the first element from + * the linkedlist using getFirst() method. + * + * @author coderolls.com + */ +public class LinkedListGetFirst { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Adidas"); + linkedList.add("Air"); + linkedList.add("Nike"); + linkedList.add("Puma"); + linkedList.add("Reebok"); + + System.out.println("LinkedList: "); + System.out.println(linkedList); + + //Get the first element + String element = linkedList.getFirst(); // Adidas + + System.out.println("\nFirst element of the linkedList is: "+ element); + } +} +``` + +Output: + +``` +LinkedList: +[Adidas, Air, Nike, Puma, Reebok] + +The first element of the linkedList is: Adidas +``` + +## 3. `getLast()` + +This method returns the last element in this list. + +The method signature is given below. + +```java +public E getLast() +``` + +This method does not accept a parameter. + +I have given a Java program to get an element from the LinkedList using the `getFirst()` method. + +```java +import java.util.LinkedList; + +/** + * A Java program to get the last element of + * the linkedlist using getLast() method. + * + * @author coderolls.com + */ +public class LinkedListGetLast { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("Adidas"); + linkedList.add("Air"); + linkedList.add("Nike"); + linkedList.add("Puma"); + linkedList.add("Reebok"); + + System.out.println("LinkedList: "); + System.out.println(linkedList); + + //Get the first element + String element = linkedList.getLast(); // Adidas + + System.out.println("\nThe last element of the linkedList is: "+ element); + } +} +``` + +Output: + +``` +LinkedList: +[Adidas, Air, Nike, Puma, Reebok] + +The last element of the linkedList is: Reebok +``` + +## Conclusion + +The LinkedList class provides the following method to get an element from the LinkedList. + +1. `get(int index)` + + ```java + //Get an element at index 3 + String element = linkedList.get(3); + ``` + +2. `getFirst()` + + ```java + //Get the first element + String element = linkedList.getFirst(); + ``` + +3. `getLast()` + + ```java + //Get the last element + String element = linkedList.getLast(); + ``` + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/get-an-element-from-linkedlist). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-09-get-an-index-of-element-of-linkedlist.md b/_posts/collections/linkedlist/2022-02-09-get-an-index-of-element-of-linkedlist.md new file mode 100644 index 0000000..31c5731 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-09-get-an-index-of-element-of-linkedlist.md @@ -0,0 +1,185 @@ +--- +layout: post +title: "How To Get An Index of the Element Of LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this tutorial, we will see how to get an index of the element of the LinkedList. LinkedList class provides various methods to get an index of the element of the LinkedList. Let's see this method with an example." +--- + +In this tutorial, we will see how to get an index of the element from the LinkedList. LinkedList class provides various methods to get an index of the element of the LinkedList. Let's see this method as an example. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly LinkedList for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +The LinkedList class provides the following method to an element from the list. + +1. `indexOf(Object o)` +2. `lastIndexOf(Object o)` + +## 1. `indexOf(Object o)` + +The `indexOf(Object o)` method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. + +The method signature is given below. + +```java +public int indexOf(Object o) +``` + +This method uses the `equals()` method to check the equality of the element from linkedList and the specified element as a parameter. + +I have given a Java program to get an index of the element of the LinkedList below. + +```java +import java.util.LinkedList; + +/** + * A Java program to get the first index of the element from + * the linkedlist using indexOf(Object o) method. + * + * @author coderolls.com + */ +public class LinkedListIndexOf { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("PepsiCo"); + linkedList.add("DrPepper"); + linkedList.add("GoldSpot"); + linkedList.add("GoldSpot"); + linkedList.add("CocaCola"); + linkedList.add("Moxie"); + linkedList.add("GoldSpot"); + linkedList.add("Moxie"); + + System.out.println("LinkedList: "); + System.out.println(linkedList); + + //Get the first index of GoldSpot + int index = linkedList.indexOf("DrPepper"); // 1 + + System.out.println("\nThe index of the DrPepper in linkedList is: "+ index); + + // get first index of GoldSpot + int indexGS = linkedList.indexOf("GoldSpot"); // 2 + + System.out.println("\nThe index of the GoldSpot in linkedList is: "+ indexGS); + + //Get the first index of Moxie + int indexMoxie = linkedList.indexOf("Moxie"); // 5 + + System.out.println("\nThe index of the Moxie in linkedList is: "+ indexMoxie); + } +} +``` + +Output: + +``` +LinkedList: +[PepsiCo, DrPepper, GoldSpot, GoldSpot, CocaCola, Moxie, GoldSpot, Moxie] + +The index of the DrPepper in linkedList is: 1 + +The index of the GoldSpot in linkedList is: 2 + +The index of the Moxie in linkedList is: 5 +``` + +## 2. `lastIndexOf(Object o)` + +The `lastIndexOf(Object o)` method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. + +The method signature for the `lastIndexOf(Object o)` method is given below. + +```java +public int lastIndexOf(Object o) +``` + +This method uses the `equals()` method to check the equality of the element from linkedList and the specified element as a parameter. + +I have given a Java program to get the last index of the element of the LinkedList below. + +```java +import java.util.LinkedList; + +/** + * A Java program to get the last index of the element from + * the linkedlist using lastIndexOf(Object o) method. + * + * @author coderolls.com + */ +public class LinkedListLastIndexOf { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("PepsiCo"); + linkedList.add("DrPepper"); + linkedList.add("GoldSpot"); + linkedList.add("GoldSpot"); + linkedList.add("CocaCola"); + linkedList.add("Moxie"); + linkedList.add("GoldSpot"); + linkedList.add("Moxie"); + + System.out.println("LinkedList: "); + System.out.println(linkedList); + + //Get the last index of GoldSpot + int index = linkedList.lastIndexOf("DrPepper"); // 1 + + System.out.println("\nThe last index of the DrPepper in linkedList is: "+ index); + + //Get the last index of GoldSpot + int indexGS = linkedList.lastIndexOf("GoldSpot"); // 6 + + System.out.println("\nThe last index of the GoldSpot in linkedList is: "+ indexGS); + + //Get the last index of Moxie + int indexMoxie = linkedList.lastIndexOf("Moxie"); // 7 + + System.out.println("\nThe last index of the Moxie in linkedList is: "+ indexMoxie); + } +} +``` +Output: +``` +LinkedList: +[PepsiCo, DrPepper, GoldSpot, GoldSpot, CocaCola, Moxie, GoldSpot, Moxie] + +The last index of the DrPepper in linkedList is: 1 + +The last index of the GoldSpot in linkedList is: 6 + +The last index of the Moxie in linkedList is: 7 +``` + +## Conclusion + +We can use the method to get an index of the elements from the LinkedList. + +1. `indexOf(Object o)` - returns the index of the first occurrence of the specified element in this list + + ```java + //Get the first index of GoldSpot from the LinkedList + int index = linkedList.indexOf("GoldSpot"); + ``` + +2. `lastIndexOf(Object o)` - returns the index of the last occurrence of the specified element in this list + + ```java + //Get the last index of GoldSpot from the LinkedList + int index = linkedList.lastIndexOf("GoldSpot"); + ``` + +Both method returns -1 if the specified element is not present in the LinkedList. + +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/get-an-index-of-element-of-linkedlist). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-14-set-element-at-an-index-in-linkedlist.md b/_posts/collections/linkedlist/2022-02-14-set-element-at-an-index-in-linkedlist.md new file mode 100644 index 0000000..c455521 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-14-set-element-at-an-index-in-linkedlist.md @@ -0,0 +1,107 @@ +--- +layout: post +title: "How To Set An Element At A Particular Index In LinkedList?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see how to set an element at a particular index in linkedList." +--- + +In this short tutorial, we will see how to set an element at a particular index in linkedList. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +Whenever we want to set an element at a particular index in the LinkedList, we can use the `set(int index, E element)` method. + +## Set An Element Using `set(int index, E element)` Method + +LinkedList class provides the `set(int index, E element)` method to set an element at a particular index in the LinkedList. This method replaces the existing element with the specified element (`element`) at the specified index (`index`). + +The method signature is given below. + +```java +public E set(int index,E element) +``` + +This method accepts two parameters as given below. + +**Parameters:** + +`index` - index of the element to replace + +`element` - element to be stored at the specified position + +This method returns **the element previously at the specified position.** + +I have given a Java program to set an element at a particular index in LinkedList. + +```java +import java.util.LinkedList; + +/** + * A Java program to set an element at the specified index + * using the set(int index, E element) method. + * + * @author coderolls.com + */ +public class LinkedListSet { + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + + linkedList.add("IN"); + linkedList.add("US"); + linkedList.add("FR"); + linkedList.add("JP"); + linkedList.add("CN"); + linkedList.add("RU"); + + System.out.println("LinkedList before setting an element at index 4:"); + System.out.println(linkedList); + + // replaces CN with BR + // returns the previously present element at index 4 i.e CN + String previousElement = linkedList.set(4, "BR"); + + System.out.println("\nLinkedList after setting an element BR at index 4:"); + System.out.println(linkedList); + + System.out.println("\nPreviously present element at index 4:"); + System.out.println(previousElement); + } +} +``` +Output: +``` +LinkedList before setting an element at index 4: +[IN, US, FR, JP, CN, RU] + +LinkedList after setting an element BR at index 4: +[IN, US, FR, JP, BR, RU] + +Previously present element at index 4: +CN +``` + +## Conclusion + +```java +public E set(int index,E element) +``` +We can use the `set(int index, E element)` method to set an element at a particular index in the LinkedList. + +```java +// replaces the element at index 4 with "BR" +// returns the previously present element at index 4 +linkedList.set(4, "BR"); +``` +This method **replaces the element at the specified position in this list with the specified element.** +--- + +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/set-element-at-an-index-in-linkedlist). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-15-iterate-linkedlist-in-java.md b/_posts/collections/linkedlist/2022-02-15-iterate-linkedlist-in-java.md new file mode 100644 index 0000000..c21c9df --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-15-iterate-linkedlist-in-java.md @@ -0,0 +1,386 @@ +--- +layout: post +title: "How To Iterate LinkedList In Java?" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this tutorial, we will see how to iterate LinkedList in Java. There are multiple ways to iterate such as loops, using Iterator or using Java 8 syntax. Let's see these ways to iterate over LinkedList in Java." +--- + +In this tutorial, we will see how to iterate LinkedList in Java. There are multiple ways to iterate such as loops, using Iterator or using Java 8 syntax. Let's see these ways to iterate over LinkedList in Java. + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly LinkedList for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +There are multiple ways to iterate over the LinkedList. We will see the following ways + +1. Iterate the LinkedList using basic for loop +2. Iterate the LinkedList using Enhanced For Loop i.e. For-each loop +3. Iterate the LinkedList using the while loop +4. Iterate the LinkedList using Iterator +5. Iterate the LinkedList using Java 8 the forEach() Method + +So let's see all the options one by one. + +## 1. Iterate the LinkedList using basic for-loop + +We can write a simple for loop for the LinkedList and access the elements of the LinkedList using the `get(int index)` method. + +Please refer to the following Java example to iterate over LinkedList using the basic for loop. + +```java +import java.util.LinkedList; +import java.util.List; + +/** + * A Java program to iterate over LinkedList + * using the basic for loop. + * + * @author coderolls.com + * + */ +public class LinkedListForLoop { + + public static void main(String[] args) { + List linkedList = new LinkedList(); + linkedList.add("Mango"); + linkedList.add("Banana"); + linkedList.add("Grapes"); + linkedList.add("Watermelon"); + linkedList.add("Apple"); + linkedList.add("Avocado"); + + System.out.println("Iterating through LinkedList using the basic for loop!\n"); + + int len = linkedList.size(); + + // iterate over linkedList using basic for loop + for (int i = 0; i < len; i++) { + + // get String object from linkedList at index i + String str = linkedList.get(i); + System.out.println("The object from the LinkedList at " + i + " is " + str); + } + } +} +``` +Output: +``` +Iterating through LinkedList using the basic for loop....... + +The object from the LinkedList at 0 is Mango +The object from the LinkedList at 1 is Banana +The object from the LinkedList at 2 is Grapes +The object from the LinkedList at 3 is Watermelon +The object from the LinkedList at 4 is Apple +The object from the LinkedList at 5 is Avocado +``` + + + +## 2. Iterate the LinkedList using Enhanced For Loop i.e. For-each loop + +Here we will use the [foreach loop i.e. Enhanced For Loop](https://coderolls.com/for-each-loop/) to iterate through ArrayList. + +Let us understand the syntax for the Enhanced For Loop. + +```java +for(DataType item:Array | Collection){ +// operate on the item here +} +``` + +Please refer to the following Java program to iterate over LinkedList using the [foreach loop](https://coderolls.com/for-each-loop/). + +```java +import java.util.LinkedList; +import java.util.List; + +/** + * A Java program to iterate over LinkedList + * using the foreach loop. + * + * @author coderolls.com + * + */ +public class LinkedListForeachLoop { + + public static void main(String[] args) { + List linkedList = new LinkedList(); + + linkedList.add("Mango"); + linkedList.add("Banana"); + linkedList.add("Grapes"); + linkedList.add("Watermelon"); + linkedList.add("Apple"); + linkedList.add("Avocado"); + + System.out.println("Iterating through LinkedList using the foreach loop!\n"); + + // iterate over linkedList using for-each loop + for (String str: linkedList) { + System.out.println("The object from the LinkedList is "+str); + } + } +} +``` + +Output: + +``` +Iterating through LinkedList using the for-each loop! + +The object from the LinkedList is Mango +The object from the LinkedList is Banana +The object from the LinkedList is Grapes +The object from the LinkedList is Watermelon +The object from the LinkedList is Apple +The object from the LinkedList is Avocado +``` + +## 3. Iterate the LinkedList using the while loop + +Similar to the for and for-each loop, we can also use the while loop to iterate over LinkedList. + +I have given a Java program below to iterate over LinkedList using the while loop. + +```java +/** + * A Java program to iterate over LinkedList + * using the while loop. + * + * @author coderolls.com + * + */ +public class LinkedListWhileLoop { + + public static void main(String[] args) { + + List linkedList = new LinkedList(); + + linkedList.add("Mango"); + linkedList.add("Banana"); + linkedList.add("Grapes"); + linkedList.add("Watermelon"); + linkedList.add("Apple"); + linkedList.add("Avocado"); + + System.out.println("Iterating through LinkedList using the while loop!\n"); + + int len = linkedList.size(); + + // iterate over linkedList using the while loop + int i =0; + + while(i linkedList = new LinkedList(); + linkedList.add("Mango"); + linkedList.add("Banana"); + linkedList.add("Grapes"); + linkedList.add("Watermelon"); + linkedList.add("Apple"); + linkedList.add("Avocado"); + System.out.println("Iterating through LinkedList using Iterator interface........\n"); + + // getting an iterator + Iterator iterator = linkedList.iterator(); + + // hasNext() returns true only if the object is available at the next call + while (iterator.hasNext()) { + // next() returns the object, we can cast it to the required type + String str = iterator.next(); + System.out.println("The object from the LinkedList is " + str); + } + } +} +``` + +Output: + +``` +Iterating through LinkedList using Iterator interface........ + +The object from the LinkedList is Mango +The object from the LinkedList is Banana +The object from the LinkedList is Grapes +The object from the LinkedList is Watermelon +The object from the LinkedList is Apple +The object from the LinkedList is Avocado +``` + +**Note:** It is always recommended to use the `Iterator.remove()` method for removing an element from a list while iterating on it. Also, we have the `remove()` method in the LinkedList class, if you use the `LinkedList.remove()` method to remove an element while iterating over the list, you will get the `ConcurrentModificationException`. + +## 5. Iterate the LinkedList using ListIterator + +I have written a detailed article on the ListIterator method of the LinkedList class. Read [LinkedList listIterator() method in Java](https://coderolls.com/linkedlist-listiterator/) + +## 6. Iterate the LinkedList using Java 8 `forEach()` Method + +In Java 8, we got the new `forEach()` method to iterator over collections. + +Inside the `forEach()` method, we can write the lambda expression for the Consumer functional interface. + +I have given a sample Java program below to iterate over the LinkedList using the `forEach()` method. + +```java +import java.util.LinkedList; +import java.util.List; + +/** + * A Java program to iterate over LinkedList + * using the java 8 forEach() method. + * + * @author coderolls.com + */ +public class LinkedListForEachMethod { + + public static void main(String[] args) { + List linkedList = new LinkedList(); + linkedList.add("Mango"); + linkedList.add("Banana"); + linkedList.add("Grapes"); + linkedList.add("Watermelon"); + linkedList.add("Apple"); + linkedList.add("Avocado"); + + System.out.println("Iterating through LinkedList using forEach method and lamda expression........\n"); + + //Add lambda expression in the forEach() method + linkedList.forEach(s -> System.out.println("The object from the LinkedList is " + s)); + } +} +``` +Output: +``` +Iterating through LinkedList using forEach method and lambda expression........ + +The object from the LinkedList is Mango +The object from the LinkedList is Banana +The object from the LinkedList is Grapes +The object from the LinkedList is Watermelon +The object from the LinkedList is Apple +The object from the LinkedList is Avocado +``` + +## Conclusion + +We can iterate over ArrayList using the following ways. + +1. Iterating the ArrayList using basic for loop + + ```java + int len = linkedList.size(); + for (int i = 0; i < len; i++) { + String str = linkedList.get(i); + System.out.println("Object form the LinkedList at " + i + " is " + str); + } + ``` + +2. Iterating the ArrayList using Enhanced For Loop i.e. For-each loop + + ```java + for (String str: linkedList) { + System.out.println("Object form the LinkedList is "+str); + } + ``` + +3. Iterating the ArrayList using a while loop + + ```java + int len = linkedList.size(); + int i =0; + + while(i iterator = linkedList.iterator(); + + while (iterator.hasNext()) { + String str = iterator.next(); + System.out.println("Object form the LinkedList is " + str); + } + ``` + +5. Iterating the ArrayList using ListIterator- I have written a detailed article on the ListIterator method of the LinkedList class. Read [LinkedList listIterator() method in Java](https://coderolls.com/linkedlist-listiterator/) + +6. Iterating the ArrayList using Java 8 forEach() Method + + ```java + linkedList.forEach(s -> System.out.println("Object form the LinkedList is " + s)); + ``` + +--- +The example Java programs given in the above tutorial can be found at [this GitHub Repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/LinkedList/iterate-linkedlist-in-java). + +Let me know your thoughts or suggestions on the topic discussed above in the comment section below. diff --git a/_posts/collections/linkedlist/2022-02-25-linkedlist-listiterator.md b/_posts/collections/linkedlist/2022-02-25-linkedlist-listiterator.md new file mode 100644 index 0000000..d68e304 --- /dev/null +++ b/_posts/collections/linkedlist/2022-02-25-linkedlist-listiterator.md @@ -0,0 +1,150 @@ +--- +layout: post +title: "LinkedList listIterator() method in Java" +author: gaurav +categories: [Collections, LinkedList] +toc: true +description: "In this short tutorial, we will see the listIterator() method of the ArrayList class in Java." +--- + +In this tutorial, we will see the `listIterator()` method of the [LinkedList class in Java](https://coderolls.com/linkedList-in-java/). + +## Introduction + +The LinkedList class is present in the `java.util` package. + +[LinkedList](https:/coderolls.com/linkedlist-in-java/) internally uses a doubly linkedlist for storing the variables. That's why LinkedList is preferred when our frequent operation is insertion and deletion. + +Let's check the `listIterator(int index)` method in LinkedList. + +## LinkedList `listIterator(int index)` method + +This listIterator method returns a fail-fast ListIterator object instance over the elements of this linkedList (in proper sequence), starting from the position specified i.e. `index`. + +The specified index indicates the first element that would be returned by an initial call to [`next`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next--). An initial call to [`previous`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#previous--) would return the element with the specified index minus one. + +The method signature is given below. + +```java +public ListIterator listIterator(int index) +``` + +This method accepts only one parameter i.e `index` of type `int` + +- **`index`**- index of the first element to be returned from the list iterator (by a call to [`next`](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next--)) + +Let's see an example Java program for the `listIterator()` method of the LinkedList. + +```java +import java.util.LinkedList; +import java.util.ListIterator; +/** + * An example Java program about the listIterator(int index) + * method of the linked list. + * + * @author coderolls.com + */ +public class LinkedListListIteratorExample2 { + + public static void main(String[] args) { + LinkedList states = new LinkedList<>(); + //Add state in the LinkedList + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + + //given index 3, the iterator starts from the element with index 3 + ListIterator itr = states.listIterator(3); + + while(itr.hasNext()) { + String state = itr.next(); + System.out.println("The state: "+ state); + } + } +} +``` + +Output: + +``` +Iterating the list from index 3 + +The state: Arizona +The state: Florida +The state: Michigan +The state: New Jersey +The state: Washington +The state: Ohio +``` + +### Exception + +If the entered index is not within the range of LinkedList, we will get `IndexOutOfBoundsException` + +I have given a Java program below which shows the case of the + +```java +import java.util.LinkedList; +import java.util.ListIterator; +/** + * An example Java program about the listIterator() + * method of the linked list. + * + * @author coderolls.com + */ +public class LinkedListListIteratorException { + + public static void main(String[] args) { + LinkedList states = new LinkedList<>(); + //Add state in the LinkedList + states.add("California"); + states.add("Texas"); + states.add("Montana"); + states.add("Arizona"); + states.add("Florida"); + states.add("Michigan"); + states.add("New Jersey"); + states.add("Washington"); + states.add("Ohio"); + + //given index 120, it will throw IndexOutOfBoundsException + ListIterator itr = states.listIterator(120); + + while(itr.hasNext()) { + String state = itr.next(); + System.out.println("The state :"+ state); + } + } +} +``` + +Output: + +``` +Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 120, Size: 9 + at java.util.LinkedList.checkPositionIndex(LinkedList.java:560) + at java.util.LinkedList.listIterator(LinkedList.java:867) + at com.gaurav.ExProject.LinkedList.LinkedListListIteratorException.main(LinkedListListIteratorException.java:29) +``` + +## Conclusion + +This method `listIterator(int index)` returns the iterator over elements of the LinkedList, starting from the position specified. i.e `index` + +Both method returns the fail-fast iterator. + +```java +public ListIterator listIterator(int index) +``` + +--- + +The example Java program used in the above article can be found at [this GitHub repository](https://github.com/coderolls/blogpost-coding-examples/tree/main/collections/linkedlist/linkedlist-listiterator). + +Please write your thoughts in the comment section below. diff --git a/_posts/eclipse/2022-08-06-maven-project.md b/_posts/eclipse/2022-08-06-maven-project.md new file mode 100644 index 0000000..7a813df --- /dev/null +++ b/_posts/eclipse/2022-08-06-maven-project.md @@ -0,0 +1,130 @@ +--- +layout: post +title: "How To Create A Maven Project In Eclipse?" +author: gaurav +categories: [Eclipse, Maven Project] +toc: true +description: "In this tutorial, we will see how to create a maven project in Eclipse." +hidden: false +--- + +In this short tutorial, we will see how to create a maven project in Eclipse. + +## Introduction + +Maven is the most popular build automation tool used to create and manage Java projects. + +Maven helps developers to save time by: + +- Making the build process easy +- Providing a uniform build system +- Providing quality project information +- Encouraging better development practices + +The Eclipse IDE is the most popular IDE for Java. It provides support for the Maven build. + +So, let's check the following step-by-step guide on how to create a maven project in Eclipse. + +## How To Create Maven Project In Eclipse? + +To create a simple maven project in the eclipse, kindly follow the below steps: + +### #Step 1: + +Open eclipse. + +If you are opening the eclipse for the first time in a workspace, you will see a 'Welcome' tab, kindly close it. + +Then click on File>New>Project. + +![Creating A Simple Maven Project In Eclipse](/assets/images/2022-08-06-eclipse-maven-project/001-maven-project.png) + +When you click on the 'project' option you will see the 'New Project' wizard. + +### #Step 2: + +Search 'maven' using the search bar given under 'Wizards' and select the 'Maven Project' option. + +![Selecting A Maven Project In Eclipse](/assets/images/2022-08-06-eclipse-maven-project/002-maven-project.png) + +When you click the 'Next' button on the 'New Project' window, you will see the 'New Maven Project' window. + +### #Step 3: + +In #Step 3, we will keep the default workspace checkbox marked. It will select the default workspace as the project workspace. + +If you want to use any specific workspace, please uncheck the default workspace checkbox and browse the location of your workspace. + +This window also provides the facility to add your project to the existing 'Working Set'. Since we do not have any working set yet, we will keep it as it is. Then click on the 'next' button. + +![Select An Archetype](/assets/images/2022-08-06-eclipse-maven-project/003-maven-project.png) + +The first checkbox is for simple maven project creation. If you check this checkbox, it will skip the maven archetype selection and create a simple maven project for you. + +To explain the archetype selection in the maven project, I am keeping it unchecked. + +### #Step 4: + +Here we need to select an archetype for the maven project. + +Select the 'Catalog' as 'Internal'. And select the archetype as 'maven-archetype-quickstart'. + +![Slecting Project Name and Location](/assets/images/2022-08-06-eclipse-maven-project/004-maven-project.png) + +### #Step 5: + +In the next part of the 'New Maven Project' window, we need to select the 'Group Id' and 'Artifact Id' + + + +**'Group Id':** A Group ID is a unique base name of the company or group that created the project. + +**'Artifact Id':** Artifact Id is a unique name of the project. + + + +I have entered the Group id as 'com.coderolls' and the Artifact id as 'SampleProject'. We will keep the 'Version' value as given there. + +Now you can click on the 'Finish' button and Eclipse will create and build the project for you. + +![Add Group Id and Artifact Id for the Project](/assets/images/2022-08-06-eclipse-maven-project/005-maven-project.png) + +You can see the project structure of your maven project below. + +The `src/main/java` contains the source code and `src/test/java` contains your unit test cases. + +![A Simple Maven Project Structure](/assets/images/2022-08-06-eclipse-maven-project/006-maven-project.png) + +In Maven projects, you can manage your dependencies using the pom.xml file. + +The pom.xml at the beginning looks like the one given below. + +```xml + + 4.0.0 + + com.coderolls + SampleProject + 0.0.1-SNAPSHOT + jar + + SampleProject + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + +``` + +This is how you have created your simple maven project step by step in Eclipse IDE. diff --git a/_posts/git/2019-12-20-basic-git-commands.md b/_posts/git/2019-12-20-basic-git-commands.md index 484d462..d69e031 100644 --- a/_posts/git/2019-12-20-basic-git-commands.md +++ b/_posts/git/2019-12-20-basic-git-commands.md @@ -3,13 +3,14 @@ layout: post title: 8 Basic GIT Commands Every Newbie Developer Must Know author: gaurav image: assets/images/2019-12-20-basic-git-commands/blog-cover.jpg -categories: [ GIT ] -description: GIT is one of the most important parts of the developer's day to day work. So learning GIT is a must for a newbie developer. In this article, you are going to learn the 8 most important basic GIT commands. -featured: true -hidden: true +categories: [GIT, GIT Basic] +description: GIT is one of the most important parts of the developer's day-to-day work. So learning GIT is a must for a newbie developer. In this article, you are going to learn the 8 most important basic GIT commands. +featured: false +hidden: false +toc: true --- -GIT is one of the most important parts of the developer's day to day work. So learning GIT is a must for a newbie developer. In this article, you are going to learn the 8 most important basic GIT commands. +GIT is one of the most important parts of the developer's day-to-day work. So learning GIT is a must for a newbie developer. In this article, you are going to learn the 8 most important basic GIT commands. Below, I have listed down all the 8 commands and then, we will have a look at them one by one. @@ -23,9 +24,9 @@ Below, I have listed down all the 8 commands and then, we will have a look at th 8. [`git push`](#git-push) ## 1. `git init` -`git init` command initializes brand new GIT repository (locally) and begins tracking the existing directory. +`git init` command initializes a brand new GIT repository (locally) and begins tracking the existing directory. -When you hit the `git init` command, git adds a subfolder withing an existing directory that manages all required files for version controlling. +When you hit the `git init` command, git adds a subfolder within an existing directory that manages all required files for version controlling. ``` HP@Gaurav MINGW64 /e/example @@ -36,12 +37,12 @@ HP@Gaurav MINGW64 /e/example (master) $ ``` -You are hitting `git init` means you want to initialize the current directory as GIT repository. - -The following GIF show initializing a new repository and a hidden subfolder containing all data structure required for version control. +You are hitting `git init` means you want to initialize the current directory as a GIT repository. + +The following GIF shows initializing a new repository and a hidden subfolder containing all data structures required for version control. ![GIF showing git init command](/assets/images/2019-12-20-basic-git-commands/git-init.gif) - + ## 2. `git clone` `git clone` creates a local copy of a repository that already exists remotely. The local copy is the exact copy of the remote repository, it contains the same files, history, and branches. @@ -63,7 +64,7 @@ HP@Gaurav MINGW64 /e/directory $ ``` -You can clone any public repository from the platforms like GitHub, BitBucket, GitLab, and other GIT hosting platforms. +You can clone any public repository from platforms like GitHub, BitBucket, GitLab, and other GIT hosting platforms. The following GIF shows the `git clone` command @@ -73,7 +74,7 @@ The following GIF shows the `git clone` command `git add` stages a change. -If you are done with changes in your code then its necessary to stage that changes and take a snapshot of it to include it in the repository's history. +If you are done with changes in your code then it's necessary to stage those changes and take a snapshot of it to include it in the repository's history. `git add` does the first step, it stages a change. @@ -88,21 +89,21 @@ $ git add If you want to stage all the files, then write '.' (dot) after `git add` ``` $ git add . -``` -Any staged changes will become the part of the next snapshot and a part of the repository's history. +``` +Any staged changes will become part of the next snapshot and a part of the repository's history. -You can stage and take a snapshot of the current changes in a single command also but is not recommended. +You can stage and take a snapshot of the current changes in a single command but is not recommended. -Staging your changes first and then taking snapshot gives you complete control over the repository's history. +Staging your changes first and then taking a snapshot gives you complete control over the repository's history. The following GIF shows the `git add` command ![GIF showing git add command](/assets/images/2019-12-20-basic-git-commands/git-add.gif) ## 4. `git commit` - `git commit` save the snapshot to the repository's history. + `git commit` saves the snapshot to the repository's history. -`git add` does the first step i.e. staging the changes and `git commit` does the final step i.e. it saves the snapshot to the repository's history. In GIT these two-step completes the changes tracking process. +`git add` does the first step i.e. staging the changes and `git commit` does the final step i.e. it saves the snapshot to the repository's history. In GIT these two steps complete the changes tracking process. ``` $ git commit -m " @@ -116,7 +117,7 @@ The following GIF shows the `git commit` command ![GIF showing git commit command](/assets/images/2019-12-20-basic-git-commands/git-commit.gif) -It is the simple way to write the commit message but there is a more in-depth way to write a commit message with title and description. We will see that in a separate blogpost. +It is the simple way to write the commit message but there is a more in-depth way to write a commit message with title and description. We will see that in a separate blog post. ## 5. `git status` @@ -147,7 +148,7 @@ The following GIF shows the `git status` command ![GIF showing git status command](/assets/images/2019-12-20-basic-git-commands/git-status.gif) ## 6. `git branch` -`git branch` list the existing branches from the local repository. The current branch will be highlighted in green and marked with an asterisk. +`git branch` lists the existing branches from the local repository. The current branch will be highlighted in green and marked with an asterisk. ``` HP@Gaurav MINGW64 /e/directory/example (master) @@ -164,7 +165,7 @@ The following GIF shows the `git branch` command ## 7. `git pull` -`git pull` update the local repository with updates from its remote counterpart. i.e. remote repository. +`git pull` updates the local repository with updates from its remote counterpart. i.e. remote repository. ``` HP@Gaurav MINGW64 /e/directory/example (master) $ git pull @@ -228,7 +229,7 @@ The following GIF shows the `git push` command You are here means you like the post and hence here is your bonus content. -### How to create a new branch locally +## How to create a new branch locally You can create a new branch locally using the following command ``` @@ -238,6 +239,4 @@ $ git checkout -b ![How to create new branch](/assets/images/2019-12-20-basic-git-commands/git-new-branch.gif) -If you found this article worth, please support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - If you have queries please let me know in the comment section below. diff --git a/_posts/git/2021-05-18-delete-a-git-branch-local-or-remote.md b/_posts/git/2021-05-18-delete-a-git-branch-local-or-remote.md new file mode 100644 index 0000000..dbc910e --- /dev/null +++ b/_posts/git/2021-05-18-delete-a-git-branch-local-or-remote.md @@ -0,0 +1,119 @@ +--- +layout: post +title: "How To Delete A Git Branch (Local or Remote)" +author: gaurav +categories: [GIT, GIT Basic] +toc: true +description: "In this article, we will see how to delete a Git Branch both locally or remotely." +--- +In this article, we will see how to delete a GIT branch both locally or remotely. + +Short Snippet + + +Delete the local branch, if you finished working on a branch, and merged + +```git +git branch -d +``` +Delete the local branch without checking the merged status + +```git +git branch -D +``` +Delete remote branch (Git v1.7.0 and above) + +```git +git push origin --delete +``` + +Delete remote branch (old syntax) +```git +git push origin : +``` + +## Introduction + +GIT is one of the most used software for version control. In GIT, branches are part of the day-to-day development process. A Git branch represents an independent line of development. + +If you are a beginner I would recommend you to have a look at 8 Basic GIT Commands Every Newbie Developer Must Know. + +Usually, all repositories have a `main/master` branch for the main code and team members create a feature or bug fix branches from the `main/master` branch. + +You add your feature or add a bug-fix to your branch commit the changes and push it to the remote branch. You will create a pull request and your team lead will review your code and merge it to the `main/master`. + +Since you have finished working on your branch you can choose to delete it. + +## How To Delete A Local Git Branch? + +When you finished working on the feature or bug fix and your branch is merged to the master, you can use the following command to delete a local GIT branch + +```git +git branch -d +``` +**For example**, If I need to delete my local Git branch `fetaure/add-profile`, I will hit the following command + +```git +git branch -d fetaure/add-profile +``` +When you want to delete a GIT branch without checking the merged status, hit the command given below +```git +git branch -D +``` +**For example**, If I need to delete my local Git branch `fetaure/add-profile` without checking its merged status, I will hit the following command + +```git +git branch -D fetaure/add-profile +``` + +## How To Delete A Remote Git Branch + +If you are using the GIT v1.7.0 and above, hit the following command to delete the remote git branch + +``` + git push --delete +``` + +**Note:** In most of the case the `` is `origin`. + +**For example** If I want to delete my remote `feature/add-profile` branch, I will hit the following command. + +``` +git push origin --delete feature/add-profile +``` + +## Conclusion + +We have seen how we can delete the local and remote branches in GIT. + +If you want to delete the **local branch** +``` + git branch -d +``` +If you want to delete the **remote branch** + +``` +$ git push -d +``` +In most of the cases ` +``` + +### Stage Changes + +Add local changes of a file to the next commit (Stage changes from a file) + +```bash +git add +``` + +Add all local changes to the next commit (Stage all changes from all files) + +```bash +git add . +``` + +### Commit Changes + +Commit (commit previously staged changes) + +```bash +git commit +``` + +The above command will open a Vim prompt to add a commit message title and commit message description. + +If you want to commit without entering the vim prompt, use the below command. + +```bash +git commit -m "" +``` + +How to commit all local changes ( even if they are not staged) + +```bash +git commit -a +``` + +How to make changes in the last commit + +```bash +git commit --amend +``` + +> **Note**: The above command will not amend published commits. + + + +### Stash Changes + +Stash local changes + +```bash +git stash +``` + +Stash local changes with a message + +```bash +git stash save "" +``` + +List all stashes + +```bash +git stash list +``` + +Reapply previously stashed changes + +```bash +git stash apply +``` + +Reapply a particular stash from the list + +```bash +git stash apply stash@{2} +``` + +> `stash@{2}` is stash identifier + +Reapply the latest stashed changes and remove it from your stashes + +```bash +git stash pop +``` + +Reapply a particular stash and remove it from your stashes + +```bash +git stash pop stash@{2} +``` + +> `stash@{2}` is stash identifier + +View a summary of a stash + +```bash +git stash show +``` + +Delete all of your stashes + +```bash +git stash clear +``` + + + +## Commit History + +Show all commits of a repository, the newest first + +```bash +git log +``` + +Show changes over time for a specific file + +```bash +git log +``` + +Check who changed what and when in a specific file + +```bash +git blame +``` + + + +## Branches and Tags + +### Branches + +List all local branches + +```bash +git branch +``` + +List all local and remote branches + +``` +git branch -a +``` + +Switch HEAD branch + +```bash +git checkout +``` + +Create a new branch from the current HEAD branch + +```bash +git branch +``` + +Create a new branch from the current HEAD branch and Switch to new branch + +```bash +git checkout -b +``` + +Create a new tracking branch based on a remote branch + +``` +git checkout --track +``` + +[Delete a local git branch](/delete-a-git-branch-local-or-remote/#how-to-delete-a-local-git-branch) + +```bash +git branch -d +``` + +[Delete a remote git branch](/delete-a-git-branch-local-or-remote/#how-to-delete-a-remote-git-branch) + +```bash +git push --delete +``` + +>**Note:** In most of the cases the `` is `origin`. + +### Tag + +Mark a current commit with tag + +```bash +git tag +``` + + + +## Update and Publish + +List all currently configured remotes +```bash +git remote -v +``` + + +Show information about a remote +```bash +git remote show +``` + + +Add new remote repository +```bash +git remote add +``` + +Change the url of an existing remote repository: + +```bash +git remote set-url +``` + +Download all changes from , but don't integrate into HEAD + +```bash +git fetch +``` + +Download changes and directly merge/integrate into HEAD +```bash +git pull +``` + +Publish local changes on a remote +```bash +git push +``` + +Delete a branch on the remote +```bash +glt branch -dr +``` + +Publish your tags +```bash +git push tags +``` + +> **Note:** In most of the cases the `` is `origin`. + + + +## Merge and Rebase + +Merge into your current HEAD +```bash +git merge +``` + +Rebase your current HEAD onto +```bash +git rebase +``` + +Abort a rebase +```bash +git rebase --abort +``` + +Continue a rebase after resolving conflicts +```bash +git rebase --continue +``` + +Use your configured merge tool to solve conflicts +```bash +git mergetool +``` + +Use your editor to manually solve conflicts and (after resolving) mark the file as resolved + +In case of adding a file + +```bash +git add +``` + +In case of removing the file +```bash +git rm +``` + + + +## Undo + +Discard all local changes in your working directory + +```bash +git reset --hard HEAD +``` + +Discard local changes in a specific file +```bash +git checkout HEAD +``` + +Revert a commit (by producing a new commit with contrary changes) +```bash +git revert +``` + +Reset your HEAD pointer to a previous commit +...and discard all changes since then + +```bash +git reset --hard +``` + +...and preserve all changes as unstaged changes +```bash +git reset +``` + +..and preserve uncommitted local changes +```bash +git reset --keep +``` diff --git a/_posts/groovy/2020-12-31-hello-world-in-groovy.md b/_posts/groovy/2020-12-31-hello-world-in-groovy.md index 8f937e1..cf0b95a 100644 --- a/_posts/groovy/2020-12-31-hello-world-in-groovy.md +++ b/_posts/groovy/2020-12-31-hello-world-in-groovy.md @@ -1,11 +1,12 @@ -ο»Ώ--- +--- layout: post title: "Hello World In Groovy" author: gaurav image: assets/images/2020-12-31/groovy-logo.webp -categories: [ Groovy] -description: "In this article you will say 'Hello' to Groovy. We will see the installation and 'the' most important 'Hello World!' program." +categories: [Groovy] +description: "In this article, you will say 'Hello' to Groovy. We will see the installation and 'the' most important 'Hello World!' program." featured: false +toc: true --- In this article, you will say 'Hello' to Groovy. We will see the installation and 'the' most important "Hello World!" program. πŸ™‚ @@ -21,11 +22,11 @@ Currently, I am using Windows so we will be using a Windows installer, which is Here is a [link for Windows Installer for Groovy 3.0.7](https://bintray.com/groovy/Distributions/download_file?file_path=groovy-3.0.7.msi). -Once you download the .msi file ( i.e. installer) simply double click on it and you will see the installation screen. +Once you download the .msi file ( i.e. installer) simply double-click on it and you will see the installation screen. ![Groovy Installation Screen](/assets/images/2020-12-31/groovy-installation-screen.webp) -The installation is pretty simple and straight-forward. Click on next and go with the default setting. +The installation is pretty simple and straightforward. Click on Next and go with the default setting. **Note:** If you are **using Mac OS** and you have Homebrew, you can install Groovy by the following command. @@ -57,9 +58,9 @@ println "Hello World!" ``` ![Groovy Hello World Program In the Groovy Console](/assets/images/2020-12-31/groovy-hello-world-program-and-run-option.webp) -To run your program right click on the console and choose the 'Run' option. +To run your program right-click on the console and choose the 'Run' option. -You can also use the shortcut `Ctrl+R` to run any groovy program. +You can also use the shortcut `Ctrl+R` to run any Groovy program. Boom!! πŸŽ‰ @@ -72,17 +73,3 @@ So you have successfully written your first groovy program. That's it for now. You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. - --------------- - -You can support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [How To Create UUID in Java?](https://coderolls.com/create-uuid-in-java/) -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) diff --git a/_posts/groovy/2021-05-11-determine-a-datatype-in-groovy.md b/_posts/groovy/2021-05-11-determine-a-datatype-in-groovy.md index c5e149e..7f83e9a 100644 --- a/_posts/groovy/2021-05-11-determine-a-datatype-in-groovy.md +++ b/_posts/groovy/2021-05-11-determine-a-datatype-in-groovy.md @@ -1,9 +1,10 @@ -ο»Ώ--- +--- layout: post title: "Groovy: How To Determine The Datatype Of An Object?" author: gaurav categories: [Groovy] description: "In this quick tutorial, we will how can we determine the datatype of an object in Groovy." +toc: true --- In this quick tutorial, we will see how we can determine the datatype of an object in Groovy. @@ -12,7 +13,7 @@ In this quick tutorial, we will see how we can determine the datatype of an obje When you are writing a Groovy code, sometimes you need to check the datatype of an object. Also, not following the proper naming convention may lead to object datatype confusion. -We will see the best way to check the datatype of an object in groovy so that you can use it correctly in the code. +We will see the best way to check the datatype of an object in Groovy so that you can use it correctly in the code. ## How To Determine The Datatype Of An Object In Groovy? @@ -22,7 +23,7 @@ An example is given below. ```groovy anObject.getClass() ``` -let check the above line program. +let's check the above-line program. ```groovy def names = ['Gaurav', 'Shubham', 'Nayan', 'Sudeep']; @@ -48,7 +49,7 @@ In the above program, we can see that the `names` is an `ArrayList` and `blogna When we call the `getClass()` method on these objects it prints its respective datatype. -In most of the cases you can use the `anObject.getClass()` as `anObject.class`. But if `anObject` is `Map` it will try to retrieve the value with key 'class'. Because of this it is always recommended to use `anObject.getClass()` instead of `anObject.class`. +In most of the cases, you can use the `anObject.getClass()` as `anObject.class`. But if `anObject` is `Map` it will try to retrieve the value with key 'class'. Because of this, it is always recommended to use `anObject.getClass()` instead of `anObject.class`. If you want to check if an object implements a particular interface or extends a particular class (e.g. String, ArrayList, etc), you can use the `instanceof` keyword. @@ -58,7 +59,7 @@ For example, (anObject instanceof String) ``` -Let's check above code in an example program +Let's check the above code in an example program ```groovy def blogname = '''coderolls'''; @@ -70,7 +71,7 @@ Output: true false ``` -See above code as [GitHub Gist](https://gist.github.com/gauravkukade/eafc65547cd3cd54877ca5d54eec8acc) +See the above code as [GitHub Gist](https://gist.github.com/gauravkukade/eafc65547cd3cd54877ca5d54eec8acc) In the above program, I have defined one String `blogname`. I have used the `instanceof` keyword to check if the `blogname` implements the `String` class and it prints `true`. It means the `blogname` is an instance of the `String` class. @@ -96,7 +97,3 @@ That's it about checking the datatype of an object in Groovy. If you know any other way to check the datatype of an object, please comment below to help the community. Thank you. You can check my YouTube channel [here](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w) - -### Related Articles - -- [Hello World In Groovy](https://coderolls.com/hello-world-in-groovy/) diff --git a/_posts/java-basic/2019-11-29-java-introduction.md b/_posts/java-basic/2019-11-29-java-introduction.md index 27dd931..9fbc1c7 100644 --- a/_posts/java-basic/2019-11-29-java-introduction.md +++ b/_posts/java-basic/2019-11-29-java-introduction.md @@ -3,23 +3,24 @@ layout: post title: "Introduction to Java Technology (Language and Platform)" author: gaurav categories: [ Java, Core Java ] -description: "Java is a general purpose computer programming language. Let's get introduce to an amazing programming language." +description: "Java is a general-purpose computer programming language. Let's get introduced to an amazing programming language." featured: false +toc: true --- -Java is a general purpose computer programming language. Let's get introduce to an amazing programming language. +Java is a general-purpose computer programming language. Let's get introduced to an amazing programming language. ## Introduction James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The project was aimed to develop software for a wide variety of network devices and embedded systems. -When the project started they have chosen C++ language, but later they understood the difficulties with C++ and found that these problems could be addressed by creating entirely new simple, reliable, secure language, as a result, the language platform is developed which is simple, secure, distributed, network-based end-user application ranging from worldwide web to the embedded systems. +When the project started they chose C++ language, but later they understood the difficulties with C++ and found that these problems could be addressed by creating an entirely new simple, reliable, and secure language, as a result, the language platform is developed which is simple, secure, distributed, network-based end-user application ranging from worldwide web to the embedded systems. The language was initially called β€˜Oak’ after an oak tree outside the Gosling’s office, then it was as a project Green and finally Java after Java coffee. The Java language compiled code can run on any platform that supports Java, we don’t have to compile Java code again and again. -When we say Java Technology, it is both programming language as well as a platform. +When we say Java Technology, it is both a programming language as well as a platform. Let’s understand Java as a programming language. @@ -33,17 +34,17 @@ We will understand Java by the following simple terms, let’s discuss one by on ### **Simple:** -The primary feature of the Java language is, it is Simple. It means anyone can learn java language without extensive programmer training, it is simple to understand. +The primary feature of the Java language is, that it is Simple. It means anyone can learn Java language without extensive programmer training, it is simple to understand. -The James Gosling designed the Java language syntax on the basis of the C/C++ language, so most of the people are already familiar with it. They can easily migrate from the C/C++ to Java. +James Gosling designed the Java language syntax on the basis of the C/C++ language, so most of people are already familiar with it. They can easily migrate from C/C++ to Java. The fundamental concepts of the Java language can be grasped easily. As a result, it will take very little time to be productive quickly. ### **Object-Oriented:** -To understand object-oriented feature we should understand object technology. In object technology, the classes used to construct the objects and it is intended to be reusable software components. +To understand object-oriented features we should understand object technology. In object technology, the classes used to construct the objects and it is intended to be reusable software components. -The Java programming language is an object-oriented programming language, it means every element in java is an object. Though, there is an exception of primitive data types. +The Java programming language is an object-oriented programming language, it means every element in Java is an object. However, there is an exception for primitive data types. As per the [dept of CS, UTSA](http://www.cs.utsa.edu/~cs3443/ch01.html) @@ -55,21 +56,21 @@ As per the [dept of CS, UTSA](http://www.cs.utsa.edu/~cs3443/ch01.html) We can develop highly reliable software using the Java programming language, it provides both compile time as well as run-time checking. -The extremely simple memory management model makes java robust. +The extremely simple memory management model makes Java robust. The new object is created using a simple β€˜new’ keyword, no explicit programmer-defined pointer datatype, no more pointer, and automatic garbage collection. The unused objects will be collected by the Java garbage collector and will be destroyed carefully. -Automatic memory management concept avoids/eliminate all the errors that previously occur in the C/C++ memory management concern. If any, that can be quickly solved. +The automatic memory management concept avoids/eliminates all the errors that previously occurred in the C/C++ memory management concern. If any, that can be quickly solved. ### **Secure:** -Java technology is developed for distributed environments., so security was always a high priority. Language creators have addressed the concern very well. +Java technology is developed for distributed environments., so security has always been a high priority. Language creators have addressed the concern very well. The application written in the Java programming language is very secure and can not be easily disturbed by the unauthenticated outsider’s code. ### **Architecture neutral:** -Java applications can be deployed on various hardware platforms and so the application should be executed on the various operating system. This is achieved by using the bytecode. +Java applications can be deployed on various hardware platforms so the application should be executed on the various operating systems. This is achieved by using the bytecode. The Java compiler produces the bytecode, that can be executed on the Java virtual machine ( It is a virtual environment, we will discuss the term in detail below) atop of any operating system. @@ -77,13 +78,13 @@ The Java compiler produces the bytecode, that can be executed on the Java virtua Architecture neutrality solves the binary distribution problem as well as the cross-platform problem. Java code is portable, it can be transported easily. -You don’t have to compile java code, again and again, it saves time. +You don’t have to compile Java code, again and again, it saves time. Unlike C, Java programs are the same on every platform. Sizes of the basic data types and arithmetic operators are the same on every platform, there is no database incompatibility. ### **Performance:** -The performance was always in consideration while designing the Java language. The Java garbage collector runs as a low priority thread, which makes memory available whenever required, it leads to better performance. +Performance was always in consideration while designing the Java language. The Java garbage collector runs as a low-priority thread, which makes memory available whenever required, leading to better performance. ### **Multithreaded:** @@ -91,7 +92,7 @@ Java language supports multithreading. You can run multiple tasks simultaneously ## The Java Platform -We are familiar with platforms like Microsoft Windows, Mac OS, Linux distributions. The platform contains hardware as well as software where the code runs. +We are familiar with platforms like Microsoft Windows, Mac OS, and Linux distributions. The platform contains hardware as well as software where the code runs. Unlike others, the Java Platform is a software-only platform. @@ -102,9 +103,9 @@ The Java platform contains ### 1. Java Virtual Machine -The architecture-neutral and portable language platform of Java Technology are called as Java Virtual Machine. +The architecture-neutral and portable language platform of Java Technology is called as Java Virtual Machine. -It is a virtual machine on top of the operating system. The Java compiler compiles the java code and creates a bytecode(.class) file. This bytecode runs on the JVM to create machine-specific code. +It is a virtual machine on top of the operating system. The Java compiler compiles the Java code and creates a bytecode(.class) file. This bytecode runs on the JVM to create machine-specific code. Java Virtual Machine is behind the platform-independent nature of the Java programming language. @@ -112,34 +113,30 @@ Because the Java compiler on any platform creates the same bytecode (.class). An If you don’t understand this won’t be a worry, I have given a diagram below which will clear all the concepts. -That’s why we can call that Java programming language is platform-independent. +That’s why we can say that Java programming language is platform-independent. -We can write java code on any machine and run on any machine. It is called β€œWrite Once, Run Anywhere”.( WORA) +We can write Java code on any machine and run on any machine. It is called β€œWrite Once, Run Anywhere”.( WORA) -But when we say about JVM, JVM itself is platform-dependent, yes I have written correctly. Java Virtual Machine is platform dependent. +But when we say about JVM, JVM itself is platform-dependent, yes I have written correctly. Java Virtual Machine is platform-dependent. -We need a machine-specific Java Virtual Machine. When you visit the JDK download page there are different JDK for windows and different JDK for MAC OS. +We need a machine-specific Java Virtual Machine. When you visit the JDK download page there are different JDKs for Windows and different JDKs for MAC OS. Java Virtual Machine is platform-dependent and that’s why it can create a machine-specific instruction set for your code from the bytecode you have given. ### 2. Java Application Programming Interface (API) -In Java API, there are a large number of ready-made components that can be used to develop an application. It consists of classes, interfaces, packages along with its methods, fields, and constructors. +In Java API, there are a large number of ready-made components that can be used to develop an application. It consists of classes, interfaces, and packages along with its methods, fields, and constructors. -The purpose of using Java API is to minimize the number of lines in the code. The most basic programming tasks are performed using Java APIs classes and packages. +The purpose of using Java API is to minimize the number of lines in the code. The most basic programming tasks are performed using Java API classes and packages. ## How Java code works In Java, the source code is written in a file with a .java extension. -When we compile this file with the javac compiler, the .class file will be generated. The .class file contains the bytecode, the bytecode can run on the Virtual Machine. +When we compile this file with the Javac compiler, the .class file will be generated. The .class file contains the bytecode, the bytecode can run on the Virtual Machine. -Refer the following diagram, +Refer to the following diagram, ![How Java Code Works](/assets/images/2019-11-29/how-java-code-works.webp) What was your experience when you started learning Java, share with us in the comment section. - -If you found this article worth, please [Give me a cup of Coffee β˜•](https://paypal.me/GauravKukade). - -Or use Google Pay/UPI at gkukade54@okicici diff --git a/_posts/java-basic/2021-03-02-convert-double-to-int.md b/_posts/java-basic/2021-03-02-convert-double-to-int.md index ad3458f..73db80d 100644 --- a/_posts/java-basic/2021-03-02-convert-double-to-int.md +++ b/_posts/java-basic/2021-03-02-convert-double-to-int.md @@ -1,50 +1,52 @@ -ο»Ώ--- +--- layout: post title: "How To Convert double To int In Java?" author: gaurav image: assets/images/2021-03-02/double-to-int-in-java.webp categories: [ Java, Core Java, String] -description: "In this article you are going to learn how can we convert a double value to an integer value." +toc: true +description: "In this article, we will see, how to convert a double value to an integer value in Java programming language." --- +In this article, we will see, how to convert a double value to an integer value in Java programming language. -In this article, we will see how we can convert a double to an int. -In java programming, you will have a double primitive value (ex 82.14), but to do the further operations you need an int value (ex. 82) so let's see how to convert double to int in java. +Let's say, you have a double primitive value (ex `82.14`), but you need an int value (ex. `82`) for further operations. So, let's see how to convert double to int in Java. -There are three ways you can convert double to int. I will list them all below and, then we will see them one by one. +There are three ways you can convert double to int. I have listed the three ways below. 1. convert double to int - using typecasting 2. convert double to int - using `Math.round()` 3. convert double to int - using `Double.IntValue()` +Let's see these ways one by one. + > You may like to visit: > [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) -## 1. convert double to int - using typecasting +## 1. Convert double to int - using typecasting -We know `double` is a 64-bit primitive value, and int is a 32-bit primitive value. So, to convert double to int, we can downcast the double value to int. +We know `double` is a 64-bit primitive value, and int is a 32-bit primitive value. So, to convert double to int, we can **downcast the double value to int**. -I have given a simple example below that shows to convert double to int using typecasting. +I have given a simple example below that shows how to convert double to int using typecasting. ```java /** - * A java program to convert double to int using typecasting + * A Java program to convert double to int using typecasting * @author Gaurav Kukade at coderolls.com **/ public class DoubleToIntUsingTypecasting{ - public static void main(String []args){ - - double doubleValue = 82.14; // 82.14 - - System.out.println("doubleValue: "+doubleValue); - - //typecase double to int - int intValue = (int) doubleValue; // 82 - - System.out.println("intValue: "+intValue); - } + public static void main(String []args){ + double doubleValue = 82.14; // 82.14 + + System.out.println("doubleValue: "+doubleValue); + + //typecase double to int + int intValue = (int) doubleValue; // 82 + + System.out.println("intValue: "+intValue); + } } ``` Output: @@ -53,7 +55,7 @@ doubleValue: 82.14 intValue: 82 ``` -The problem with the typecasting is that it will truncate the value after the decimal point. It will not round it. +The problem with the typecasting is that it will **truncate the value after the decimal point**. It will not round it. In the case of 82.14, we will get an int value of 82, which looks ok. But when we have a double value like 82.99, we will get only 82 and loss the 0.99 that is ~1. @@ -65,44 +67,42 @@ It is not possible with typecasting, but our next solution can achieve it. ## 2. convert double to int - using [`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) -[`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method will round the floating-point value to the nearest long value. Then we can typecast it to the int. +[`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method will **round the floating-point value to the nearest long value**. Then we can typecast it to the int. -I have given a simple java program below that shows how to convert double to int using the [`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method. +I have given a simple Java program below that shows how to convert double to int using the [`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method. ```java /** - * A java program to convert double to int using + * A Java program to convert double to int using * Math.round() method - * @author Gaurav Kukade at coderolls.com + * @author coderolls.com **/ public class DoubleToIntUsingRoundMethod{ - public static void main(String []args){ - - // case 1 - double doubleValue = 82.14; // 82.14 - - System.out.println("doubleValue: "+doubleValue); - - //typecase double to int - int intValue = (int) Math.round(doubleValue); // 82 - - System.out.println("intValue: "+intValue); - - System.out.println(); - - // case 2 - double nextDoubleValue = 82.99; // - - - System.out.println("nextDoubleValue: "+nextDoubleValue); - - // Math.round(nextDoubleValue) returns long value - //typecase long to int - int nextIntValue = (int) Math.round(nextDoubleValue); // 83 - - System.out.println("nextIntValue: "+nextIntValue); - } + public static void main(String []args){ + // case 1 + double doubleValue = 82.14; // 82.14 + + System.out.println("doubleValue: "+doubleValue); + + //typecase double to int + int intValue = (int) Math.round(doubleValue); // 82 + + System.out.println("intValue: "+intValue); + + System.out.println(); + + // case 2 + double nextDoubleValue = 82.99; // + + System.out.println("nextDoubleValue: "+nextDoubleValue); + + // Math.round(nextDoubleValue) returns long value + //typecase long to int + int nextIntValue = (int) Math.round(nextDoubleValue); // 83 + + System.out.println("nextIntValue: "+nextIntValue); + } } ``` Output: @@ -126,28 +126,27 @@ I have given a simple java program below that shows how to convert double to int ```java /** * - * A java program to convert double to int using + * A Java program to convert double to int using * Double.intValue() method - * @author Gaurav Kukade at coderolls.com + * @author coderolls.com * **/ public class DoubleToIntUsingIntValueMethod{ - public static void main(String []args){ - - double doubleValue = 82.14; // 82.14 - - System.out.println("doubleValue: "+doubleValue); - - //create Double wrapper object - Double doubleValueObject = new Double(doubleValue); - - - //typecase double to int - int intValue = doubleValueObject.intValue(); // 82 - - System.out.println("intValue: "+intValue); - } + public static void main(String []args){ + double doubleValue = 82.14; // 82.14 + + System.out.println("doubleValue: "+doubleValue); + + //create a Double wrapper object + Double doubleValueObject = new Double(doubleValue); + + + //typecase double to int + int intValue = doubleValueObject.intValue(); // 82 + + System.out.println("intValue: "+intValue); + } } ``` @@ -162,18 +161,18 @@ We can convert double to int in java using the three ways given below. **1. convert double to int - using typecasting** -In this method we typecast the double value to int as give below, +In this method we **typecast the double value to int** as given below, ```java -int intValue = (int) Math.round(doubleValue); +int intValue = (int) doubleValue; ``` -But in this way, we will lose the value after the decimal point. It will not do the rounding before converting double to int. +But in this way, we will **lose the value after the decimal point**. It will not do the rounding before converting double to int. **2. convert double to int - using [`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) ** In this way, we use the [`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method for the rounding purpose. -[`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method round the double value to the nearest long, and then we can typecast long to the int as given below. +[`Math.round()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-) method **round the double value to the nearest long**, and then we can typecast long to the int as given below. ```java int nextIntValue = (int) Math.round(nextDoubleValue); ``` @@ -182,35 +181,18 @@ int nextIntValue = (int) Math.round(nextDoubleValue); In this way, we convert the `double` value to the `Double` wrapper class, and then we use the [`Double.IntValue()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#intValue--) method to get the int value. ```java -//create Double wrapper object +//create a Double wrapper object Double doubleValueObject = new Double(doubleValue); //typecase double to int int intValue = doubleValueObject.intValue(); ``` -In this way also we will lose the digits after the decimal points. +In this way we will **lose the digits after the decimal points**. -So this is how we do convert a double to int in java. You can check all three ([DoubleToIntUsingTypecasting.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingTypecasting.java), [DoubleToIntUsingRoundMethod.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingRoundMethod.java), [DoubleToIntUsingIntValueMethod.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingIntValueMethod.java)) programs on GitHub +So this is how we convert a double to int in Java. You can check all three ([DoubleToIntUsingTypecasting.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingTypecasting.java), [DoubleToIntUsingRoundMethod.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingRoundMethod.java), [DoubleToIntUsingIntValueMethod.java](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-basic/DoubleToIntUsingIntValueMethod.java)) programs on GitHub You can read more about [string to int](https://coderolls.com/convert-int-to-string/) and [int to string](https://coderolls.com/convert-string-to-int/) conversion. ------- You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -### Related Articles - -- [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) - -- [How to convert String to Integer in Java](https://coderolls.com/convert-string-to-int/) - -- [How To Convert StringBuilder To String In Java?](https://coderolls.com/convert-stringbuilder-to-string-in-java/) - -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) - - - - diff --git a/_posts/java-basic/2021-12-06-for-each-loop.md b/_posts/java-basic/2021-12-06-for-each-loop.md new file mode 100644 index 0000000..43c453b --- /dev/null +++ b/_posts/java-basic/2021-12-06-for-each-loop.md @@ -0,0 +1,128 @@ +--- +layout: post +title: "For-each loop in Java or Enhanced For loop in Java" +author: gaurav +categories: [Java, Control Flow Statements] +toc: true +description: "In this article, we will see the for-each loop in Java i.e. Enhanced for loop" +--- +In this article, we will see the for-each loop in Java i.e. Enhanced for-loop + +## Introduction + +For-each loop is introduced in Java 1.5. + +It provides a better approach to traversing the array or collection. + +In a simple for loop, we initialize the variable and write the condition for that variable. But in the enhanced loop, we do not have to initialize a variable or write any condition for that. + +The foreach loop is always used to traverse over the array or any collection. + +The for-each loop i.e. enhanced for loop will automatically traverse for each element of the array or collection. + +I have given the syntax for the for-each loop below. + +```java +for(DataType item : Array | Collection){ + //We have the item with us to operate +} +``` + +## Examples + +I have given a simple Java program to traverse over an array using the for-each loop i.e. enhanced for loop. + +```java +/** + * A Java program to traverse the array using the + * for-each loop i.e. enhanced for loop + * + * @author Guarav Kukade at coderolls.com + * + */ +public class ArrayForEachExample { + + public static void main(String[] args) { + //Create an array of marks + int[] numbers = { 88, 95, 65, 76, 78, 45, 95, 96, 56}; + + // traversing the array using for-each loop + for(int number: numbers) { + System.out.println("The number is "+ number); + } + } +} +``` +Output: +``` +The number is 88 +The number is 95 +The number is 65 +The number is 76 +The number is 78 +The number is 45 +The number is 95 +The number is 96 +The number is 56 +``` + + +Also, I have given a Java program below to traverse a collection using the for-each loop i.e. enhanced for loop. + +```java +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program to traverse the collection using + * the for-each loop i.e. enhanced for loop + * + * @author Gaurav Kukade at coderolls.com + * + */ +public class ArrayListForEachExample { + + public static void main(String[] args) { + //Create an empty ArrayList of Integer + List numbers = new ArrayList(); + + //add number to the list + numbers.add(1); + numbers.add(8); + numbers.add(8); + numbers.add(5); + numbers.add(4); + numbers.add(6); + numbers.add(3); + numbers.add(2); + numbers.add(9); + + //traversing the collection using for-each loop + for(Integer number: numbers) { + System.out.println("The number is "+ number); + } + } +} +``` +Output: +``` +The number is 1 +The number is 8 +The number is 8 +The number is 5 +The number is 4 +The number is 6 +The number is 3 +The number is 2 +The number is 9 +``` + +## Conclusion + +For-each loop i.e. enhanced for loop can be used to traverse over the array or collection. + +It provides a more readable syntax as compared to the simple for loop. + +The example Java program used in the above article can be found at [this GitHub repository.](https://github.com/coderolls/blogpost-coding-examples/tree/main/java-basic/for-each-loop) + +Please write down your thoughts in the comment section below. diff --git a/_posts/java-basic/2023-11-04-java-platform-independant.md b/_posts/java-basic/2023-11-04-java-platform-independant.md new file mode 100644 index 0000000..331ef14 --- /dev/null +++ b/_posts/java-basic/2023-11-04-java-platform-independant.md @@ -0,0 +1,58 @@ +--- +layout: post +title: "Java: The Platform-Independent Programming Language" +author: gaurav +categories: [ Java, Core Java ] +featured: false +toc: true +description: "In this article, we will learn about Java's platform independence and how Java achieves it." +--- + +In this article, we will learn about [Java's platform](/java-introduction) independence and how Java achieves it. + +## Introduction + +The software programs are very specific to the hardware and operation systems it is written on. When we write a piece of code on a platform, it will compile and run on that sample platform. But for the diversity and portability of the code or software, it is important that it should run on other platforms too. + +But In practicality, there are some limitations to it. Some programming languages are platform-dependent which means the code written on the platform can run on that platform only. For example C. + +But Java is an exception to it. + +> **Java is a platform-independent programming language.** +> +> Java achieves platform independence with the help of **bytecode** and **Java Virtual Machine**. + +Let's see what does it mean by platform independence. + +## What is Platform Independence? + +If a code written on one platform can run on any other platform, then it is platform independence. + +In Java programming language a program written on a platform can be run on any other platform, provided a JVM is installed. + +So, in Java we can **Write Once Run Anywhere (WORA)**. + +## How Java Achieves Platform Independence? + +When a developer writes a program it is in human readable format. i.e. `.java` file. + +When we compile it, the Java compiler converts it to the **bytecode**. i.e. `.class` file. Bytecode is not a native code for a machine. It can be understood by JVMs only. + +Then J**ava Virtual Machine** (JVM) executes the bytecode. At the end, we can see the output of the program. + +Let's take an example to understand the process. Assume, the below code is in a HelloWorld.java file. + +```java +public class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} +``` + +![An image showing How Java Achieves Platform Independance.](/assets/images/2023-11-04/java-platform-independent.png) + +## Conclusion +1. Java Programming language is a platform independent. We can **Write Once Run Anywhere (WORA)**. +2. Java Virtual Machine (JVM) is not platform-independent. Different Operating systems have different types of executable instructions. So there are different JVMs for different OS. +3. All JVMs can understand the bytecode and convert it to respective executable instructions. This makes Java a platform-independent language. diff --git a/_posts/java-basic/2023-11-16-jdk-vs-jre-vs-jvm.md b/_posts/java-basic/2023-11-16-jdk-vs-jre-vs-jvm.md new file mode 100644 index 0000000..02de072 --- /dev/null +++ b/_posts/java-basic/2023-11-16-jdk-vs-jre-vs-jvm.md @@ -0,0 +1,55 @@ +--- +layout: post +title: "Compare JDK vs JRE vs JVM" +author: gaurav +categories: [ Java, Core Java ] +featured: false +toc: true +description: "In this article, we will see the comparison between JDK, JRE and JVM." +--- + +In this article, we will see the comparison between JDK, JRE and JVM. + +## Introduction + +While talking about the Java programming language, we usually hear the terminologies like JDK, JRE and JVM. + +To understand the difference between these terminologies, let's see a use case. + +Two types of users use the Java programming language. The first ones are Developers, who develop the software in Java, and the second ones are the end-users, who use this software for various purposes. + +## JVM + +JVM stands for Java Virtual Machine. + +It is a virtual machine that executes Java bytecode. + +All JVMs can understand the bytecode and convert it to respective executable instructions. This makes Java a platform-independent language. + +## JRE + +JRE stands for Java Runtime Environment. + +Two types of users use the Java programming language. Developers and end-users. End-users use JRE to run the applications. + +The end-users do not need to develop or compile the software. The end-user can directly run it using the JRE. + +JRE contains some sets of libraries and JVM. + +## JDK + +JDK stands for Java Development Kit. + +Two types of users use the Java programming language. Developers and end-users. Developers can use JDK to develop and run applications. + +The developer needs to write a Java program. He needs to compile it and debug it. Once it is written and compiled successfully, He can try running it. All this can be done with JDK i.e. Java Development Kit. + +JDK contains the `javac` Java Compiler, debugging tools, JRE and JVM. + + +Let's see the following diagram to understand the JDK vs JRE vs JVM. + +![JDK vs JRE vs JVM](/assets/images/2023-11-08/jdk-vs-jre-vs-jvm.png) + + + diff --git a/_posts/java-basic/2023-11-30-c++-vs-java.md b/_posts/java-basic/2023-11-30-c++-vs-java.md new file mode 100644 index 0000000..32497ca --- /dev/null +++ b/_posts/java-basic/2023-11-30-c++-vs-java.md @@ -0,0 +1,27 @@ +--- +layout: post +title: "Difference Between C++ and Java" +author: gaurav +categories: [ Java, Core Java ] +featured: false +toc: true +description: "In this article, we will see the difference between C++ and Java." +--- + +In today's programming world, both C++ and Java are popular. + +Both are the Object object-oriented programming languages. Still, C++ and Java have a different set of features for different use cases. + +Let's try to understand the basic difference between C++ and Java. + +## Difference between C++ and Java (C++ vs Java) +{:class=" table table-bordered"} + +| Property | C++ | Java | +| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Platform Independence | C++ is a platform-dependent programming language. | C++ is a platform-independent programming language. | +| Garbage Collection | Programmer has to take care of the Garbage Collection. I.e. Removing unrefereed objects from the memory. | Java has a provision to remove unreferred objects from the memory. i.e. Garbage Collection | +| Multiple Inheritance | C++ supports multiple inheritance. | Java does not support multiple inheritance. | +| Internal access to Memory | C++ has the concept of 'Pointers' to access the internal memory. | Java does not have Pointers. | +| Object Oriented | C++ is less object-oriented as we can write structural programs without using objects. | Java is more purer Object Oriented Language as compared to C++ (except for primitive variables). | + diff --git a/_posts/java-files-io/2021-01-03-read-file-using-bufferedreader.md b/_posts/java-files-io/2021-01-03-read-file-using-bufferedreader.md index 71cbcf5..989f790 100644 --- a/_posts/java-files-io/2021-01-03-read-file-using-bufferedreader.md +++ b/_posts/java-files-io/2021-01-03-read-file-using-bufferedreader.md @@ -4,12 +4,13 @@ title: "How To Read File Using BufferedReader In Java?" author: gaurav image: assets/images/2021-01-03/read-file-using-bufferedreader.webp categories: [Java, Java File IO] -description: "In this article we will see how to read a file using the `BufferedReader` class in Java." +toc: true +description: "In this article, we will see how to read a file using the `BufferedReader` class in Java." --- -In this article we will see how to read a file using the `BufferedReader `class in Java. +In this article, we will see how to read a file using the `BufferedReader `class in Java. -`BufferedReader` class reads text from a character-input stream. Because of buffering characters it provides an efficient way to read characters, arrays, and lines. +`BufferedReader` class reads text from a character-input stream. Because of buffering characters, it provides an efficient way to read characters, arrays, and lines. `BufferedReader` provides two important methods to read from the file. i.e `read()` and `readLine()`. @@ -18,46 +19,43 @@ You can specify the bufferSize in `BufferedReader `constructer. But as [motioned ## BufferedReader `read()` method -`BufferedReader` `read()` method reads a single character. IT returns the `int` representation of the char in range of 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached. +`BufferedReader` `read()` method reads a single character. It returns the `int` representation of the char in the range of 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached. -We can cast `int` value returned by `read()` method to `char` to get the character value. +We can cast the `int` value returned by the `read()` method to `char` to get the character value. -I have given an example to read a file character by character using the `read()` method of the `BufferedReader` class +I have given an example of reading a file character by character using the `read()` method of the `BufferedReader` class ```java package com.coderolls; import java.io.*; /** - * A java program to read file character by character using the + * A Java program to read files character by character using the * read() method of the BufferedReader Class. * * @author Gaurav Kukade at coderolls.com */ public class BufferedReaderReadMethodExample { - public static void main(String[] args) { - - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader("F:\\sample-text.txt")); - - int i; - //read each character using read() method and print it - while((i=bufferedReader.read())!=-1){ - System.out.print((char)i); - } - - }catch (IOException e) { - e.printStackTrace(); - }finally { - try { - bufferedReader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + public static void main(String[] args) { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new FileReader("F:\\sample-text.txt")); + int i; + //read each character using read() method and print it + while((i=bufferedReader.read())!=-1){ + System.out.print((char)i); + } + }catch (IOException e) { + e.printStackTrace(); + }finally { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } } ``` Output @@ -71,9 +69,9 @@ As specified in the name, this method reads a line of text. A line is considered to be terminated by any one of a line feed ('\n') or a carriage return ('\r'). -The `readLine()` method returns the content of a line as string except the line terminating character (i.e. `\n` or `\r`). Or it will return `null` if the end of the stream has been reached. +The `readLine()` method returns the content of a line as a string except the line terminating character (i.e. `\n` or `\r`). Or it will return `null` if the end of the stream has been reached. -I have given below an example to read file line by line using the `readLine()` method +I have given below an example of reading file line by line using the `readLine()` method ```java package com.coderolls; @@ -81,7 +79,7 @@ package com.coderolls; import java.io.*; /** - * A java program to read file line by line using the + * A Java program to read files line by line using the * readLine() method of the BufferedReader Class. * * @author Gaurav Kukade at coderolls.com @@ -89,28 +87,25 @@ import java.io.*; */ public class BufferedReaderReadLineMethodExample { - public static void main(String[] args) { - - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader("F:\\sample-text-two-lines.txt")); - - String line; - //read each line using readLine() method and print it - while((line = bufferedReader.readLine()) != null){ - System.out.println(line); - } - - }catch (IOException e) { - e.printStackTrace(); - }finally { - try { - bufferedReader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + public static void main(String[] args) { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new FileReader("F:\\sample-text-two-lines.txt")); + String line; + //read each line using readLine() method and print it + while((line = bufferedReader.readLine()) != null){ + System.out.println(line); + } + }catch (IOException e) { + e.printStackTrace(); + }finally { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } } ``` Output @@ -121,7 +116,7 @@ Visit coderolls to read more coding tutorials! ``` See [this example on GitHub](https://github.com/coderolls/blogpost-coding-examples/blob/main/java-files-io/BufferedReaderReadLineMethodExample.java). -I have given below a combine example of the Java `BufferedReader` `read()` and `readLine()` method below +I have given below a combined example of the Java `BufferedReader` `read()` and `readLine()` methods below ```java package com.coderolls; @@ -130,28 +125,28 @@ import java.io.*; public class BufferedReaderExanple { - public static void main(String[] args) { - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader("F:\\sample-text.txt")); - System.out.println("Read file using read() method: "); - readFileCharacterByCharacter(bufferedReader); - - bufferedReader = new BufferedReader(new FileReader("F:\\sample-text-two-lines.txt")); - System.out.println("\n\nRead file using readLine() method: "); - readFileLineByLine(bufferedReader); - - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - bufferedReader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void main(String[] args) { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new FileReader("F:\\sample-text.txt")); + System.out.println("Read file using read() method: "); + readFileCharacterByCharacter(bufferedReader); + + bufferedReader = new BufferedReader(new FileReader("F:\\sample-text-two-lines.txt")); + System.out.println("\n\nRead file using readLine() method: "); + readFileLineByLine(bufferedReader); + + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } /** * A method to read file content character by character using the BufferedReader @@ -159,17 +154,17 @@ public class BufferedReaderExanple { * * @param bufferedReader */ - public static void readFileCharacterByCharacter(BufferedReader bufferedReader) { - try { - int i; - //read each character using read() method and print it - while((i=bufferedReader.read())!=-1){ - System.out.print((char)i); - } - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void readFileCharacterByCharacter(BufferedReader bufferedReader) { + try { + int i; + //read each character using read() method and print it + while((i=bufferedReader.read())!=-1){ + System.out.print((char)i); + } + } catch (IOException e) { + e.printStackTrace(); + } + } /** * A method to read file content line by line using the BufferedReader @@ -179,16 +174,16 @@ public class BufferedReaderExanple { */ public static void readFileLineByLine(BufferedReader bufferedReader) { - try { - String line; - //read each line using readLine() method and print it - while((line = bufferedReader.readLine()) != null){ - System.out.println(line); - } - }catch (IOException e) { - e.printStackTrace(); - } - } + try { + String line; + //read each line using readLine() method and print it + while((line = bufferedReader.readLine()) != null){ + System.out.println(line); + } + }catch (IOException e) { + e.printStackTrace(); + } + } } ``` @@ -202,32 +197,12 @@ In Java 1.8 and above you can get a `BufferedReader` instance using the `newBuff You can read file character by character using the `read()` method of the `BufferedReader`Class. -`read()` method returns an integer value, you have to cast it to `char` to get character value. +The `read()` method returns an integer value, you have to cast it to `char` to get the character value. -Also, you can read file line by line using the `readLine()` method of the `BufferedReader`Class +Also, you can read files line by line using the `readLine()` method of the `BufferedReader`Class -`readLine()` methods returns the line content as string, except the line terminating character +The `readLine()` method returns the line content as a string, except the line terminating character You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. --------------- - -You can support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) - -- [How To Create UUID in Java?](https://coderolls.com/create-uuid-in-java/) - -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) - -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) - -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) - -- [How To Create UUID in Java?](https://coderolls.com/create-uuid-in-java/) +Please write down your thoughts in the comment section below. diff --git a/_posts/java-interview-questions/2022-10-28-core-java-interview-questions.md b/_posts/java-interview-questions/2022-10-28-core-java-interview-questions.md new file mode 100644 index 0000000..12f2045 --- /dev/null +++ b/_posts/java-interview-questions/2022-10-28-core-java-interview-questions.md @@ -0,0 +1,15 @@ +--- +layout: post +title: "Core Java Interview Questions" +author: gaurav +categories: [Java, Java Interview Questions, Core Java Interview Questions] +toc: false +description: "An index page for Core Java Interview Questions." +hidden: true +--- + +- [Java OOPs Concepts](/java-oops-concepts/) +- [Difference Between Abstract Class and Interface In Java](/difference-between-abstract-class-and-interface/) +- [Method Overloading In Java](/method-overloading-in-java/) +- [Method Overriding In Java](/method-overriding-in-java/) + diff --git a/_posts/java-interview-questions/core-java-interview-questions/2022-10-20-difference-between-interface-and-abstract-class.md b/_posts/java-interview-questions/core-java-interview-questions/2022-10-20-difference-between-interface-and-abstract-class.md new file mode 100644 index 0000000..87c7466 --- /dev/null +++ b/_posts/java-interview-questions/core-java-interview-questions/2022-10-20-difference-between-interface-and-abstract-class.md @@ -0,0 +1,56 @@ +--- +layout: post +title: "Difference Between Interface and Abstract Class In Java" +author: gaurav +categories: [Java, Java Interview Questions] +toc: true +description: "In this tutorial, we will see the difference between abstract class and interface in Java." +--- + +In this tutorial, we will see the difference between abstract class and interface in Java. + +## Introduction + +Interfaces form a contract between **the class and the outside world**, and this contract is enforced at build time by the compiler. + +An *abstract class* is a class that is **declared with the `abstract` keyword**β€”it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. + +We all know that Defaults and Static methods are introduced in Java 8. + +We can have business logic in the interface with default and static methods. So the measure difference that interface can not have concrete methods and abstract class have concrete methods is no more. But still, there are many differences in the interface and abstract class as discussed below. + +## Difference Between Interface And Abstract Class After Java 8 i.e. Interface Vs Abstract Class After Java 8 + +{:class="table table-bordered"} + +| Property | Interface | Abstract Class | +| -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Variables | **Every variable present inside the interface is always public, static, and final,** whether we are declaring or not. | The variables present inside the abstract class **need not be public static and final.** We can have other types of variables too. | +| Variables | We **can not declare protected, transient and volatile variables** in the interface. | There are **no restrictions on abstract class variable modifiers**. We can have protected, transient and volatile variables in the Abstract class. | +| Default Methods | After Java 8, an i**nterface can have default methods.** | **Abstract Class can not have default methods**. | +| Final Methods | As we know, an interface can have default and static methods along with abstract methods. But **Interfaces don’t support final methods**. | **Abstract classes support final as well as non-final methods** and static as well as non-static methods along with abstract methods. | +| Constructors | We **can not have constructors** inside the interface. | We **can declare a constructor inside an abstract class**, that can be used at the time of child object creation. | +| Multiple Inheritance | **A class can implement multiple interfaces**. So multiple inheritances are possible with Interfaces. | **A class can extend only one abstract class**. So multiple inheritances are not possible with abstract classes. | + +## Difference Between Interface And Abstract Class Before Java 8 i.e. Interface Vs Abstract Class Before Java 8 + +Here we will see the difference between the interface and abstract class before the Java 8 version. + +{:class="table table-bordered"} + +| Property | Interface | Abstract Class | +| ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| When to use? | If we **don't know anything about implementation and we just have requirement specifications** then we should go for an interface. | If we do not have a complete idea about implementation then we should go for the Abstract class. i.e. **In case of partial implementation**, we should go for Abstract Class. | +| Methods | Inside the interface, **all methods are public and abstract** by default. Hence we can achieve 100% abstraction with an interface. | Every method present in the abstract class need not be public and abstract. **In addition to abstract methods, we can have concrete methods too**. | +| Modifiers | Since all the methods are public and abstract, we **can not use any other modifiers. (Other than public and abstract)** | Since we can concrete methods in the Abstract class, **there are no restrictions on abstract class method modifiers.** | +| Variables | **Every variable present inside the interface is always public, static, and final,** whether we are declaring or not. | The variables present inside the abstract class **need not be public static and final.** We can have other types of variables too. | +| Variables | We **can not declare protected, transient, and volatile variables** in the interface. | There are **no restrictions on abstract class variable modifiers**. We can have protected, transient, and volatile variables in the Abstract class. | +| Variable Initialisation | At the time of declaration, **we need to initialize the variables compulsorily**. Otherwise, we will get a compile-time error. | For Abstract class variables, **it is not necessary to initialize them at the time of declaration**. | +| Blocks | Inside the interface, **we can not declare instances and static blocks**. Otherwise, we will get a compile-time error. | Inside the abstract class, we **can declare instances and static blocks**. | +| Constructors | We **can not have constructors** inside the interface. | We **can declare a constructor inside an abstract class** that can be used at the time of child object creation. | +| Multiple Inheritance | A **class can implement multiple interfaces**. So multiple inheritances are possible with Interfaces. | A **class can extend only one abstract class**. So multiple inheritances are not possible with abstract classes. | +| Example | Servlet | GenericServlet , HttpServlet | + +--- + +Please write your thoughts in the comment section below. diff --git a/_posts/java-interview-questions/core-java-interview-questions/2022-10-23-java-oops-concepts.md b/_posts/java-interview-questions/core-java-interview-questions/2022-10-23-java-oops-concepts.md new file mode 100644 index 0000000..da9e33f --- /dev/null +++ b/_posts/java-interview-questions/core-java-interview-questions/2022-10-23-java-oops-concepts.md @@ -0,0 +1,129 @@ +--- +layout: post +title: "Java OOPs Concepts" +author: gaurav +categories: [Java, Java Interview Questions] +toc: true +description: "In this tutorial, we will see the basic object-oriented programming concepts." +--- + +In this tutorial, we will see the basic object-oriented programming concepts. + +## Introduction + +Object-oriented programming (OOP) is *a computer programming model that organizes software design around data, or objects, rather than functions and logic*. + +There are many opps concepts but here we will see the most important 4. I.e Abstraction, Encapsulation, Inheritance and Polymorphism. + +## Java OOPs Concepts + +### 1. Abstraction + +**Hiding internal implementation** and just **hightailing the functionalities offered** is known as abstraction. + +**Example:** ATM functions are a practical example of abstraction. They just highlight the functionality i.e. withdrawing money, checking balance or printing the mini statement. It does not show the internal implementation of those functions. + +**Method in a Java class** is an example of Abstraction. + +### 2. Encapsulation + +The **process of grouping the data members and corresponding methods in a single unit** is called encapsulation. + +**Every Java class is an example of encapsulation.** Java bean is the fully encapsulated class because all the data members are private here. + +**Example:** + +```java +public class Student { + + private int id; + + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} +``` + +In the above code, the data members like `id`, `name` and corresponding methods such as `setId()`, `getId` etc. are grouped together in a java class `Student`. So Java class is a good example of *Encapsulation*. + +### 3. Inheritance + +***When a child object acquires all the properties and behaviours of a parent object***, it is known as inheritance. It provides code re-usability. It is an `IS-A ` relationship. + +```java +public class Animal { + + private String name; + + public void run() { + + } + + public void feed() { + + } + +} + +class Dog extends Animal{ + + private String breed; + + public void bark() { + + } +} +``` + +In the above example, the `Animal` class is a Parent class and the `Dog` class is a `child` class. + +The animal can have a name, it can run. + +We have created a child class `Dog` which `extends` the `Animal` class. That means the `Dog` class inherits the properties and behaviours of the parent class `Animal`. + +A dog can have a name, it can run and in addition, it can have its own property like `breed` and behaviours like `bark()`. + +### 4. Polymorphism + +If *one task is performed in different ways*, it is known as polymorphism. + +The word ***poly*** means ***many*** and ***morphs*** means ***forms or ways***. + +In Java, we use [method overloading](/method-overloading-in-java/) and [method overriding](/method-overriding-in-java/) to achieve polymorphism. + +There are two types of polymorphism in Java: + +1. Compile-time Polymorphism +2. Runtime Polymorphism. + +Compile-time polymorphism can be achieved by [**overloading the static method**](/method-overloading-in-java/). While Runtime Polymorphism can be achieved by [**overriding the parent class method in the child class**](/method-overriding-in-java/). + +## Conclusion + + Abstraction, Encapsulation, Inheritance and Polymorphism are the most important oops concepts in Java. + +1. In Abstraction we **hide the internal implementation** and **highlight the functionalities offered**. Ex. method in Java + +2. Encapsulation is the **process of grouping data members and corresponding methods in a single unit**. Ex. Java Class + +3. In inheritance, **a child class inherits all the properties and behaviour of the parent class**. It can be done by extending the parent class. Ex. `class Dog extends Animal{...}` +4. **Doing one task in many ways** is called polymorphism. In Java, polymorphism can be done using [method overloading](/method-overloading-in-java/) and [method overriding](/method-overriding-in-java/). + +--- + +Please write your thoughts in the comment section below. diff --git a/_posts/java-interview-questions/core-java-interview-questions/2022-10-31-method-overloading-in-java.md b/_posts/java-interview-questions/core-java-interview-questions/2022-10-31-method-overloading-in-java.md new file mode 100644 index 0000000..53d6fa1 --- /dev/null +++ b/_posts/java-interview-questions/core-java-interview-questions/2022-10-31-method-overloading-in-java.md @@ -0,0 +1,91 @@ +--- +layout: post +title: "Method Overloading In Java" +author: gaurav +categories: [Java, Java Interview Questions] +toc: true +description: "In this tutorial, we will see the method overloading in Java." +--- + +In this tutorial, we will see the method overloading in Java. + +## Introduction + +It is known as **Method Overloading** when a class has the same name but a different method signature. + +For example, when we have a method `add()`, we can have it in multiple forms. + +For example `add(int a, int b)` or `add(int a, int b, int c)` or `add(double a, double b)` + +--- + +> **What Is Method Signature In Java?** +> +> In Java, the method signature contains the method name and type of arguments. +> +> method-name(argument-type-1, argument-type-2...) +> +> Ex. `getData(int, String)` +> +> **Note:** In Java, the method signature does not include the name of the parameter, it only includes its datatype. + +--- + +Compile-time polymorphism can be achieved by Method overloading. + +In Java, there are two ways to overload the method. + +1. By changing the number of arguments +2. By changing the data type of arguments + +## 1. By changing the number of arguments + +We can overload a method **by changing the number of arguments i.e parameters it receives**. + +As shown in the example from the introduction, we can overload the method `add(int a, int b)` by making the parameters three. i.e `add(int a, int b, int c)` + +```java +public class Operation{ + + public static int add(int a, int b){ + return a+b; + } + + public static int add(int a, int b, int c){ + return a+b+c; + } + +} +``` + +## 2. By changing the data type of arguments + +We can overload a method **by changing the data type of the arguments i.e parameters it receives**. + +As shown in the example from the introduction, we can overload the method `add(int a, int b)` by changing the data type of the parameters. i.e `add(double a, double b)` + +```java +public class Operation{ + + public static int add(int a, int b){ + return a+b; + } + + public static double add(double a, double b){ + return a+b; + } + +} +``` + +Method overloading improves the readability of the code. + +## Conclusion + +It is known as **Method Overloading** when a class has the same name but a different method signature. + +We can overload the method by changing the number of arguments or changing the data type of arguments. + +--- + +Please write your thoughts in the comment section below. diff --git a/_posts/java-interview-questions/core-java-interview-questions/2022-11-03-method-overriding-in-java.md b/_posts/java-interview-questions/core-java-interview-questions/2022-11-03-method-overriding-in-java.md new file mode 100644 index 0000000..04b044e --- /dev/null +++ b/_posts/java-interview-questions/core-java-interview-questions/2022-11-03-method-overriding-in-java.md @@ -0,0 +1,58 @@ +--- +layout: post +title: "Method Overriding In Java" +author: gaurav +categories: [Java, Java Interview Questions] +toc: false +description: "In this tutorial, we will see the method overriding in Java." +--- + +In this tutorial, we will see the method overriding in Java. + +When **a child class provides a specific implementation for the method already declared in parent class**, it is called a method overriding. + +So both parent class and child class will have the same method but with different implementations. + +Example:- + +```java +/** + * A Java Program to explain the method of overriding. + * @author coderolls.com + * + */ +public class Test { + public static void main(String[] args) { + Dog dog = new Dog(); + Cat cat = new Cat(); + + dog.printSound(); + cat.printSound(); + } + +} +class Animal { + public void printSound() { + System.out.println("Print sound of animal"); + } +} + +class Dog extends Animal { + @Override + public void printSound() { + System.out.println("Dogs bark..!"); + } +} + +class Cat extends Animal { + @Override + public void printSound() { + System.out.println("Cats meow..!"); + } +} +``` + +1. In the above example `Animal` is the parent class. It has the `printSound()` method with its own implementation. +2. Next, we have created a child class `Dog` by extending the parent class `Animal`. We know dogs do bark so we can provide the specific implementation for the `printSound()` method in the `Dog` class. +3. Also, we have created a child class `Cat` by extending the parent class `Animal`. We can again provide the cat-specific implementation for the `printSound()` method in the `Cat` class. +4. In the Test class, we have created objects of the Dog and Cat class and invoked their `printSound()` method. We can see, that when we invoke the `printSound()` method on Dog object `dog`, it prints the `Dogs bark..!` i.e. dog specific implementation. And when we invoke the `printSound()` method on the Cat object `cat`, it prints the `Cats meow..!` i.e. dog specific implementation diff --git a/_posts/java-interview-questions/core-java-interview-questions/2022-11-10-arraylist-vs-linkedlist.md b/_posts/java-interview-questions/core-java-interview-questions/2022-11-10-arraylist-vs-linkedlist.md new file mode 100644 index 0000000..ebb94c5 --- /dev/null +++ b/_posts/java-interview-questions/core-java-interview-questions/2022-11-10-arraylist-vs-linkedlist.md @@ -0,0 +1,24 @@ +--- +layout: post +title: "ArrayList VS LinkedList" +author: gaurav +categories: [Java, ArrayList, Java Interview Questions] +toc: false +description: "In this article, we will see the difference between ArrayList and LinkedList." +--- + +In this article, we will see the difference between ArrayList and LinkedList. + +## ArrayList Vs LinkedList + +{:class="table table-bordered"} +| Property | ArrayList | LinkedList | +| ------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Internal Implementation | ArrayList internally uses a **dynamic array** to store the elements. | LinkedList internally uses a **doubly linked list** to store the elements. | +| Preference | ArrayList is **preferred for storing and retrieving the data** from the list. | LinkedList is **preferred for inserting and deleting the data** in a list. | +| Store and Retrieve Data | Storing and retrieving the data from the ArrayList is faster since it uses a **dynamic array** to store the elements.


Time complexity for retrieving an element by id from the ArrayList is **O(1)**. | Storing and retrieving the data from the LinkedList is slower in comparison since it uses a **doubly linked list** to store the elements.


Time complexity for retrieving an element by id from the LinkedList is **O(n)**. | +| Data Manipulation ( Insert or delete data) | Manipulation with ArrayList is **slower** because it internally uses an array.
In case of removing an element from the array or inserting an element in between the array, all the other elements are shifted in memory. | Manipulation with LinkedList is **faster** than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. | +| Interface implementation | An ArrayList class can **act as a list** only because it implements List interface only.

`ArrayList implements List` | LinkedList class can **act as a list and queue** both because it implements List and Deque interfaces.

`LinkedList implements List, Deque` | +| Memory Location | The memory location for the elements of an ArrayList is **contiguous**. | The location for the elements of a linked list is **not contagious**. | +| Default Capacity | On initialisation, a **default capacity of 10** is assigned to the ArrayList. | There is no case of default capacity in a LinkedList. An empty list is created when a LinkedList is initialized. | + diff --git a/_posts/java-json/2021-01-07-parse-json-in-java.md b/_posts/java-json/2021-01-07-parse-json-in-java.md index c105ec2..42d6129 100644 --- a/_posts/java-json/2021-01-07-parse-json-in-java.md +++ b/_posts/java-json/2021-01-07-parse-json-in-java.md @@ -1,12 +1,15 @@ -ο»Ώ--- +--- layout: post title: "How To Parse JSON In Java?" author: gaurav -image: assets/images/2021-01-07/parse-json-in-java.png categories: [JSON, Java] -description: "In this article we will see, how to parse JSON in java. We will be using the JSON Libraries like JSON-java, GSON and json simple" +toc: true +description: "In this article, we will see, how to parse JSON in Java. We will be using JSON Libraries like JSON-java, GSON and JSON simple" +featured: true --- -In this article we will see, how to parse JSON in java. We will be using the JSON Libraries like JSON-java, GSON and json-simple +In this article, we will see, how to parse JSON in Java. We will be using the JSON Libraries like JSON-java, GSON and json-simple + +## Introduction **JSON** stands for JavaScript Object Notation. It is easy to use and lightweight open standard file format for storing and transporting data. @@ -40,25 +43,25 @@ Example JSON: ] } ``` -In the above JSON, `name` is key and `coderolls` is it's value. For `address` key, value is another JSON object which contains key and values. +In the above JSON, `name` is the key and `coderolls` is its value. For the `address` key, the value is another JSON object which contains the key and values. -For `employees` key, it's value is array of JSON objects. +For the `employees` key, its value is an array of JSON objects. -Today we will see three json libraries in java to parse a JSON string. These are listed below, +Today we will see three JSON libraries in Java to parse a JSON string. These are listed below, 1. JSON-Java 2. GSON 4. json-simple -Now we will see one by one example of all three libraries for parsing a JSON in java. +Now we will see one by one examples of all three libraries for parsing a JSON in Java. ## How to parse JOSN in Java using JSON-Java -JSON-java is one of the most simple JSON library for Java. +JSON-java is one of the most simple JSON libraries for Java. Here, we will be using the `JSONObject` class of the JSON-java library. -`JSONObject` [has a constructor which accepts string](https://stleary.github.io/JSON-java/index.html). We will be using ths constructor to parse a JSON string. +`JSONObject` [has a constructor which accepts string](https://stleary.github.io/JSON-java/index.html). We will be using this constructor to parse a JSON string. ``` public JSONObject(String source) throws JSONException @@ -98,64 +101,64 @@ import org.json.JSONArray; import org.json.JSONObject; /** - * A program to parse JSON strin in Java using JSON-Java + * A program to parse JSON string in Java using JSON-Java * @author Gaurav Kukade at coderolls.com */ public class ParseJSONUsingJSONJava { - public static void main(String[] args) { - - String jsonString = "{" - + " \"name\": \"coderolls\"," - + " \"type\": \"blog\"," - + " \"address\": {" - + " \"street\": \"1600 Pennsylvania Avenue NW\"," - + " \"city\": \"Washington\"," - + " \"state\": \"DC\"" - + " }," - + " \"employees\": [" - + " {" - + " \"firstName\": \"John\"," - + " \"lastName\": \"Doe\"" - + " }," - + " {" - + " \"firstName\": \"Anna\"," - + " \"lastName\": \"Smith\"" - + " }," - + " {" - + " \"firstName\": \"Peter\"," - + " \"lastName\": \"Jones\"" - + " }" - + " ]" - + "}"; - - System.out.println("Parsing the json string in java using JSON-Java......\n"); - - //add jsonString to the constructor - JSONObject coderollsJSONObject = new JSONObject(jsonString); - - //now we can access the values - String name = coderollsJSONObject.getString("name"); - System.out.println("Name: "+name+"\n"); - - //we can get the JSON object present as value of any key in the parent JSON - JSONObject addressJSONObject = coderollsJSONObject.getJSONObject("address"); - - //access the values of the addressJSONObject - String street = addressJSONObject.getString("street"); - System.out.println("Street: "+street+"\n"); - - - //we can get the json array present as value of any key in the parent JSON - JSONArray employeesJSONArray = coderollsJSONObject.getJSONArray("employees"); - System.out.println("Printing the employess json array: \n"+employeesJSONArray.toString()+"\n"); - - //we can get individual json object at an index from the employeesJSONArray - JSONObject employeeJSONObject = employeesJSONArray.getJSONObject(0); - String firstName = employeeJSONObject.getString("firstName"); - System.out.println("First Name of the employee at index 0: "+firstName); - } + public static void main(String[] args) { + + String jsonString = "{" + + " \"name\": \"coderolls\"," + + " \"type\": \"blog\"," + + " \"address\": {" + + " \"street\": \"1600 Pennsylvania Avenue NW\"," + + " \"city\": \"Washington\"," + + " \"state\": \"DC\"" + + " }," + + " \"employees\": [" + + " {" + + " \"firstName\": \"John\"," + + " \"lastName\": \"Doe\"" + + " }," + + " {" + + " \"firstName\": \"Anna\"," + + " \"lastName\": \"Smith\"" + + " }," + + " {" + + " \"firstName\": \"Peter\"," + + " \"lastName\": \"Jones\"" + + " }" + + " ]" + + "}"; + + System.out.println("Parsing the JSON string in Java using JSON-Java......\n"); + + //add jsonString to the constructor + JSONObject coderollsJSONObject = new JSONObject(jsonString); + + //now we can access the values + String name = coderollsJSONObject.getString("name"); + System.out.println("Name: "+name+"\n"); + + //we can get the JSON object present as value of any key in the parent JSON + JSONObject addressJSONObject = coderollsJSONObject.getJSONObject("address"); + + //access the values of the addressJSONObject + String street = addressJSONObject.getString("street"); + System.out.println("Street: "+street+"\n"); + + + //we can get the JSON array present as the value of any key in the parent JSON + JSONArray employeesJSONArray = coderollsJSONObject.getJSONArray("employees"); + System.out.println("Printing the employees JSON array: \n"+employeesJSONArray.toString()+"\n"); + + //we can get individual JSON objects at an index from the employeesJSONArray + JSONObject employeeJSONObject = employeesJSONArray.getJSONObject(0); + String firstName = employeeJSONObject.getString("firstName"); + System.out.println("First Name of the employee at index 0: "+firstName); + } } ``` @@ -163,13 +166,13 @@ Get the code for [ParseJSONUsingJSON.Java](https://github.com/coderolls/blogpost Output: ```java -Parsing the json string in java using JSON-Java...... +Parsing the JSON string in Java using JSON-Java...... Name: coderolls Street: 1600 Pennsylvania Avenue NW -Printing the employess json array: +Printing the employee's JSON array: [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}] First Name of the employee at index 0: John @@ -182,7 +185,7 @@ So we can use it to convert a JSON string to an equivalent Java object. Here, we will be using the `JsonObject` class of the Gson library. -You can refer the [docs of JsonObject](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonObject.html). +You can refer to the [docs of JsonObject](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonObject.html). Maven: ``` @@ -206,66 +209,66 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** - * A program to parse JSON strin in Java using Gson + * A program to parse JSON string in Java using Gson * @author Gaurav Kukade at coderolls.com */ public class ParseJSONUsingGSON { - public static void main(String[] args) { - - //take json as string - String jsonString = "{" - + " \"name\": \"coderolls\"," - + " \"type\": \"blog\"," - + " \"address\": {" - + " \"street\": \"1600 Pennsylvania Avenue NW\"," - + " \"city\": \"Washington\"," - + " \"state\": \"DC\"" - + " }," - + " \"employees\": [" - + " {" - + " \"firstName\": \"John\"," - + " \"lastName\": \"Doe\"" - + " }," - + " {" - + " \"firstName\": \"Anna\"," - + " \"lastName\": \"Smith\"" - + " }," - + " {" - + " \"firstName\": \"Peter\"," - + " \"lastName\": \"Jones\"" - + " }" - + " ]" - + "}"; - System.out.println("Parsing the json string in java using Gson......\n"); - - Gson gson = new Gson(); - - //get json object from the json string - JsonObject coderollsJsonObject = gson.fromJson(jsonString, JsonObject.class); - - //now we can access the values - String name = coderollsJsonObject.get("name").getAsString(); - System.out.println("Name: "+name+"\n"); - - //we can get the JSON object present as value of any key in the parent JSON - JsonObject addressJsonObject = coderollsJsonObject.get("address").getAsJsonObject(); - - //access the values of the addressJSONObject - String street = addressJsonObject.get("street").getAsString(); - System.out.println("Street: "+street+"\n"); - - - //we can get the json array present as value of any key in the parent JSON - JsonArray employeesJsonArray = coderollsJsonObject.get("employees").getAsJsonArray(); - System.out.println("Printing the employess json array: \n"+employeesJsonArray.toString()+"\n"); - - //we can get individual json object at an index from the employeesJSONArray - JsonObject employeeJsonObject = employeesJsonArray.get(0).getAsJsonObject(); - String firstName = employeeJsonObject.get("firstName").getAsString(); - System.out.println("First Name of the employee at index 0: "+firstName); - } + public static void main(String[] args) { + + //Take JSON as a string + String jsonString = "{" + + " \"name\": \"coderolls\"," + + " \"type\": \"blog\"," + + " \"address\": {" + + " \"street\": \"1600 Pennsylvania Avenue NW\"," + + " \"city\": \"Washington\"," + + " \"state\": \"DC\"" + + " }," + + " \"employees\": [" + + " {" + + " \"firstName\": \"John\"," + + " \"lastName\": \"Doe\"" + + " }," + + " {" + + " \"firstName\": \"Anna\"," + + " \"lastName\": \"Smith\"" + + " }," + + " {" + + " \"firstName\": \"Peter\"," + + " \"lastName\": \"Jones\"" + + " }" + + " ]" + + "}"; + System.out.println("Parsing the JSON string in Java using Gson......\n"); + + Gson gson = new Gson(); + + //get JSON object from the JSON string + JsonObject coderollsJsonObject = gson.fromJson(jsonString, JsonObject.class); + + //now we can access the values + String name = coderollsJsonObject.get("name").getAsString(); + System.out.println("Name: "+name+"\n"); + + //we can get the JSON object present as the value of any key in the parent JSON + JsonObject addressJsonObject = coderollsJsonObject.get("address").getAsJsonObject(); + + //access the values of the addressJSONObject + String street = addressJsonObject.get("street").getAsString(); + System.out.println("Street: "+street+"\n"); + + + //we can get the JSON array present as the value of any key in the parent JSON + JsonArray employeesJsonArray = coderollsJsonObject.get("employees").getAsJsonArray(); + System.out.println("Printing the employees JSON array: \n"+employeesJsonArray.toString()+"\n"); + + //we can get individual JSON object at an index from the employeesJSONArray + JsonObject employeeJsonObject = employeesJsonArray.get(0).getAsJsonObject(); + String firstName = employeeJsonObject.get("firstName").getAsString(); + System.out.println("First Name of the employee at index 0: "+firstName); + } } ``` @@ -274,13 +277,13 @@ Get the code for [ParseJSONUsingGSON.java](https://github.com/coderolls/blogpost Output: ```java -Parsing the json string in java using Gson...... +Parsing the JSON string in Java using Gson...... Name: coderolls Street: 1600 Pennsylvania Avenue NW -Printing the employess json array: +Printing the employees JSON array: [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}] First Name of the employee at index 0: John @@ -302,7 +305,7 @@ Gradle: ``` compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1' ``` -You can refer the [json-simple project page.java](https://code.google.com/archive/p/json-simple/). +You can refer to the [json-simple project page.java](https://code.google.com/archive/p/json-simple/). Example: @@ -315,69 +318,69 @@ import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** - * A program to parse JSON strin in Java using json-simple + * A program to parse JSON string in Java using json-simple * @author Gaurav Kukade at coderolls.com */ public class ParseJSONUsingJsonSimple { - public static void main(String[] args) { - //take json as string - String jsonString = "{" - + " \"name\": \"coderolls\"," - + " \"type\": \"blog\"," - + " \"address\": {" - + " \"street\": \"1600 Pennsylvania Avenue NW\"," - + " \"city\": \"Washington\"," - + " \"state\": \"DC\"" - + " }," - + " \"employees\": [" - + " {" - + " \"firstName\": \"John\"," - + " \"lastName\": \"Doe\"" - + " }," - + " {" - + " \"firstName\": \"Anna\"," - + " \"lastName\": \"Smith\"" - + " }," - + " {" - + " \"firstName\": \"Peter\"," - + " \"lastName\": \"Jones\"" - + " }" - + " ]" - + "}"; - - System.out.println("Parsing the json string in java using json-simple......\n"); - - JSONParser parser = new JSONParser(); - JSONObject coderollsJSONObject = new JSONObject(); - try { - coderollsJSONObject = (JSONObject) parser.parse(jsonString); - } catch (ParseException e) { - e.printStackTrace(); - } - - //now we can access the values - String name = (String) coderollsJSONObject.get("name"); - System.out.println("Name: "+name+"\n"); - - //we can get the JSON object present as value of any key in the parent JSON - JSONObject addressJSONObject = (JSONObject) coderollsJSONObject.get("address"); - - //access the values of the addressJSONObject - String street = (String) addressJSONObject.get("street"); - System.out.println("Street: "+street+"\n"); - - - //we can get the json array present as value of any key in the parent JSON - JSONArray employeesJSONArray = (JSONArray) coderollsJSONObject.get("employees"); - System.out.println("Printing the employess json array: \n"+employeesJSONArray.toString()+"\n"); - - //we can get individual json object at an index from the employeesJSONArray - JSONObject employeeJSONObject = (JSONObject) employeesJSONArray.get(0); - String firstName = (String) employeeJSONObject.get("firstName"); - System.out.println("First Name of the employee at index 0: "+firstName); - } + public static void main(String[] args) { + //Take JSON as string + String jsonString = "{" + + " \"name\": \"coderolls\"," + + " \"type\": \"blog\"," + + " \"address\": {" + + " \"street\": \"1600 Pennsylvania Avenue NW\"," + + " \"city\": \"Washington\"," + + " \"state\": \"DC\"" + + " }," + + " \"employees\": [" + + " {" + + " \"firstName\": \"John\"," + + " \"lastName\": \"Doe\"" + + " }," + + " {" + + " \"firstName\": \"Anna\"," + + " \"lastName\": \"Smith\"" + + " }," + + " {" + + " \"firstName\": \"Peter\"," + + " \"lastName\": \"Jones\"" + + " }" + + " ]" + + "}"; + + System.out.println("Parsing the JSON string in Java using json-simple......\n"); + + JSONParser parser = new JSONParser(); + JSONObject coderollsJSONObject = new JSONObject(); + try { + coderollsJSONObject = (JSONObject) parser.parse(jsonString); + } catch (ParseException e) { + e.printStackTrace(); + } + + //now we can access the values + String name = (String) coderollsJSONObject.get("name"); + System.out.println("Name: "+name+"\n"); + + //we can get the JSON object present as the value of any key in the parent JSON + JSONObject addressJSONObject = (JSONObject) coderollsJSONObject.get("address"); + + //access the values of the addressJSONObject + String street = (String) addressJSONObject.get("street"); + System.out.println("Street: "+street+"\n"); + + + //we can get the JSON array present as the value of any key in the parent JSON + JSONArray employeesJSONArray = (JSONArray) coderollsJSONObject.get("employees"); + System.out.println("Printing the employees JSON array: \n"+employeesJSONArray.toString()+"\n"); + + //we can get individual JSON objects at an index from the employeesJSONArray + JSONObject employeeJSONObject = (JSONObject) employeesJSONArray.get(0); + String firstName = (String) employeeJSONObject.get("firstName"); + System.out.println("First Name of the employee at index 0: "+firstName); + } } ``` @@ -385,13 +388,13 @@ Get the code for [ParseJSONUsingJsonSimple.java](https://github.com/coderolls/bl Output: ```java -Parsing the json string in java using json-simple...... +Parsing the JSON string in Java using json-simple...... Name: coderolls Street: 1600 Pennsylvania Avenue NW -Printing the employess json array: +Printing the employees JSON array: [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}] First Name of the employee at index 0: John @@ -399,20 +402,6 @@ First Name of the employee at index 0: John ## Conclusion -All three libraries allow you create a JSON object from the json string but I found the JSON-Java is easy to use. +All three libraries allow you to create a JSON object from the JSON string but I found the JSON-Java is easy to use. You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. - --------------- - -You can support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [How To Create UUID in Java?](https://coderolls.com/create-uuid-in-java/) -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) diff --git a/_posts/java-programs/2022-10-13-largest-element-in-an-array.md b/_posts/java-programs/2022-10-13-largest-element-in-an-array.md new file mode 100644 index 0000000..8f42caa --- /dev/null +++ b/_posts/java-programs/2022-10-13-largest-element-in-an-array.md @@ -0,0 +1,170 @@ +--- +layout: post +title: "Java Program To Find Largest Element In An Array (3 Ways)" +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In this tutorial, we will see a Java program to find the largest element in an array." +--- + +In this tutorial, we will see how to find the largest element in an array. + +## Introduction + +We will take an array of integers `arr` and write a program to find the largest number from `arr`. Please note that `arr` is not a sorted array. ex. `{2, 5, 9, 8, 11}` + +## Java Program to find the largest element in an array + +### 1. Using for loop iteration + +In this way, we are iterating over an array using a for loop to find the largest number. + +```java +/** + * A Java program to find the largest number in an array + * using for loop iteration. + * + * @author coderolls.com + * + */ +public class LargestElementInArray { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11}; + + int largestElement = getLargest(arr); + System.out.println("The largest element in an array 'arr' is: "+ largestElement); + } + + private static int getLargest(int[] arr) { + int n = arr.length; + int largest = arr[0]; + + for(int i=0; iarr[0]) { + largest = arr[i]; + } + } + return largest; + } +} +``` + +Output: + +``` +The largest element in an array 'arr' is: 11 +``` + +#### Explanation: + +1. In the main method, we have taken a sample array `arr = {2, 5, 9, 8, 11};` and passed it as a parameter to the `getLargest()` method to return the largest number in an array `arr`. +2. In the `getLargest()` method we have stored the length of an array `aar` into int variable n using the `arr.length` method and also we have assigned the number at index `0` as the current largest number. So we have stored `arr[0]` to int variable `largest`. +3. In a for loop, we are iterating over the array arr and checking if there is a larger number at index `i` than the current largest number. ( We had assigned `arr[0]` as the current most significant number to start with in step 2.) +4. If the number at index `i` is larger than the current largest number i.e. `largest`, we will copy it to largest and continue iterating. OR if the number at index i is smaller or equal to the current largest number i.e `largest` we will ignore and continue iterating. +5. At the last, we will return the largest, which has the largest number in an array. + +### 2. Using `Arrays.sort()` + +As the array is not sorted, we can sort it using the `Arrays.sort()` method. So the last element of an array will be the largest element of an array. + +```java +import java.util.Arrays; + +/** + * A Java program to find the largest number in an array + * using Arrays.sort(). + * + * Arrays.sort() sort the array in natural sorting order + * + * @author coderolls.com + * + */ +public class LargestElementInArrayUsingArrays { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11}; + + int largestElement = getLargest(arr); + System.out.println("The largest element in an array 'arr' " + + "using Array.sort() is: "+ largestElement); + } + + private static int getLargest(int[] arr) { + Arrays.sort(arr); + return arr[arr.length-1]; + } +} +``` + +Output: + +``` +The largest element in an array 'arr' using Array.sort() is:11 +``` + +#### Explanation: + +1. In the main method, we have taken a sample array `arr = {2, 5, 9, 8, 11};` and passed it as a parameter to the `getLargest()` method to return the largest number in an array `arr`. +2. In the `getLargest()` method, we have sorted an array `arr` in natural sorting order using the `Arrays.sort()` method. +3. Once we sort the array in natural sorting order, we will have the largest number at the end of the array. We can get the last number of an array as `arr[arr.length-1]` to return it. + +### 3. Using Java 8 Streams API + +Java 8 Streams API provides various methods to perform data processing operations on data sources. We can create a stream of an array and the `max()` method will return the maximum element of this stream. + +```java +import java.util.Arrays; +/** + * A Java program to find the largest number in an array + * using Java 8 Streams API. + * + * max() returns the maximum element of this stream + * + * @author coderolls.com + * + */ +public class LargestElementInArrayUsingStream { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11}; + + int largestElement = getLargest(arr); + System.out.println("The largest element in an array 'arr'" + + "using Java 8 Streams API is: "+ largestElement); + } + + private static int getLargest(int[] arr) { + int largest = Arrays.stream(arr).max().getAsInt(); + return largest; + } +} +``` + +Output: + +``` +The largest element in an array 'arr' using Java 8 Streams API is: 11 +``` + +#### Explanation: + +1. In the main method, we have taken a sample array `arr = {2, 5, 9, 8, 11};` and passed it as a parameter to the `getLargest()` method to return the largest number in an array `arr`. +2. In the `getLargest()` method, we have created a Stream of array `arr`. The `max()` returns the maximum element of this stream. We are using the `getAsInt()` method to get the result as `int` and store it in the int variable `largest`. +3. Return the `largest`. + +## Conclusion: + +We have seen a few Java programs to find the largest element in an array. + +1. We can find the largest element in an array by iterating over an array and comparing each element. +2. The second way to find the largest element in an array is by sorting an array in a natural sorting order and returning the last element. +3. The third way to find the largest element in an array is by using the Java 8 Streams API's max method. + +--- + +The example Java programs used in the above article can be found at this GitHub repository, [blogpost-coding-examples/java-programs/largest-element-in-an-array/](https://github.com/coderolls/blogpost-coding-examples/tree/main/java-programs/largest-element-in-an-array). + +Please write your thoughts in the comment section below. diff --git a/_posts/java-programs/2022-10-17-second-largest-element-in-an-array.md b/_posts/java-programs/2022-10-17-second-largest-element-in-an-array.md new file mode 100644 index 0000000..a519ee0 --- /dev/null +++ b/_posts/java-programs/2022-10-17-second-largest-element-in-an-array.md @@ -0,0 +1,147 @@ +--- +layout: post +title: "Java Program To Find Second Largest Element In An Array" +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In This tutorial, we will see a Java program to find the second largest element in an array." +--- + +In This tutorial, we will see a Java program to find the second largest element in an array. + +## Introduction + +In the previous article, [Java Program To Find Largest Element In An Array (3 Ways)](/largest-element-in-an-array/), we have seen a few programs to find the largest element in an array. Today, we will see a program to find the second-largest element in an array. + +Here we will take an array of integers `arr` and please note that `arr` is not a sorted array. ex. `{2, 5, 9, 8, 11, 18, 13}` + +## Java Program to find the second largest element in an array + +### 1. Iterating over an array + +We will iterate over an array using the `for` loop to find the second largest element in an array. + +```java +/** + * A Java program to find the second-largest number in an array + * by iterating over an array using a for loop. + * + * @author coderolls.com + */ +public class SecondLargestElementInArray { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11, 18, 13}; + + int secondLargest = getSecondLargest(arr); + System.out.println("The second largest element in " + + "an array 'arr'is: "+ secondLargest); + } + + private static int getSecondLargest(int[] arr) { + int n =arr.length; + int largest =arr[0]; + int secondLargest = -1; + + for(int i=0; ilargest) { + //if you found the new largest, + //copy current largest to second largest and + //copy current element arr[i] to largest + secondLargest = largest; + largest = arr[i]; + }else if(arr[i]!=largest) { + // if the current element arr[i] is not the largest and + // still larger than the current secondLargest + // then copy it to secondLargest + if(arr[i]>secondLargest) { + secondLargest = arr[i]; + } + } + } + return secondLargest; + } +} +``` + +Output: + +``` +The second largest element in an array 'arr' is: 13 +``` + +#### Explanation: + +1. In the main method, we have taken a sample array `arr = {2, 5, 9, 8, 11, 18, 13};` and passed it as a parameter to the `getSecondLargest()` method to return the largest number in an array `arr`. + +2. In the `getSecondLargest()` method we have stored the length of an array `arr` into int variable n using the `arr.length` method. To start the program we have assigned the number at index `0` i.e. `arr[0]` as the current largest number i.e. `largest`. Also, we have assigned the value `-1` the current second largest number `secondLargest`. + + > If the array contains all the similar numbers, there will be no second-largest number in an array. ex. `arr= {12,12,12,12}` So it will return -1 in that case. + +3. Using the `if` statement we are checking if the current number at index `i` i.e. `arr[i]` is larger than the current largest number i.e `largest`, we will + + 1. assign the current largest number `largest` to `secondLargest` + 2. store current number i.e. `arr[i]` as `largest` + +4. Next, we will check if the current number `arr[i]` is not the current largest number `largest` but is still larger than the current second largest number, we will store it to the `secondLargest`. + +5. Return `secondLargest`. + +### 2. Using `Arrays.sort()` + +As the array is not sorted, we can sort it using the `Arrays.sort()` method in natural sorting order. So the second last element of an array will be the second largest element of an array. + +```java +import java.util.Arrays; + +/** + * A Java program to find the second-largest number in an array + * using Arrays.sort() method. + * + * @author coderolls.com + */ + public class SecondLargestElementInArrayUsingArrays { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11, 18, 13}; + + int secondLargest = getSecondLargest(arr); + System.out.println("The second largest element in" + + "an array 'arr' is using Arrays.sort() :"+ secondLargest); + } + + private static int getSecondLargest(int[] arr) { + Arrays.sort(arr); + // return second largest, so length-2 + return arr[arr.length-2]; + } +} +``` + +Output: + +``` +The second largest element in an array 'arr' is using Arrays.sort(): 13 +``` + +#### Explanation: + +1. In the main method, we have taken a sample array `arr = {2, 5, 9, 8, 11, 18, 13};` and passed it as a parameter to the `getSecondLargest()` method to return the largest number in an array `arr`. +2. In the `getSecondLargest()` method, we have sorted an array `arr` in natural sorting order using the `Arrays.sort()` method. +3. Once we sort the array in natural sorting order, we will have the second largest number as the second last element of the array. We can get the second last number of an array as `arr[arr.length-2]` to return it. + +> In this way ( 2. Using `Arrays.sort()`) even if all the numbers of an array are similar ex. `arr= {12,12,12,12}`, i.e. when there is no second largest element, it will return that same number. + +## Conclusion + +We can find the second largest element in an array in the following two ways, + +1. By iterating over an array using a for loop to compare the largest and second largest number. +2. By sorting an array in a natural sorting order and returning the second last element. i.e. `arr[arr.length-2]` + +--- + +The example Java programs used in the above article can be found at this GitHub repository, [blogpost-coding-examples/java-programs/second-largest-element-in-an-array/](https://github.com/coderolls/blogpost-coding-examples/tree/main/java-programs/second-largest-element-in-an-array). + +Please write your thoughts in the comment section below. + diff --git a/_posts/java-programs/2022-10-26-check-if-array-is-sorted-java.md b/_posts/java-programs/2022-10-26-check-if-array-is-sorted-java.md new file mode 100644 index 0000000..a019bfd --- /dev/null +++ b/_posts/java-programs/2022-10-26-check-if-array-is-sorted-java.md @@ -0,0 +1,86 @@ +--- +layout: post +title: "Check If An Array Is Sorted In Java" +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In this tutorial, we will see a Java program to check if an array is sorted in Java." +--- + +In this tutorial, we will see a Java program to check if an array is sorted in Java. + +## Introduction + +We will write a Java program to check if the array is sorted or not. + +We will take a sample integer array `arr = {1, 3 , 5, 9};` We will return `true` if the array is sorted or `false` if the array is not sorted. + +## Check if an array is sorted or not in Java + +```java +/** + * A Java program to check if the array of integers is sorted + * or not using for loop iteration. + * + * @author coderolls.com + * + */ +public class SortedArrayTester { + + public static void main(String[] args) { + int[] arr = {2, 5, 9, 8, 11, 18, 13}; + + boolean isSorted = isArraySorted(arr); + + //Use this to check the sorted case + + /* + * int[] arr2 = {2, 5, 9, 11, 18}; + * boolean isSorted = isArraySorted(arr2); + */ + if(isSorted) { + System.out.println("The array is sorted."); + } + else { + System.out.println("The array is not sorted."); + } + } + + private static boolean isArraySorted(int[] arr) { + int n = arr.length; + + for(int i=0; iarr[i+1]) { + return false; + } + } + return true; + } +} +``` + +Output: + +``` +The array is not sorted. +``` + +### Explanation: + +1. In the `main` method we are taking a sample array `arr` and passing it to the `isArraySorted()` method to check if the array is sorted or not. This method returns a `boolean` value. `true` - if an array is sorted, `false` - if an array is not sorted +2. In the `isArraySorted()` method, we are iterating over an array from index `0` to `n-1`, (`n`-length of the array) and we will check if the current number (number at index `i`) is greater than the next number ( number at index `i+1`). +3. If the current number (number at index `i`) is greater than the next number ( number at index `i+1`), that means the array is not sorted, and we will return `false`. +4. If the control came out of the for loop, that means the array is sorted and we will return `true`. +5. When we receive the `boolean` result `isSorted` we will print the output. + +## Conclusion + + we can check if the primitive arrays are sorted or not by comparing the adjacent array elements. + +--- + +The example Java programs used in the above article can be found at this GitHub repository, [blogpost-coding-examples/java-programs/second-largest-element-in-an-array/](https://github.com/coderolls/blogpost-coding-examples/tree/main/java-programs/second-largest-element-in-an-array). + +Please write your thoughts in the comment section below. diff --git a/_posts/java-programs/2023-10-21-remove-all-whitespaces-from-string.md b/_posts/java-programs/2023-10-21-remove-all-whitespaces-from-string.md new file mode 100644 index 0000000..19d7bf7 --- /dev/null +++ b/_posts/java-programs/2023-10-21-remove-all-whitespaces-from-string.md @@ -0,0 +1,51 @@ +--- +layout: post +title: "Java Program To Remove All Whitespaces From The Given String." +author: gaurav +categories: [String, Java Programs] +toc: false +description: "In this tutorial, we will see how to remove all whitespaces from the given String." +--- + +## Remove whitespaces from all over the String + +We can replace all whitespaces with empty string using `String.replaceAll() method. + +The replace all methods accept regex string and replacement string as input params. And return the replaced string. + +We can use the `"\\s+"` regex expression to find all the whitespaces from the given input string. + +**Java Program** + +```java +/** + * A Java program to remove all the whitespaces from the given string. + * By coderolls.com + */ +public class RemoveWhitespaces { + + public static void main(String[] args) { + + String exampleString = "It is an example string."; + + System.out.println("The example String is as given below: "); + System.out.println(exampleString); + + //Remove all whitespaces from the example string + String stringWithoutWhitespaces = exampleString.replaceAll("\\s+", ""); + + System.out.println("\nThe example String after removing all the whitespaces is as given below: "); + System.out.println(stringWithoutWhitespaces); + } +} +``` + +**Output** + +``` +The example String is given below: +It is an example string. + +The example String after removing all the whitespaces is as given below: +Itisanexamplestring. +``` diff --git a/_posts/java-programs/2023-10-30-remove-all-leading-and-trailing-whitespaces-from-string.md b/_posts/java-programs/2023-10-30-remove-all-leading-and-trailing-whitespaces-from-string.md new file mode 100644 index 0000000..00f6a5a --- /dev/null +++ b/_posts/java-programs/2023-10-30-remove-all-leading-and-trailing-whitespaces-from-string.md @@ -0,0 +1,142 @@ +--- +layout: post +title: "Java Program To Remove All Leading and Trailing Whitespaces From The Given String." +author: gaurav +categories: [String, Java Programs] +toc: true +description: "In this tutorial, we will see how to remove all the leading and trailing whitespaces from the given String." +--- + +In this tutorial, we will see how to remove all the leading and trailing whitespaces from the given String. + +## Introduction + +We can remove all the leading and trailing spaces from the string in two ways, + +1. Using the regex expressions with `String.replaceAll()` +2. Using the ready-made `String.trim()` method + +### 1. Using the regex expressions with `String.replaceAll()` + +We can use the following regex expressions to remove leading and trailing whitespaces from the given input string. + +We are simply replacing all leading and trailing whitespaces with empty strings. + +`^\s+` - remove all leading whitespaces + +`\s+$` - remove all trailing whitespaces + +**Java program** + +```java +/** + * A Java program to remove all the leading and trailing + * whitespaces from the given string using the String.replaceAll() method. + * By coderolls.com + */ +public class RemoveLeadingAndTrailingWhitespaces { + + public static void main(String[] args) { + + String exampleString = " Let's learn Java "; + String result = ""; + + System.out.println("(We are printing the example string in between the three hyphens" + + " to show leading and trailing spaces)"); + System.out.println("\nThe example String is as given below: "); + + //We are printing the example string in between the three hyphens + //to show leading and trailing spaces + System.out.println("---" + exampleString + "---"); + + //Removing all leading whitespace + result = exampleString.replaceAll("^\\s+", ""); + + // removing all trailing whitespace from stringWithoutLeadingOrTrailingSpaces + result = result.replaceAll("\\s+$", ""); + + System.out.println("\nThe example String after removing the leading and trailing spaces is as " + + "given below: "); + System.out.println("---" + result + "---"); + } +} +``` + +**Output** + +``` +(We are printing the example string in between the three hyphens to show leading and trailing spaces) + +The example String is given below: +--- Let's learn Java --- + +The example String after removing the leading and trailing spaces is as given below: +---Let's learn Java--- +``` + +### 2. Using the ready-made `String.trim()` method + +**We can remove all the leading (at the start of the sting ) and trailing (at the end of the string) using the `String.trim()` method.** + +It is a simple way as compared to 1st way. + +Here are using the ready-made method and we do not need to remember the regex expression to find all the leading and trailing spaces. + +**Java Program** + +```java +/** + * A Java program to remove all the leading and trailing + * whitespaces from the given string using the String.trim() method. + * By coderolls.com + */ +public class TrimMethodExample { + + public static void main(String[] args) { + String exampleString = " Let's learn Java "; + + System.out.println("(We are printing the example string in between the three hyphens to show " + + "leading and trailing spaces)"); + System.out.println("\nThe example String is as given below: "); + + //We are printing the example string in between the three hyphens + //to show leading and trailing spaces + System.out.println("---" + exampleString + "---"); + + String result = exampleString.trim(); + System.out.println("\nThe example String after removing the leading and trailing spaces is as " + + "given below: "); + System.out.println("---" + result + "---"); + } +} + +``` + +**Output** + +``` +(We are printing the example string in between the three hyphens to show leading and trailing spaces) + +The example String is as given below: +--- Let's learn Java --- + +The example String after removing the leading and trailing spaces is as given below: +---Let's learn Java--- +``` + +## Conclusion + +We can remove all the leading and trailing whitespaces from the given String as follows. + +1. replace all the leading and trailing whitespaces with an empty string + ```java + result = exampleString.replaceAll("^\\s+", ""); // remove leading whitespaces + result = result.replaceAll("\\s+$", ""); // then removes trailing whitespaces + ``` + +2. Use the ready-made `String.trim()` method. + ```java + String result = exampleString.trim(); + ``` + + diff --git a/_posts/java-programs/2023-11-06-duplicate-characters-count-in-string.md b/_posts/java-programs/2023-11-06-duplicate-characters-count-in-string.md new file mode 100644 index 0000000..d7ff885 --- /dev/null +++ b/_posts/java-programs/2023-11-06-duplicate-characters-count-in-string.md @@ -0,0 +1,84 @@ +--- +layout: post +title: "Java Program To Find Duplicate Characters And Their Count In a String." +author: gaurav +categories: [String, Java Programs] +toc: true +description: "In this tutorial, we will see how to find duplicate characters and their count in the string using the Java program." +--- + +In this tutorial, we will see how to find duplicate characters and their count in the string using the Java program. + +We will be iterating over the string and then we will be using the HashMap to store characters and their count as a key and value pair. + +**Java Program To Find Duplicate Characters And Their Count Form The String** + +```java +import java.util.Map; +import java.util.HashMap; + +/** + * Java program to print duplicate characters and their count + * By coderolls.com + */ +public class CharactersCount { + + public static void main(String[] args) { + + String exampleString = "This is an example string."; + System.out.println("The example string is as given below: "); + System.out.println(exampleString); + + Map map = new HashMap<>(); + + for(int i=0; i entry : map.entrySet()) { + if (entry.getValue()>1) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } + } + + } +} +``` + +**Explanation** + +1. We have an example string to get duplicate characters and their respective count from it. +2. We have created a new HashMap with `Character` as the key and `Integer` as the value. +3. We will be iterating over the example string using the for loop. +4. We can use the `String.charAt(index)` method to get the character at index `index`. +5. We will check if the map contains the key or not. If present, that means this character was also present one or more times in the string before. So we will fetch its count and increase it by one. +6. If the map does not contain the key, that means we are getting characters for the first time. We will simply add the character and it counts as 1. +7. In the next for loop, we will print the duplicate characters and their respective counts. If the value is greater than 1 it means the character came more than one time in the string and we can print it. + +**Output** + +``` +The example string is given below: +This is an example string. + +The duplicate characters and their respective count are given below: + : 4 +a: 2 +e: 2 +i: 3 +n: 2 +s: 3 +``` + diff --git a/_posts/java-programs/2023-11-13-check-if-two-arrays-are-equal.md b/_posts/java-programs/2023-11-13-check-if-two-arrays-are-equal.md new file mode 100644 index 0000000..0a6f526 --- /dev/null +++ b/_posts/java-programs/2023-11-13-check-if-two-arrays-are-equal.md @@ -0,0 +1,128 @@ +--- +layout: post +title: "Java Program To Check Two Arrays Are Equal" +author: gaurav +categories: [Java Programs, Array] +toc: true +description: "In this tutorial, we will see a Java program to check if two arrays are equal or not." +--- + +In this tutorial, we will see a Java program to check if two arrays are equal or not. + +We have x ways to check if the two Arrays are equal or not. + +1. Iterating over an array +2. Using the `Arrays.equal()` method + +## 1. Java Program To Check Two Arrays Are Equal By Iterating over an Array + +To check if the two arrays are equal or not, we can use the following strategy. + +If the lengths of the two arrays are not the same, these arrays are not equal. + +If the length is the same, we can iterate over an array and check if the elements are equal at the same indices. If yes, these arrays are equal. + +Let's have a look at the following Java program for better understanding. + +**Java Program** + +```java +/** + * Java program to check if the two arrays are equal or not + * by iterating over an array + * By coderolls.com + */ +public class ArrayEqual { + + public static void main(String[] args) { + int[] arr = {2, 3, 5, 6}; + int[] arr2 = {2, 3, 5, 6}; + int[] arr3 = {2, 3, 1, 4}; + int[] arr4 = {2, 3, 5, 6, 7, 4}; + + System.out.println("Comparing arr and arr2: "); + checkIfArraysAreEqual(arr, arr2); + + System.out.println("\nComparing arr and arr3: "); + checkIfArraysAreEqual(arr, arr3); + + System.out.println("\nComparing arr and arr4: "); + checkIfArraysAreEqual(arr, arr4); + } + + private static void checkIfArraysAreEqual(int[] arr, int[] arr2) { + boolean isEqual = true; + if (arr.length == arr2.length) { + for (int i=0; i duplicateElements = new HashSet<>(); + + for (int i=0; i duplicateElements = new HashSet<>(); + Arrays.sort(arr); + + for (int i=0; i duplicateElements = new HashSet<>(); + Set hashSet = new HashSet<>(); + + for (int i : arr) { + if (!hashSet.add(i)) { + duplicateElements.add(i); + } + } + System.out.println("Duplicate elements in array are :" + duplicateElements); + + } +``` + +## 4. Find duplicate elements in an array using the Java 8 Streams method + +In this method, we are using the Java 8 Streams method to find the duplicate elements from the input array. + +We have created a stream of an array. The `filter()` method accepts an expression and returns a boolean result. + +As we know, the Set always contains unique elements. The `set.add()` method returns true if the element is successfully added to the set, and false if the element already exists. + +We are filtering out the duplicate elements using the above logic and collecting them in another set. + +```java +private static void printDuplicatesByJava8Streams(int[] arr) { + System.out.println("\nFinding duplicate elements using the Java 8 Streams method."); + Set hashSet = new HashSet<>(); + + Set duplicateElements = Arrays.stream(arr).filter(i -> !hashSet.add(i)).boxed().collect(Collectors.toSet()); + System.out.println("Duplicate elements in array are :" + duplicateElements); + } +``` + + + +## Java Program to find duplicate elements in an array + +**Java Program** + +```java +import java.util.*; +import java.util.stream.Collectors; + +/** + * Java Program to find duplicate elements in an Array + * By coderolls.com + */ + +public class DuplicatesInArray { + + public static void main(String[] args) { + int[] arr = {1, 5, 6, 9, 2, 6, 9, 6, 3, 2, 1}; + System.out.print("The input array is as given: "); + System.out.println(Arrays.toString(arr)); + + printDuplicatesByIterating(arr); + + printDuplicatesBySorting(arr); + + printDuplicatesByHashSet(arr); + + printDuplicatesByJava8Streams(arr); + } + + + private static void printDuplicatesByIterating(int[] arr) { + System.out.println("\nFinding duplicate elements using the iterative method."); + Set duplicateElements = new HashSet<>(); + + for (int i=0; i duplicateElements = new HashSet<>(); + Arrays.sort(arr); + + for (int i=0; i duplicateElements = new HashSet<>(); + Set hashSet = new HashSet<>(); + + for (int i : arr) { + if (!hashSet.add(i)) { + duplicateElements.add(i); + } + } + System.out.println("Duplicate elements in array are :" + duplicateElements); + + } + + private static void printDuplicatesByJava8Streams(int[] arr) { + System.out.println("\nFinding duplicate elements using the Java 8 Streams method."); + Set hashSet = new HashSet<>(); + + Set duplicateElements = Arrays.stream(arr).filter(i -> !hashSet.add(i)).boxed().collect(Collectors.toSet()); + System.out.println("Duplicate elements in array are :" + duplicateElements); + } +} +``` + +**Output** + +``` +The input array is as given: [1, 5, 6, 9, 2, 6, 9, 6, 3, 2, 1] + +Finding duplicate elements using the iterative method. +Duplicate elements in array are :[1, 2, 6, 9] + +Finding duplicate elements using the sorting method. +Duplicate elements in array are :[1, 2, 6, 9] + +Finding duplicate elements using the HashSet method. +Duplicate elements in array are :[1, 2, 6, 9] + +Finding duplicate elements using the Java 8 Streams method. +Duplicate elements in array are :[1, 2, 6, 9] +``` diff --git a/_posts/java-programs/2023-12-04-sum-of-all-digits-in-a-number.md b/_posts/java-programs/2023-12-04-sum-of-all-digits-in-a-number.md new file mode 100644 index 0000000..9342d69 --- /dev/null +++ b/_posts/java-programs/2023-12-04-sum-of-all-digits-in-a-number.md @@ -0,0 +1,51 @@ +--- +layout: post +title: "Java Program To Calculate Sum Of All Digits Of A Number" +author: gaurav +categories: [Java Programs, Core Java] +toc: false +description: "In this tutorial, we will see a Java program to get the sum of all digits of a number in Java." +--- + +To calculate the sum of all digits of a number + +1. First, we will get a reminder of the input number by the modulo operator (%) and add it to the `sum` variable. +2. Second, we will divide the input number by 10 and assign it again to an input number variable. +3. We will repeat the above process until the input number is not equal to zero. +4. At the end we will have the sum of all the digits of a number in the `sum` variable. + +Let's a Java program to calculate the sum of all digits of a number. + +**Java Program** + +```java +/** + * A Java program to calculate the sum of all digits of a given number + * By coderolls.com + */ +public class SumOfAllDigits { + + public static void main(String[] args) { + int number = 1256; + int sum = sumOfAllDigits(number); + System.out.println("The sum of all digits of " + number + " is: "+ sum); + } + + private static int sumOfAllDigits(int number) { + int sum =0; + while(number!=0){ + int reminder = number%10; + sum = sum + reminder; + number = number/10; + } + return sum; + } +} +``` + +**Output** + +``` +The sum of all digits of 1256 is: 14 +``` + diff --git a/_posts/java-programs/2023-12-07-check-if-string-is-a-number-or-not.md b/_posts/java-programs/2023-12-07-check-if-string-is-a-number-or-not.md new file mode 100644 index 0000000..2941156 --- /dev/null +++ b/_posts/java-programs/2023-12-07-check-if-string-is-a-number-or-not.md @@ -0,0 +1,172 @@ +--- +layout: post +title: "Java Program To Check If the given String Is A Number or Not" +author: gaurav +categories: [Java Programs, Core Java] +toc: true +description: "In this tutorial, we will see a Java program to check if the given String is a number or not." +--- + +In this tutorial, we will see a Java program to check if the given String is a number or not. + +We can check it using the regex expression. + +## Java Program To Check If the Given String is Number or Not Using Regex Expression + +In the below program, we have simply used the regex expression to check whether the given string is numeric or not. + +The regex expression to check this is `-?\\d+` + +Here, + +`-?` --> negative sign, could have none or one + +`\\d+` --> one or more digits + +**Java Program** + +```java +import java.util.List; + +/** + * A Java program to check if the given String is a number or not. + * @author coderolls.com + */ +public class CheckIfNumber { + + public static void main(String[] args) { + List strings = List.of("95965", "Jack485", "-9859", "784Will", "056", "Google"); + for(String str : strings) { + boolean isNumber = isNumberOrNot(str); + if (isNumber) { + System.out.println("The String '" + str + "' is a Number."); + } else { + System.out.println("The String '" + str + "' is not a Number."); + } + } + + } + + /** + * A method checks if the input param string is numeric or not + * It uses a regex Expression + * -? --> negative sign, could have none or one + * \\d+ --> one or more digits + * @param str + * @return + */ + private static boolean isNumberOrNot(String str) { + return str.matches("-?\\d+"); + } +} +``` + +Output + +``` +The String '95965' is a Number. +The String 'Jack485' is not a Number. +The String '-9859' is a Number. +The String '784Will' is not a Number. +The String '056' is a Number. +The String 'Google' is not a Number. +``` + + + +## Java Program To Check If the Given String is Number or Not Using the `Character.isDigit()` method + +In this method, we are iterating over an array of characters of the String and checking if any character is a digit or not. + +If we find one or more digits in the string, the given string is not a number string or a number. + +```Java +import java.util.List; + +/** + * A Java program to check if the given String is a number or not. + * using the Character.isDigit() method. + * @author coderolls.com + */ +public class CheckIfNumber2 { + + public static void main(String[] args) { + List strings = List.of("95965", "Jack485", "-9859", "784Will", "056", "Google"); + for(String str : strings) { + boolean isNumber = isNumberOrNot(str); + if (isNumber) { + System.out.println("The String '" + str + "' is a Number."); + } else { + System.out.println("The String '" + str + "' is not a Number."); + } + } + + } + + /** + * A method checks if the input param string is numeric or not + * It uses a regex Expression + * -? --> negative sign, could have none or one + * \\d+ --> one or more digits + * @param str + * @return + */ + private static boolean isNumberOrNot(String str) { + char[] chars = str.toCharArray(); + for(int i=0; i= 0; --i) { + reversedString = reversedString + str.charAt(i); + } + if (str.equalsIgnoreCase(reversedString)) { + System.out.println("The String '" + str + "' is a Palindrome String."); + } else { + System.out.println("The String '" + str + "' is not a Palindrome String."); + } + } +} +``` + +Output + +``` +The String 'racecar' is a Palindrome String. +``` diff --git a/_posts/java-programs/2023-12-18-check-for-palindrome-number.md b/_posts/java-programs/2023-12-18-check-for-palindrome-number.md new file mode 100644 index 0000000..d649675 --- /dev/null +++ b/_posts/java-programs/2023-12-18-check-for-palindrome-number.md @@ -0,0 +1,49 @@ +--- +layout: post +title: "Java Program To Check If the given Number Is Palindrome or Not" +author: gaurav +categories: [Java Programs, Core Java] +toc: false +description: "In this tutorial, we will see a Java program to check if the given Number is palindrome or not." +--- + +In this tutorial, we will see a Java program to check if the given Number is palindrome or not. + +## Java Program To Check If the given Number Is Palindrome or Not + +```java +/** + * A Java program to check if the given number is a palindrome or not. + * @author coderolls.com + */ +public class PalindromeNumber { + + public static void main(String[] args) { + int num = 125521; + checkIfPalindrome(num); + } + + private static void checkIfPalindrome(int num) { + int numCopy = num; + int reversedNumber = 0; + int reminder; + + while(numCopy != 0){ + reminder = numCopy % 10; + reversedNumber = reversedNumber *10 + reminder; + numCopy /=10; + } + if (reversedNumber == num) { + System.out.println("The Number '" + num + "' is a Palindrome Number."); + } else { + System.out.println("The Number '" + num + "' is not a Palindrome Number."); + } + } +} +``` + +Output + +``` +The Number '125521' is a Palindrome Number. +``` diff --git a/_posts/java-programs/2023-12-21-check-if-number-is-binary.md b/_posts/java-programs/2023-12-21-check-if-number-is-binary.md new file mode 100644 index 0000000..29e83d7 --- /dev/null +++ b/_posts/java-programs/2023-12-21-check-if-number-is-binary.md @@ -0,0 +1,109 @@ +--- +layout: post +title: "Java Program To Check If The Given Number is Binary Or Not" +author: gaurav +categories: [Java Programs, Core Java] +toc: true +description: "In this tutorial, we will see a Java program to check if the given number is binary or not." +--- + +In this tutorial, we will see a Java program to check if the given number is binary or not. + +We can check if the given number is binary or not by the following ways + +1. Checking if the number contains a `1` or `0` digits by the reminder and divide method +2. Convert the number to String + +## 1. Java program to check if the given number is binary or not by checking if the number contains `1` or `0` digit by the reminder and divide method + +In the below program, we are getting each digit of the given input number one by one using the reminder method. + +If the digit is any other than the `0` and `1`, i.e. number is not Binary and it returns `false`. Otherwise, it will return `true`. + +**Java Program** + +```java +public class BinaryChecker { + + public static void main(String[] args) { + long input = 101110001; // Change this to the number you want to check. + boolean isBinary = isBinaryNumber(input); + + if (isBinary) { + System.out.println(input + " is a binary number."); + } else { + System.out.println(input + " is not a binary number."); + } + } + + public static boolean isBinaryNumber(long num) { + while (num > 0) { + long digit = num % 10; + if (digit != 0 && digit != 1) { + return false; // The number contains a non-binary digit. + } + num /= 10; + } + return true; // All digits are 0 or 1, so it's a binary number. + } +} +``` + +**Output** + +``` +101110001 is a binary number. +``` + +## 2. Java program to check if the given number is binary or not by converting the number to a String + +In the below program, we have used the regex expression to check if the number has only `0` or `1` digits. + +We can do it as follows + +1. We are converting the given input number to a string + +2. Using the regex pattern matcher to check whether the number string i.e. `inputStr` contains only `0` or `1` digits. +3. If we find any `0` or `1` in the number, the number is binary and it returns `true`, Otherwise it returns `false` + +**Java Program** + +```java +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +public class BinaryChecker2 { + + public static void main(String[] args) { + long input = 10110101; + String inputStr = String.valueOf(input); + boolean isBinary = isBinary(inputStr); + + if (isBinary) { + System.out.println(inputStr + " is a binary number."); + } else { + System.out.println(inputStr + " is not a binary number."); + } + } + + public static boolean isBinary(String num) { + // Define a regular expression pattern to match binary numbers (0 or 1). + String binaryPattern = "^[01]+$"; + + // Create a Pattern object. + Pattern pattern = Pattern.compile(binaryPattern); + + // Use a Matcher to match the input string with the pattern. + Matcher matcher = pattern.matcher(num); + + // Return true if the input string is a binary number; otherwise, return false. + return matcher.matches(); + } +} +``` + +**Output** + +``` +10110101 is a binary number. +``` diff --git a/_posts/java-programs/2023-12-26-check-if-number-is-prime.md b/_posts/java-programs/2023-12-26-check-if-number-is-prime.md new file mode 100644 index 0000000..d879586 --- /dev/null +++ b/_posts/java-programs/2023-12-26-check-if-number-is-prime.md @@ -0,0 +1,51 @@ +--- +layout: post +title: "Java Program To Check If The Given Number is Prime or Not" +author: gaurav +categories: [Java Programs, Core Java] +toc: true +description: "In this tutorial, we will see a Java program to check if the given number is Prime or Not." +--- + +In this tutorial, we will see a Java program to check if the given number is prime or not. + +## What is a Prime Number? + +A number that can be divided exactly only by itself and 1. + +For example 7, 17 and 41. + +## Java Program To Check If The Given Number is Binary Or Not + +```java +public class PrimeNumber { + + public static void main(String[] args) { + int num = 41; + boolean isPrimeNumber = isPrime(num); + if (isPrimeNumber) { + System.out.println(num + " is a prime number."); + } else { + System.out.println(num + " is not a prime number."); + } + } + + public static boolean isPrime(int num) { + if (num <= 1) { + return false; + } + for (int i = 2; i <= Math.sqrt(num); i++) { + if (num % i == 0) { + return false; + } + } + return true; + } +} +``` + +Output + +``` +41 is a prime number. +``` diff --git a/_posts/java-programs/2023-12-28-print-fibonacci-series.md b/_posts/java-programs/2023-12-28-print-fibonacci-series.md new file mode 100644 index 0000000..ddc82d3 --- /dev/null +++ b/_posts/java-programs/2023-12-28-print-fibonacci-series.md @@ -0,0 +1,48 @@ +--- +layout: post +title: "Java Program To Print The Fibonacci Series Up To A Given Number of terms" +author: gaurav +categories: [Java Programs, Core Java] +toc: true +description: "In this tutorial, we will see a Java program to print the Fibonacci series up to a given number of terms." +--- + +In this tutorial, we will see a Java program to print the Fibonacci series up to a given number of terms. + +## What is the Fibonacci Series? + +Fibonacci Series is the **sequence of numbers in which each number in the sequence is equal to the sum of two numbers before it**. + +Fibonacci Series: + +0, 1, 1, 2, 3, 5, 8, 13, 21............. + +## Java Program To Print The Fibonacci Series Up To A Given Number of terms + +```java +public class FibonacciSeries { + + public static void main(String[] args) { + int terms = 15; + System.out.println("Fibonacci Series:"); + printFibonacciSeries(terms); + } + + public static void printFibonacciSeries(int num) { + int a = 0, b = 1; + for (int i = 0; i < num; i++) { + System.out.print(a + " "); + int temp = a + b; + a = b; + b = temp; + } + } +} +``` + +Output + +``` +Fibonacci Series: +0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 +``` diff --git a/_posts/java-string/2019-11-30-compare-two-strings-lexicographically-in-java.md b/_posts/java-string/2019-11-30-compare-two-strings-lexicographically-in-java.md index 116bb3c..cd64a31 100644 --- a/_posts/java-string/2019-11-30-compare-two-strings-lexicographically-in-java.md +++ b/_posts/java-string/2019-11-30-compare-two-strings-lexicographically-in-java.md @@ -3,6 +3,7 @@ layout: post title: "How To Compare Two Strings Lexicographically In Java" author: gaurav categories: [ Java, Core Java, String] +toc: true description: "In this article, we will learn how to compare two strings lexicographically in java." featured: false comments: true @@ -207,6 +208,4 @@ In a first way, I am using the `compareTo()` method of the Java and in the secon Most noteworthy, In `compareTo()` method of the Java, the comparison is based on the Unicode value of each character in the strings. -If you found this article worth, please [Give me a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - Have you tried the `compareTo()` method or created a user-defined method to compare two string lexicographically? How was your experience? Have you faced any problem? please write down the same in the comment section below. diff --git a/_posts/java-string/2019-12-02-reverse-a-string-in-java.md b/_posts/java-string/2019-12-02-reverse-a-string-in-java.md index aebc940..4863b8d 100644 --- a/_posts/java-string/2019-12-02-reverse-a-string-in-java.md +++ b/_posts/java-string/2019-12-02-reverse-a-string-in-java.md @@ -4,7 +4,8 @@ title: "How To Reverse A String In Java (5 ways)" author: gaurav categories: [ Java, Core Java, String] description: "In this article, we will learn how to reverse strings in Java. I have write down 5 diffrent ways to reverse strings. Have a look!" -featured: false +featured: true +toc: true --- In this article, we will learn how to reverse strings in Java. I have write down 5 diffrent ways to reverse strings. Have a look! @@ -258,10 +259,10 @@ public class ReverseStringUsingReverseMethodOfStringBuilder { StringBuilder stringBuilder = new StringBuilder(blogName); - stringBuilder = stringBuilder.reverse(); + String reversedString = stringBuilder.reverse().toString(); System.out.print("The reversed string of the '"+blogName+"' is: "); - System.out.println(stringBuilder); + System.out.println(reversedString); } } ``` @@ -367,8 +368,6 @@ We can reverse the string in multiple ways. I have listed the five ways below. These are the ways we can reverse the string in Java. -If you found this article worth, please [Give me a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - If you have any queries or any suggestions or if you find any mistakes in the article or in the code snippet given above please feel free to comment below. Have you try the different ways to reverse the string in the java? or do you know the most simple way? please write it down in the comment section below. diff --git a/_posts/java-string/2019-12-10-compare-strings-in-java.md b/_posts/java-string/2019-12-10-compare-strings-in-java.md index 2d0094c..ae88658 100644 --- a/_posts/java-string/2019-12-10-compare-strings-in-java.md +++ b/_posts/java-string/2019-12-10-compare-strings-in-java.md @@ -3,6 +3,7 @@ layout: post title: How Do I Compare Strings In Java author: gaurav categories: [ Java, Core Java, String] +toc: true description: In this article you are going to learn how to compare strings. What problem occurs when you compare string using `equals to` (`=`)operator. featured: false --- @@ -281,9 +282,3 @@ Most of the beginner java developers do mistakes while comparing strings. They a It is always advised to use equals() method to compare the string on the basis of its content. If you have any query about the code blocks given above, please write it down in the comment section below. Also. let me know if you have any other way to compare two strings in java in the comment section. - -### Related Article - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [How To Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Introduction to Java Technology (Language and Platform)](https://coderolls.com/java-introduction/) diff --git a/_posts/java-string/2019-12-12-java-string-pool-and-intern-method.md b/_posts/java-string/2019-12-12-java-string-pool-and-intern-method.md index 4849223..e21ca64 100644 --- a/_posts/java-string/2019-12-12-java-string-pool-and-intern-method.md +++ b/_posts/java-string/2019-12-12-java-string-pool-and-intern-method.md @@ -3,6 +3,7 @@ layout: post title: Learn About Java String Pool And intern() Method author: gaurav categories: [ Java, Core Java, String] +toc: true description: String is an important class in Java. In this article I am explaining one of the most important concepts of String class i.e. the concept of Java String Pool and the `intern()` method. Read this article to understand this concept completely. --- @@ -163,15 +164,4 @@ When you assigned a literal to string variable it will automatically be interned In contrast, when you create a string using `new` operator you have applied `intern()` method to add its copy to the java string pool. -If you found this article worth, please - -[Give me a cup of Coffee β˜•](https://paypal.me/GauravKukade) - If you have any queries about the code blocks given above, please write it down in the comment section below. Also. let me know if you have any other information about the Java String pool and `intern()` method in the comment section. - -### Related Article - -- [How do I compare strings in Java](https://coderolls.com/compare-strings-in-java) -- [Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Introduction to Java Technology (Language and Platform)](https://coderolls.com/java-introduction/) diff --git a/_posts/java-string/2019-12-12-java-substring-method.md b/_posts/java-string/2019-12-12-java-substring-method.md index 6528cc3..dc30c62 100644 --- a/_posts/java-string/2019-12-12-java-substring-method.md +++ b/_posts/java-string/2019-12-12-java-substring-method.md @@ -3,6 +3,7 @@ layout: post title: substring() Method in Java (With example) author: gaurav categories: [ Java, Core Java, String] +toc: true description: The String class in Java is one of the most important classes in Java. After reading this article you will be able to use the 'substring()` method of the String class. --- The String class in Java is one of the most important classes in Java. After reading this article you will be able to use the 'substring()` method of the String class. @@ -170,14 +171,4 @@ In Java `substring()` method has two variants. `substring(int beginIndex, int endIndex)` returns the substring of this string which will start from the character at the `beginIndex` and will extend till the character at the `endIndex - 1`. Here, the parameter `beginIndex` is inclusive while the parameter `endIndex` is exclusive. -If you found this article worth, please [Give me a cup of Coffee β˜•](https://paypal.me/GauravKukade) - If you have any queries about the `substring()` method please write it below in the comment section. - -#### Related Articles - -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Introduction to Java Technology (Language and Platform)](https://coderolls.com/java-introduction/) diff --git a/_posts/java-string/2019-12-24-difference-between-stringbuffer-and-stringbuilder.md b/_posts/java-string/2019-12-24-difference-between-stringbuffer-and-stringbuilder.md index 3eb50ad..a777367 100644 --- a/_posts/java-string/2019-12-24-difference-between-stringbuffer-and-stringbuilder.md +++ b/_posts/java-string/2019-12-24-difference-between-stringbuffer-and-stringbuilder.md @@ -4,6 +4,7 @@ title: "Difference Between StringBuffer and StringBuilder class" author: gaurav image: assets/images/2019-12-24-difference-between-stringbuffer-and-stringbuilder/blog-cover.webp categories: [ Java, Core Java, String] +toc: true description: "In this article, we are going to discuss the differences between the `StringBuffer` and `StringBuilder` class. And we will see why it `StringBuilder` is preferable to `StringBuffer` class." featured: false @@ -75,6 +76,4 @@ So, `StringBuffer` class takes more time as compare to `StringBuilder` class for Taking efficiency into consideration, it is highly recommended to use `StringBuilder` class instead of the old `StringBuffer` class. -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - Also, if you have other information about the difference between `StringBuffer` class and `StringBuilder` class please write it down in the comment section below. diff --git a/_posts/java-string/2020-01-05-convert-string-to-int.md b/_posts/java-string/2020-01-05-convert-string-to-int.md index a881bb6..58adb47 100644 --- a/_posts/java-string/2020-01-05-convert-string-to-int.md +++ b/_posts/java-string/2020-01-05-convert-string-to-int.md @@ -1,44 +1,45 @@ --- layout: post -title: How to convert String to Integer in Java +title: "How to convert String to int in Java?" author: gaurav categories: [ Java, Core Java, String] -description: In this article you are going to learn how can one convert the string into an integer using the inbuilt methods of the Integer class. +toc: true +description: "In this article you are going to learn how one can convert the string to int using the inbuilt methods of the Integer class." --- -In this article you are going to learn how can one convert the string into an integer using the inbuilt methods of the Integer class. +In this article you are going to learn how one can convert the string to int using the inbuilt methods of the Integer class. ## Introduction We have learned many tutorials on the String class and seen the String operations are an important part of java programming. -Sometimes we took some values as a String but we want to operate them as an Integer, then questions arise how can one convert string to the integer? The Java team provided the solution for it. +Sometimes we took some values as a String but we want to operate them as an int, then questions arise how can one convert string to int? The Java team provided the solution for it. -Converting a string to integer is one of the most important things to know by a Java Developer. +Converting a string to int is one of the most important things to know by a Java Developer. -Now we will see what are the available options to convert a Siring into Integer. +Now we will see what are the available options to convert a string to int. -I have listed down two ways to convert a String into an Integer. +I have listed down two ways to convert a String to int. -1. Using the `Integre.parseInt()` method -2. Using the `Integer.valueOf()` method +1. Convert String to int using the `Integre.parseInt()` method +2. Convert String to int using the `Integer.valueOf()` method You can watch [the video on my youtube channel for "How To Convert A String To An Integer In Java"](https://www.youtube.com/watch?v=pNHjvpNHVCs). -Now we will see the above ways to convert string to integer one by one. +Now we will see the above ways to convert string to int one by one. -## Using the `Integre.parseInt()` method +## How to convert string to int using the `Integre.parseInt()` method -We can convert the String to an integer using the `Integre.parseInt()` method. +We can convert String to int using the `Integre.parseInt()` method. -The `Integer.parseInt()` method can convert an entire string to integer provided the String must contain the digit values only. For example `String str= "123";` +The `Integer.parseInt()` method can convert an entire string to int, provided the String must contain the digit values only. For example `String str= "123";` -Now we will see one example which converts the string to an integer using the `Integre.parseInt()` method. +Now we will see one example which converts the string to int using the `Integre.parseInt()` method. ```java /* - * A Java program to convert String to Integer. + * A Java program to convert String to int. * * @author Gaurav Kukade at coderolls.com */ @@ -58,9 +59,9 @@ Output ```java 1254 ``` -## Using the `Integer.valueOf()` method +## How to convert string to int using the `Integer.valueOf()` method -We can also convert String to Integer using the `Integer.valueOf()` method. +We can also convert String to int using the `Integer.valueOf()` method. The `Integer.valueOf()` method returns the integer instance of the value represented by the string variable. @@ -68,7 +69,7 @@ Below we will see one program to convert string to int using the `Integer.valueO ```java /* - * A Java program to convert String to Integer. + * A Java program to convert String to int. * * @author Gaurav Kukade at coderolls.com */ @@ -91,7 +92,7 @@ Output ## A Note about `NumberFormatException` -When you are trying to convert a string to integer but your string contains a value other than the decimal digits, then bothe the methods (`Integre.parseInt()` method and `Integer.valueOf()` method) will throw the `NumberFormatException`. +When you are trying to convert a string to int but your string contains a value other than the decimal digits, then both the methods (`Integre.parseInt()` method and `Integer.valueOf()` method) will throw the `NumberFormatException`. Below we will one program to see how `Integre.parseInt()` method throw the `NumberFormatException`. @@ -125,10 +126,8 @@ Exception in thread "main" java.lang.NumberFormatException: For input string: "1 ## Conclusion -We can convert String to integer using two methods, `Integre.parseInt()` method and `Integer.valueOf()` method. +We can convert String to int using two methods, `Integre.parseInt()` method and `Integer.valueOf()` method. -If the string contains some other value than the decimal numbers bothe the methods will throw the `NumberFormatException`. +If the string contains some other value than the decimal numbers both the methods will throw the `NumberFormatException`. -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -If you know any other way to convert the string to integer or if you have any query about the string to integer conversion please write it down in the comment section below. +If you know any other way to convert the string to int or if you have any query about the string to int conversion please write it down in the comment section below. diff --git a/_posts/java-string/2020-12-24-convert-stringbuilder-to-string-in-java.md b/_posts/java-string/2020-12-24-convert-stringbuilder-to-string-in-java.md index 56f11c8..128c753 100644 --- a/_posts/java-string/2020-12-24-convert-stringbuilder-to-string-in-java.md +++ b/_posts/java-string/2020-12-24-convert-stringbuilder-to-string-in-java.md @@ -4,6 +4,7 @@ title: "How To Convert StringBuilder To String In Java?" author: gaurav image: assets/images/2020-12-24/convert-stringbuilder-to-string-in-java.webp categories: [ Java, Core Java, String] +toc: true description: "In this article you will see, how to convert a StringBuilder to String in Java." featured: false --- @@ -52,14 +53,3 @@ Get the [above code as GitHub Gist](https://gist.github.com/gauravkukade/00bd416 --------- You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. - -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) diff --git a/_posts/java-string/2021-02-27-convert-int-to-string.md b/_posts/java-string/2021-02-27-convert-int-to-string.md index e55834b..657693e 100644 --- a/_posts/java-string/2021-02-27-convert-int-to-string.md +++ b/_posts/java-string/2021-02-27-convert-int-to-string.md @@ -4,6 +4,7 @@ title: "How To Convert An Integer To String In Java" author: gaurav image: assets/images/2021-02-27/convert-int-to-string.webp categories: [Java, Core Java, String] +toc: true description: "In this article you are going to learn how can you convert an integer to a String." --- @@ -106,15 +107,4 @@ String numberString = Integer.toString(number); ``` In both cases, `number` is an `int` value. -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - - -### Related Articles - -- [How to convert String to Integer in Java](https://coderolls.com/convert-string-to-int/) -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) +Please write down your thoughts in the comment section below. diff --git a/_posts/java-string/2021-12-08-java-reverse-string-using-recursion.md b/_posts/java-string/2021-12-08-java-reverse-string-using-recursion.md new file mode 100644 index 0000000..e57b2df --- /dev/null +++ b/_posts/java-string/2021-12-08-java-reverse-string-using-recursion.md @@ -0,0 +1,84 @@ +ο»Ώ--- +layout: post +title: "How To Reverse A String In Java Using Recursion" +author: gaurav +categories: [Java, String] +toc: true +description: "In this article, we will see how to reverse a string in java using the recursion." +--- +In this article, we will see how to reverse a string in java using the recursion. + +We have seen multiple ways to reverse a string in the previous article. + +Now we will see how to reverse a string using the recursion. + +## A function to reverse the string using the recursion + + +```java +public static String reverse(String str) { + if ((null == str) || (str.length() <= 1)) { + return str; + } + return reverse(str.substring(1)) + str.charAt(0); +} +``` + +In the above method `reverse()` we are taking String `str` to be reversed. + +We are checking if the `str` is null or its length is less than 1. If found, we will return the same string. + +Then we are returning the following statement +```java +reverse(str.substring(1)) + str.charAt(0); +``` + +In the above statement we are calling the `reverse()` function again with `str.substring(1)` as parameter. And adding the character at `0`th index. + + +So if we passed the "Hello" String to the function, the call will look like the code below. + +```java +reverse("Hello") +(reverse("ello")) + "H" +((reverse("llo")) + "e") + "H" +(((reverse("lo")) + "l") + "e") + "H" +((((reverse("o")) + "l") + "l") + "e") + "H" +(((("o") + "l") + "l") + "e") + "H" +"olleH" +``` + +## A complete Java Example +The full example java program is as given below. + +```java +/** + * A java program to reverse a striong using recursion. + * + * @author gaurav + * + */ +public class ReverseStringUsingRecursion { + + public static void main(String[] args) { + String str = "hello"; + System.out.println(reverse(str)); + + } + + public static String reverse(String str) { + if ((null == str) || (str.length() <= 1)) { + return str; + } + return reverse(str.substring(1)) + str.charAt(0); + } +} +``` +Output: +``` +olleh +``` + +The example java program given in the above tutorial can be found at [this GitHub Gist](https://gist.github.com/gauravkukade/16388aabb97a4990bd91cd32f3acf9d6). + +Please write you thoughts in the comment section below. diff --git a/_posts/java-string/2022-08-05-string-tutorials.md b/_posts/java-string/2022-08-05-string-tutorials.md new file mode 100644 index 0000000..a2135bc --- /dev/null +++ b/_posts/java-string/2022-08-05-string-tutorials.md @@ -0,0 +1,20 @@ +--- +layout: post +title: "String Tutorials" +author: gaurav +categories: [Java Basics, String Tutorials] +toc: false +description: "An index page for all collections tutorial." +hidden: true +--- + +- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) +- [How To Reverse A String In Java Using Recursion](https://coderolls.com/java-reverse-string-using-recursion/) +- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) +- [How To Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) +- [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) +- [How To Convert StringBuilder To String In Java?](https://coderolls.com/convert-stringbuilder-to-string-in-java/) +- [How to convert String to int in Java?](https://coderolls.com/convert-string-to-int/) +- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) +- [substring() Method in Java (With example)](https://coderolls.com/java-substring-method/) +- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) \ No newline at end of file diff --git a/_posts/java-time/2021-05-13-how-to-get-current-timestamps-in-java.md b/_posts/java-time/2021-05-13-how-to-get-current-timestamps-in-java.md index 40602d3..1b9ed68 100644 --- a/_posts/java-time/2021-05-13-how-to-get-current-timestamps-in-java.md +++ b/_posts/java-time/2021-05-13-how-to-get-current-timestamps-in-java.md @@ -1,8 +1,9 @@ -ο»Ώ--- +--- layout: post title: "How To Get Current Timestamp In Java?" author: gaurav categories: [Java, Java Time] +toc: true description: "In this article, we will see how to get the current timestamp in Java." --- In this article, we will see how to get the current timestamp in Java. @@ -13,7 +14,7 @@ We check both [`java.time.Instant`](https://docs.oracle.com/javase/8/docs/api/ja ## 1. Using `java.time.Instant` ( for Java 8) As per the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html), -> This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application. +> This class models a single instantaneous point on the timeline. This might be used to record event timestamps in the application. I have given an example below that shows how to get the current timestamp using `java.time.Instant` @@ -23,47 +24,40 @@ import java.time.Instant; import java.util.Date; /** - * A Java Program to get current timestamp using using the java.time.Instant - * - * @author Gaurav Kukade at coderolls.com - * + * A Java Program to get the current timestamp using the java.time.Instant + * @author coderolls.com */ -public class InstantExample { - - public static void main(String[] args) { - - Instant instant = Instant.now(); - System.out.println("1. instant: "+ instant); // 2021-05-13T15:05:18.734Z - - - //convert date object to instant - Date date = new Date(); - Instant instantFromDate = date.toInstant(); - - System.out.println("2. instantFromDate: " +instantFromDate); // 2021-05-13T15:05:18.873Z - - - //get instnat from the java.sql.Timestamp - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - Instant instantFromTimestamp = timestamp.toInstant(); - - System.out.println("3. instantFromTimestamp: "+ instantFromTimestamp); // 2021-05-13T15:05:18.874Z - - //get the epoch timestamp in milliseconds - //epoch timestamp is number of milliseconds since January 1, 1970, 00:00:00 GMT - Instant instant2 = Instant.now(); - long timeStampMillis = instant2.toEpochMilli(); - - System.out.println("4. timeStampMillis: "+ timeStampMillis); // 1620918318874 - - //get the epoch timestamp in seconds - Instant instant3 = Instant.now(); - long timeStampSeconds = instant3.getEpochSecond(); - - System.out.println("5. timeStampSeconds: "+ timeStampSeconds); // 1620918318 - - } - + public class InstantExample { + + public static void main(String[] args) { + Instant instant = Instant.now(); + System.out.println("1. instant: "+ instant); // 2021-05-13T15:05:18.734Z + + //convert date object to instant + Date date = new Date(); + Instant instantFromDate = date.toInstant(); + + System.out.println("2. instantFromDate: " +instantFromDate); // 2021-05-13T15:05:18.873Z + + //get instant from the java.sql.Timestamp + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + Instant instantFromTimestamp = timestamp.toInstant(); + + System.out.println("3. instantFromTimestamp: "+ instantFromTimestamp); // 2021-05-13T15:05:18.874Z + + //get the epoch timestamp in milliseconds + //epoch timestamp is the number of milliseconds since January 1, 1970, 00:00:00 GMT + Instant instant2 = Instant.now(); + long timeStampMillis = instant2.toEpochMilli(); + + System.out.println("4. timeStampMillis: "+ timeStampMillis); // 1620918318874 + + //get the epoch timestamp in seconds + Instant instant3 = Instant.now(); + long timeStampSeconds = instant3.getEpochSecond(); + + System.out.println("5. timeStampSeconds: "+ timeStampSeconds); // 1620918318 + } } ``` Output: @@ -74,7 +68,7 @@ Output: 4. timeStampMillis: 1620919459988 5. timeStampSeconds: 1620919459 ``` -See above code as [GitHub Gist](https://gist.github.com/gauravkukade/b1ceabac137864efd7258b60610cd9dd) +See the above code as [GitHub Gist](https://gist.github.com/gauravkukade/b1ceabac137864efd7258b60610cd9dd) ### Explanation: @@ -92,25 +86,20 @@ import java.util.Date; /** * A Java program to get the current timestamp using java.sql.Timestamp - * - * @author Gaurav Kukade at coderolls.com - * + * @author coderolls.com */ public class TimestampExample { - public static void main(String[] args) { - - //using system time in milliseconds - Timestamp timestampFromSystemTime = new Timestamp(System.currentTimeMillis()); - System.out.println("1. timestampFromSystemTime: "+timestampFromSystemTime); // 2021-05-13 20:55:44.179 - - //using java.util.Date - Date date = new Date(); - Timestamp timestampFromDateObject = new Timestamp(date.getTime()); - System.out.println("2. timestampFromDateObject: " +timestampFromDateObject); // 2021-05-13 20:55:44.187 - - } - + public static void main(String[] args) { + //using system time in milliseconds + Timestamp timestampFromSystemTime = new Timestamp(System.currentTimeMillis()); + System.out.println("1. timestampFromSystemTime: "+timestampFromSystemTime); // 2021-05-13 20:55:44.179 + + //using java.util.Date + Date date = new Date(); + Timestamp timestampFromDateObject = new Timestamp(date.getTime()); + System.out.println("2. timestampFromDateObject: " +timestampFromDateObject); // 2021-05-13 20:55:44.187 + } } ``` Output: @@ -120,12 +109,12 @@ Output: 2. timestampFromDateObject: 2021-05-13 20:55:44.187 ``` -See above code as [GitHub Gist](https://gist.github.com/gauravkukade/a965f1a078d382ff7366e7ba6d13561c) +See the above code as [GitHub Gist](https://gist.github.com/gauravkukade/a965f1a078d382ff7366e7ba6d13561c) ### Explanation: -1. In the first case, we are got the `timestamp` using the system time in milliseconds. We can get the system time in millisecond using the `System.currentTimeMillis()`. -2. In the second case, we have created a new `date` object, and then we have used the `.getTime()` on the `date` object to get the current time in milliseconds. We have passed the time milliseconds to timestamp constructor to get the current timestamp. +1. In the first case, we get the `timestamp` using the system time in milliseconds. We can get the system time in milliseconds using the `System.currentTimeMillis()`. +2. In the second case, we have created a new `date` object, and then we have used the `.getTime()` on the `date` object to get the current time in milliseconds. We have passed the time milliseconds to the timestamp constructor to get the current timestamp. Sometimes we may need to convert the `java.time.Instant` to `java.sql.Timestamp` or vice versa. So let's see both conversions below. @@ -145,15 +134,12 @@ import java.time.Instant; */ public class InstantToTimestamp { - public static void main(String[] args) { - - // get Timestamp from Instant - Instant instant = Instant.now(); - Timestamp timestamp = Timestamp.from(instant); - System.out.println("Instant To Timestamp: " +timestamp); // 2021-05-13 21:07:44.381 - - - } + public static void main(String[] args) { + //Get Timestamp from Instant + Instant instant = Instant.now(); + Timestamp timestamp = Timestamp.from(instant); + System.out.println("Instant To Timestamp: " +timestamp); // 2021-05-13 21:07:44.381 + } } ``` @@ -162,7 +148,7 @@ Output: ``` Instant To Timestamp: 2021-05-13 21:07:44.381 ``` -See above code as [GitHub Gist](https://gist.github.com/gauravkukade/ea3bc951f15be0010569d306ccafa975) +See the above code as [GitHub Gist](https://gist.github.com/gauravkukade/ea3bc951f15be0010569d306ccafa975) ### Explanation: @@ -189,15 +175,12 @@ import java.time.Instant; */ public class TimestampToInstant { - public static void main(String[] args) { - - //get instnat from the java.sql.Timestamp - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - Instant instant = timestamp.toInstant(); - System.out.println("Timestamp To Instant: " +instant); // 2021-05-13T15:39:08.046Z - - } - + public static void main(String[] args) { + //get instant from the java.sql.Timestamp + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + Instant instant = timestamp.toInstant(); + System.out.println("Timestamp To Instant: " +instant); // 2021-05-13T15:39:08.046Z + } } ``` @@ -205,7 +188,7 @@ Output: ``` Timestamp To Instant: 2021-05-13T15:39:08.046Z ``` -See above code as [GitHub Gist](https://gist.github.com/gauravkukade/a031b1904d4efaf758a59462ee2dc02e) +See the above code as [GitHub Gist](https://gist.github.com/gauravkukade/a031b1904d4efaf758a59462ee2dc02e) ### Explanation: @@ -213,7 +196,7 @@ In the above example, we have used the `.toInstant()` method on the `timestamp` ## Conclusion -We can get the current timestamp in java using the `Instant` and `Timestamp`. +We can get the current timestamp in Java using the `Instant` and `Timestamp`. From Java 8, it is recommended to use the timestamp of the Instant class. We can get the current timestamp from `Instant`as is given below, @@ -224,13 +207,13 @@ Instant instant = Instant.now(); Date date = new Date(); Instant instantFromDate = date.toInstant(); -//get instnat from the java.sql.Timestamp +//get instant from the java.sql.Timestamp Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Instant instantFromTimestamp = timestamp.toInstant(); //get the epoch timestamp in milliseconds -//epoch timestamp is number of milliseconds since January 1, 1970, 00:00:00 GMT +//epoch timestamp is the number of milliseconds since January 1, 1970, 00:00:00 GMT Instant instant2 = Instant.now(); long timeStampMillis = instant2.toEpochMilli(); @@ -252,7 +235,7 @@ System.out.println(date.getTime()); Timestamp timestampFromDateObject = new Timestamp(date.getTime()); ``` -Also we can convert the `java.time.Instant` to `java.sql.Timestamp` or vice versa. +Also, we can convert the `java.time.Instant` to `java.sql.Timestamp` or vice versa. **Instant To Timestamp** @@ -277,17 +260,3 @@ We will see [how to get the current date-time in java](https://coderolls.com/get You can check my YouTube channel [here](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w) -### Related Articles - -- [How To Get Current Date Time In Java](https://coderolls.com/get-current-date-time-in-java/) - -- [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) - -- [How to convert String to Integer in Java](https://coderolls.com/convert-string-to-int/) - -- [How To Convert StringBuilder To String In Java?](https://coderolls.com/convert-stringbuilder-to-string-in-java/) - -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) - diff --git a/_posts/java-time/2021-05-15-get-current-date-time-in-java.md b/_posts/java-time/2021-05-15-get-current-date-time-in-java.md index 9891b4e..e714b28 100644 --- a/_posts/java-time/2021-05-15-get-current-date-time-in-java.md +++ b/_posts/java-time/2021-05-15-get-current-date-time-in-java.md @@ -1,8 +1,9 @@ -ο»Ώ--- +--- layout: post title: "How To Get Current Date Time In Java?" author: gaurav categories: [Java, Java Time] +toc: true description: "We need to use Date and Time in day-to-day programming. In this article, we will see how to get the current date and time in Java. " --- We need to use Date and Time in day-to-day programming. In this article, we will see how to get the current date and time in Java. @@ -34,27 +35,26 @@ import java.text.SimpleDateFormat; import java.util.Date; /** - * A java program to get current date time using the java.util.Date class + * A Java program to get current date time using the java.util.Date class * @author Gaurav Kukade at coderolls.com * */ public class DateExample { - public static void main(String[] args) { - - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - Date date = new Date(); - - // print date object - System.out.println(date); // Sat May 15 12:21:39 IST 2021 - - // print formated date object - System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:21:39 - - // creates new Date() object using System.currentTimeMillis() - Date date2 = new Date(System.currentTimeMillis()); - System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:21:39 - } + public static void main(String[] args) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); + Date date = new Date(); + + // print date object + System.out.println(date); // Sat May 15 12:21:39 IST 2021 + + // print formatted date object + System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:21:39 + + // creates new Date() object using System.currentTimeMillis() + Date date2 = new Date(System.currentTimeMillis()); + System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:21:39 + } } ``` @@ -65,11 +65,11 @@ Sat May 15 12:21:39 IST 2021 15/05/2021 12:21:39 15/05/2021 12:21:39 ``` -Check above code as [GitHub Gist](https://gist.github.com/gauravkukade/c0abb86106b161cd9b3d12de37e34cb3) +Check the above code as [GitHub Gist](https://gist.github.com/gauravkukade/c0abb86106b161cd9b3d12de37e34cb3) ## 2. Java Calendar API (`java.util.Calendar`) (Legacy) -We can use the `java.util.Calendar` class to get the instance of the Date class. The `getTime()` method of Calendar class returns the instance of `java.util.Date` +We can use the `java.util.Calendar` class to get the instance of the Date class. The `getTime()` method of the Calendar class returns the instance of `java.util.Date` I have given an example below that shows how to get the current date and time using the `java.util.Calendar` class. ```java @@ -83,23 +83,21 @@ import java.util.Date; */ public class CalendarExample { - public static void main(String[] args) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - - // get the instance of the java.util.Calendar - Calendar calendar = Calendar.getInstance(); - - // getTime() method returns the instance of java.util.Date - Date date = calendar.getTime(); - - // prints the date object - System.out.println(date); // Sat May 15 12:50:17 IST 2021 - - // print the formated date - System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:50:17 - - } - + public static void main(String[] args) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); + + // get the instance of the java.util.Calendar + Calendar calendar = Calendar.getInstance(); + + // getTime() method returns the instance of java.util.Date + Date date = calendar.getTime(); + + // prints the date object + System.out.println(date); // Sat May 15 12:50:17 IST 2021 + + // print the formatted date + System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:50:17 + } } ``` Output: @@ -108,14 +106,14 @@ Sat May 15 12:50:17 IST 2021 15/05/2021 12:50:17 ``` -Check above code as [GitHub Gist](https://gist.github.com/gauravkukade/b29079c6b840d9c894c836468d9326dd) +Check the above code as [GitHub Gist](https://gist.github.com/gauravkukade/b29079c6b840d9c894c836468d9326dd) ## 3. LocalDate (`java.time.LocalDate`) `LocalDate` is one of the most commonly used classes of Java date/Time API. As given in the name specifies the local date. -We can use this class when zones are not required to specify. The `LocalDate` represents a date in ISO format (yyyy-MM-dd) without time. ex. 2021-05-15 +We can use this class when zones are not required to be specified. The `LocalDate` represents a date in ISO format (yyyy-MM-dd) without time. ex. 2021-05-15 I have given an example below that shows how to get the current local date using the `java.time.LocalDate` class. ```java @@ -127,18 +125,16 @@ import java.time.format.DateTimeFormatter; */ public class LocalDateExample { - public static void main(String[] args) { - - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); - LocalDate localDate = LocalDate.now(); - - // print localDate object - System.out.println(localDate); // 2021-05-15 - - // print formatted localDate - System.out.println(dateTimeFormatter.format(localDate)); // 2021/05/15 - - } + public static void main(String[] args) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + LocalDate localDate = LocalDate.now(); + + // print localDate object + System.out.println(localDate); // 2021-05-15 + + // print formatted localDate + System.out.println(dateTimeFormatter.format(localDate)); // 2021/05/15 + } } ``` @@ -147,13 +143,13 @@ Output: 2021-05-15 2021/05/15 ``` -Check above code as [GitHub Gist](https://gist.github.com/gauravkukade/4a756785c65e94fa645c1a4faa65edb4) +Check the above code as [GitHub Gist](https://gist.github.com/gauravkukade/4a756785c65e94fa645c1a4faa65edb4) ## 4. LocalTime (`java.time.LocalTime`) `LocalTime` is one of the most commonly used classes of Java date/Time API. As given in the name specifies the local time. -We can use this class when zones are not required to specify. The `LocalTime` represents a time without the date. ex. 20:21:32 +We can use this class when zones are not required to be specified. The `LocalTime` represents a time without a date. ex. 20:21:32 I have given an example below that shows how to get the current local time using the `java.time.LocalTime` class. @@ -161,23 +157,20 @@ I have given an example below that shows how to get the current local time using import java.time.LocalTime; import java.time.format.DateTimeFormatter; /** - * A java program to get local time using the java.time.LocalTime class + * A Java program to get local time using the java.time.LocalTime class * @author Gaurav Kukade at coderolls.com */ public class LocalTimeExample { - - public static void main(String[] args) { - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); - LocalTime localTime = LocalTime.now(); - - // print localTime object - System.out.println(localTime); // 13:11:46.140359217 - - // print formatted localTime - System.out.println(dateTimeFormatter.format(localTime)); // 13:11:46 - - } - + public static void main(String[] args) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + LocalTime localTime = LocalTime.now(); + + // print localTime object + System.out.println(localTime); // 13:11:46.140359217 + + // print formatted localTime + System.out.println(dateTimeFormatter.format(localTime)); // 13:11:46 + } } ``` Output: @@ -192,32 +185,28 @@ Check above code as [GitHub Gist](https://gist.github.com/gauravkukade/8ca11fd8b `LocalDateTime` is one of the most commonly used classes of Java date/Time API. As given in the name specifies the local date and time. -We can use this class when zones are not required to specify. The `LocalDateTime` represents a combination of date and time. ex. 2021-05-15 +We can use this class when zones are not required to be specified. The `LocalDateTime` represents a combination of date and time. ex. 2021-05-15 -I have given an example below that shows how to get the current local date time using the `java.time.LocalDateTime` class. +I have given an example below that shows how to get the current local date-time using the `java.time.LocalDateTime` class. ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** - * A java program to get local date time using the java.time.LocalDateTime class + * A Java program to get local date-time using the java.time.LocalDateTime class * @author Gaurav Kukade at coderolls.com */ public class LocalDateTimeExample { - - public static void main(String[] args) { - - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); - LocalDateTime localDateTime = LocalDateTime.now(); - - // print localDateTime object - System.out.println(localDateTime); // 2021-05-15T13:20:13.329481722 - - // print formatted localDateTime - System.out.println(dateTimeFormatter.format(localDateTime)); //15/05/2021 13:20:13 - - } - + public static void main(String[] args) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); + LocalDateTime localDateTime = LocalDateTime.now(); + + // print localDateTime object + System.out.println(localDateTime); // 2021-05-15T13:20:13.329481722 + + // print formatted localDateTime + System.out.println(dateTimeFormatter.format(localDateTime)); //15/05/2021 13:20:13 + } } ``` Output: @@ -229,7 +218,7 @@ Check above code as [GitHub Gist](https://gist.github.com/gauravkukade/ef36191b7 ## 6. ZonedDateTime (`java.time.ZonedDateTime`) -When we need to use zone specific date and time, we can use the `ZonedDateTime` class. +When we need to use zone-specific dates and times, we can use the `ZonedDateTime` class. The different zones are represented by the [`ZoneId`](https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html). We can get all the list of available ZoneIds using the [`getAvailableZoneIds()`](https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#getAvailableZoneIds--) @@ -238,9 +227,9 @@ The code snippet to get the set of all available `ZoneIds` is given below. Set allZoneIds = ZoneId.getAvailableZoneIds(); ``` -We can use `ZonedDateTime.now()` method to get system default zone local time. We can specify the zone using `now.withZoneSameInstant(zoneId)` method. +We can use the `ZonedDateTime.now()` method to get the system's default zone local time. We can specify the zone using the `now.withZoneSameInstant(zoneId)` method. -I have given an example below that shows how to get the zone-specific date time using the `java.time.ZonedDateTime` class. +I have given an example below that shows how to get the zone-specific date-time using the `java.time.ZonedDateTime` class. ```java import java.time.OffsetDateTime; @@ -249,37 +238,34 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; /** - * A java program to get the zone specific date time using the java.time.ZonedDateTime class + * A Java program to get the zone-specific date-time using the java.time.ZonedDateTime class * @author Gaurav Kukade at coderolls.com */ public class ZonedDateTimeExample { - public static void main(String[] args) { - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); - - // get system default zone date time, - // my system default zone is +05:30 - ZonedDateTime now = ZonedDateTime.now(); - System.out.println(dateTimeFormatter.format(now)); // 2021/05/15 13:45:55 - System.out.println(now.getOffset()); // +05:30 - - // check the default time zone - System.out.println(ZoneOffset.systemDefault()); // Asia/Kolkata - System.out.println(OffsetDateTime.now().getOffset()); // +05:30 - - // get get current date time for Kolkata, India - ZonedDateTime indiaDateTime = now.withZoneSameInstant(ZoneId.of("Asia/Kolkata")); - System.out.println(dateTimeFormatter.format(indiaDateTime)); // 2021/05/15 13:45:55 - System.out.println(indiaDateTime.getOffset()); // +05:30 - - - // get get current date time for Paris , France - ZonedDateTime franceDateTime = now.withZoneSameInstant(ZoneId.of("Europe/Paris")); - System.out.println(dateTimeFormatter.format(franceDateTime)); // 2021/05/15 10:15:55 - System.out.println(franceDateTime.getOffset()); // +02:00 - - } - + public static void main(String[] args) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); + + // get system default zone date time, + // my system default zone is +05:30 + ZonedDateTime now = ZonedDateTime.now(); + System.out.println(dateTimeFormatter.format(now)); // 2021/05/15 13:45:55 + System.out.println(now.getOffset()); // +05:30 + + // check the default time zone + System.out.println(ZoneOffset.systemDefault()); // Asia/Kolkata + System.out.println(OffsetDateTime.now().getOffset()); // +05:30 + + // get get current date time for Kolkata, India + ZonedDateTime indiaDateTime = now.withZoneSameInstant(ZoneId.of("Asia/Kolkata")); + System.out.println(dateTimeFormatter.format(indiaDateTime)); // 2021/05/15 13:45:55 + System.out.println(indiaDateTime.getOffset()); // +05:30 + + // get get current date time for Paris , France + ZonedDateTime franceDateTime = now.withZoneSameInstant(ZoneId.of("Europe/Paris")); + System.out.println(dateTimeFormatter.format(franceDateTime)); // 2021/05/15 10:15:55 + System.out.println(franceDateTime.getOffset()); // +02:00 + } } ``` Output: @@ -305,32 +291,29 @@ import java.time.ZoneId; import java.time.format.DateTimeFormatter; /** - * A java program to get current date time using the jjava.time.Instant class + * A Java program to get the current date time using the java.time.Instant class * @author Gaurav Kukade at coderolls.com */ public class InstantExample { - public static void main(String[] args) { - - Instant instant = Instant.now(); - - // print instant object - System.out.println(instant); // 2021-05-15T10:11:45.331237189Z - - // get epoch time in milliseconds - // epoch timestamp is number of milliseconds/seconds since January 1, 1970, 00:00:00 GMT - System.out.println(instant.toEpochMilli()); // 1621073505331 - - // get epoch time in seconds - System.out.println(instant.getEpochSecond()); // 1621073505 - - // we can convert instant to LocalDateTime, LocalDate, LocalTime - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); - LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); - System.out.println(dateTimeFormatter.format(localDateTime)); // 15/05/2021 15:41:45 - - } - + public static void main(String[] args) { + Instant instant = Instant.now(); + + //print instant object + System.out.println(instant); // 2021-05-15T10:11:45.331237189Z + + //get epoch time in milliseconds + //epoch timestamp is the number of milliseconds/seconds since January 1, 1970, 00:00:00 GMT + System.out.println(instant.toEpochMilli()); // 1621073505331 + + // get epoch time in seconds + System.out.println(instant.getEpochSecond()); // 1621073505 + + //We can convert instant to LocalDateTime, LocalDate, LocalTime + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); + LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); + System.out.println(dateTimeFormatter.format(localDateTime)); // 15/05/2021 15:41:45 + } } ``` Output: @@ -356,7 +339,7 @@ Date date = new Date(); // print date object System.out.println(date); // Sat May 15 12:21:39 IST 2021 -// print formated date object +// print formatted date object System.out.println(simpleDateFormat.format(date)); // 15/05/2021 12:21:39 ``` `java.util.Calendar` class @@ -402,22 +385,8 @@ System.out.println(instant.toEpochMilli()); // 1621073505331 System.out.println(instant.getEpochSecond()); // 1621073505 ``` -So, we have seen all the ways to get the current date and time in Java. You can comment below if you know any other way to get the current date time in Java. +So, we have seen all the ways to get the current date and time in Java. You can comment below if you know of any other way to get the current date time in Java. If you want to check, [how can we get the current timestamps in Java?](https://coderolls.com/how-to-get-current-timestamps-in-java/) we have written an article on it. You can check my YouTube channel [here](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w) - -### Related Articles - -- [How To Get Current Timestamp In Java?](https://coderolls.com/how-to-get-current-timestamps-in-java/) - -- [How To Convert An Integer To String In Java](https://coderolls.com/convert-int-to-string/) - -- [How to convert String to Integer in Java](https://coderolls.com/convert-string-to-int/) - -- [How To Convert StringBuilder To String In Java?](https://coderolls.com/convert-stringbuilder-to-string-in-java/) - -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) - -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) diff --git a/_posts/java-time/2021-08-29-how-to-get-gmt-time-in-java.md b/_posts/java-time/2021-08-29-how-to-get-gmt-time-in-java.md new file mode 100644 index 0000000..1fbcd5a --- /dev/null +++ b/_posts/java-time/2021-08-29-how-to-get-gmt-time-in-java.md @@ -0,0 +1,56 @@ +--- +layout: post +title: "How To Get GMT Time In Java?" +author: gaurav +categories: [Java, Java Time] +toc: true +description: "In this article, we will see how we can get GMT time in Java." +--- + +In Java Programming, sometimes we need the date in GMT format. In this quick tutorial, we will see how we can get GMT time in Java. + +We will be using the `ZonedDateTime` class to get the GMT. We can get any zone time using the `ZonedDateTime` class. You can see this article to learn more about it. + +I have given a Java program below, it has the `getGMTTime()` method. This method receives the Date object (java.util.Date) and returns a GMT string. + +```java +package com.coderolls.examples; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +/** + * A Java Program to get time in GMT + * + * @author Gaurav Kukade at coderolls.com + * + */ +public class GMTTimeExample { + public static void main(String[] args) { + Date date = new Date(); + String gmtTime = getGMTTime(date); + System.out.println("Print time in GMT: "+gmtTime); + } + + /** + * A method to return the GMT time string + * @param date + * @return + */ + public static String getGMTTime(Date date) { + DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss O"); + Instant instant = date.toInstant(); + ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC); + return customFormatter.format(zonedDateTime); + } +} +``` + +In the above program, we have used the DateTimeFormatter. You can check its various patterns in the documentation. + +If you are looking to get the current timestamp in Java, you can visit this article How To Get Current Timestamp In Java?. + +You can check my YouTube channel [here](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w). + diff --git a/_posts/java-uuid/2020-12-19-uuid-in-java.md b/_posts/java-uuid/2020-12-19-uuid-in-java.md index 6b6332b..bda7db0 100644 --- a/_posts/java-uuid/2020-12-19-uuid-in-java.md +++ b/_posts/java-uuid/2020-12-19-uuid-in-java.md @@ -1,15 +1,15 @@ -ο»Ώ--- +--- layout: post title: "Your Guide To UUID In Java" author: gaurav image: assets/images/2020-12-19/uuid.webp categories: [ Java, Core Java, String] -description: In this article you will learn what is UUID and about the Java UUID class. +description: In this article, you will learn what is UUID and about the Java UUID class. +toc: true featured: false - --- -In this article we will see, +In this article, we will see, - What is UUID? - Java UUID class @@ -37,13 +37,13 @@ There are 4 types of UUID variant - **6:** It is reserved for Microsoft backward compatibility - **7:** It is reserved for future definition. -Mostly the variant 2 is used. +Mostly variant 2 is used. UUID can be used in the following cases - - As a primary key of database table -- To create session id for web application -- To represent as transaction id + - As a primary key of the database table +- To create a session ID for a web application +- To represent as transaction ID - To create a random file name ### Example UUID @@ -73,21 +73,21 @@ The above method creates a UUID from the string standard representation as descr ```java UUID.nameUUIDFromBytes(byte[] name) ``` -This method is used to create a version 3 (name based) UUID based on the specified byte array. +This method is used to create a version 3 (name-based) UUID based on the specified byte array. ```java UUID.randomUUID() ``` -This method is used to create a version 4 (pseudo randomly generated) UUID. +This method is used to create a version 4 (pseudo-randomly generated) UUID. ### Instance methods -Also there are a few instance methods of a UUID class. +Also, there are a few instance methods of a UUID class. ```java clockSequence() ``` -This method is used to get the the clock sequence value associated with this UUID. +This method is used to get the clock sequence value associated with this UUID. This method returns the clock sequence value as `int`. @@ -101,7 +101,7 @@ This method returns -1, 0 or 1 as this `UUID` is less than, equal to, or greater ```java equals(Object obj) ``` -This method simply compares this object to the specified object. It return the result in `boolean` +This method simply compares this object to the specified object. It returns the result in `boolean` ```java node() @@ -130,14 +130,3 @@ This method returns the version number (`int`) associated with this UUID. -------- You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. - -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Introduction to Java Technology (Language and Platform)](https://coderolls.com/java-introduction/) - diff --git a/_posts/java-uuid/2020-12-23-create-uuid-in-java.md b/_posts/java-uuid/2020-12-23-create-uuid-in-java.md index 959af80..94a3c20 100644 --- a/_posts/java-uuid/2020-12-23-create-uuid-in-java.md +++ b/_posts/java-uuid/2020-12-23-create-uuid-in-java.md @@ -1,19 +1,19 @@ -ο»Ώ--- +--- layout: post title: "How To Create UUID in Java?" author: gaurav image: assets/images/2020-12-23/create-uuid-in-java.webp categories: [Java, Core Java, String] -description: "In this article you will see, how to create UUID in Java." -featured: true -hidden: true +description: "In this article, you will see, how to create UUID in Java." +toc: true +hidden: false --- -In this article you will see, how to create UUID in Java. +In this article, you will see, how to create UUID in Java. ## Introduction -UUID, a universally unique identifier is a 128-bit number used to identify information in computer systems. +[UUID](https://coderolls.com/uuid-in-java/), a universally unique identifier is a 128-bit number used to identify information in computer systems. UUID is made of hex digits along with 4 hyphen ("-") symbols. The length of a UUID is 36 characters. @@ -29,7 +29,7 @@ df6fdea1-10c3-474c-ae62-e63def80de0b Creating a Randomly Generated UUID (version 4) is really easy in Java. -UUID Class is present in `java.util` package. And it has the static method `randomUUID()` which returns the randomly generated UUID. +UUID Class is present in the `java.util` package. And it has the static method `randomUUID()` which returns the randomly generated UUID. The example is given below. @@ -43,16 +43,14 @@ import java.util.UUID; */ public class CreateUUID { - public static void main(String[] args) { - - // creating random uuid i.e. version 4 UUID - UUID uuid = UUID.randomUUID(); - - System.out.println("Printing the randomly generated UUID value......\n"); - - System.out.println("uuid: "+uuid); - - } + public static void main(String[] args) { + // creating random uuid i.e. version 4 UUID + UUID uuid = UUID.randomUUID(); + + System.out.println("Printing the randomly generated UUID value......\n"); + + System.out.println("uuid: "+uuid); + } } @@ -64,20 +62,12 @@ Printing the randomly generated UUID value...... uuid: e3aed661-ccc2-42fd-ad69-734fee350cd2 ``` +## Conclusion + +You can create a UUID using the static method `randomUUID()` of the `UUID` class. Get the [above code as GitHub Gist](https://gist.github.com/gauravkukade/395f314c549969bd300d72c7e032dbcb). -------- You can visit my [YouTube channel 'coderolls'](https://www.youtube.com/channel/UCl31HHUdQbSHOQfc9L-wo3w?view_as=subscriber?sub_confirmation=1) to find more video tutorials. - -If you found this article worth, support me by [giving a cup of Coffee β˜•](https://www.paypal.me/GauravKukade) - -#### Related Articles - -- [Learn About Java String Pool And intern() Method](https://coderolls.com/java-string-pool-and-intern-method/) -- [How Do I Compare Strings In Java](https://coderolls.com/compare-strings-in-java/) -- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/) -- [Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/) -- [Difference Between StringBuffer and StringBuilder class](https://coderolls.com/difference-between-stringbuffer-and-stringbuilder/) -- [8 Basic GIT Commands Every Newbie Developer Must Know](https://coderolls.com/basic-git-commands/) diff --git a/_posts/junit/2022-08-28-why-unit-test-cases.md b/_posts/junit/2022-08-28-why-unit-test-cases.md new file mode 100644 index 0000000..f34f345 --- /dev/null +++ b/_posts/junit/2022-08-28-why-unit-test-cases.md @@ -0,0 +1,33 @@ +--- +layout: post +title: "Why We Write JUnit Test Cases?" +author: gaurav +categories: [Unit Testing in Java, JUnit] +toc: true +description: "In this article, we will see why unit testing is important in Java. This is the first article of the JUnit Tutorial Series." +--- + +In this article, we will see why unit testing is important in Java. This is the first article of the JUnit Tutorial Series. + +## Why We Write JUnit Test Cases? + +Whenever we are writing some code, it is essential to check whether the code is working fine or not. + +Sometimes we can test it manually if our code is working as expected, but it is not an efficient way to test it. + +As a developer, we are used to changing the code as per changes in business requirements. In this case, we need to test all the happy path, edge, and corner cases again to check whether the code is working fine or not. It will be a time-consuming process, and also it will affect the team's efficiency and release. + +To make this testing part efficient, we can write unit test cases for our code. + +**Unit test cases are the code written to test all the happy path, edge, and corner cases of the feature or functionality. Basically, by writing a JUnit Test case, we are testing a unit of code on its own.** + +We can run a JUnit Test case in milliseconds to check if the code is working as expected. If the JUnit test case passes that means the feature or functionality is working as expected. + +If the unit test case fails, it shows there are a single or more flaws/errors in the feature or functionality. Various Unit testing framework provides a detailed explanation of the flaws or error in the code with line number and error details. + +JUnit Testing framework provides detailed explanations of the test failures with line numbers and reasons. + +## Conclusion + +**We should always write unit test cases for our code to test it efficiently.** JUnit is a unit-testing open-source framework for the Java programming language. We will learn more about it in our next article, [How To Write JUnit Test Case In Java? (With Example)](/junit-test-case-in-java/) + diff --git a/_posts/junit/2022-08-30-junit-test-case-in-java.md b/_posts/junit/2022-08-30-junit-test-case-in-java.md new file mode 100644 index 0000000..230533f --- /dev/null +++ b/_posts/junit/2022-08-30-junit-test-case-in-java.md @@ -0,0 +1,233 @@ +--- +layout: post +title: "How To Write JUnit Test Case In Java? (With Example)" +author: gaurav +categories: [Unit Testing in Java, JUnit] +toc: true +description: "In this article, we will be introduced to JUnit - Unit Testing Framework in Java. Also, you will be writing your First JUnit Test case." +--- + +In this article, we will be introduced to JUnit - Unit Testing Framework in Java. Also, We will see How To Write a JUnit Test Case. So, you will be writing your First JUnit Test case. + +## Introduction + +JUnit is an open-source Unit Testing Framework for the Java programming language. + +JUnit framework helps developers to test their code on its own. + +## How to write a JUnit Test case in Java? + +To write the first JUnit Test case we will take a sample method `generatePassword()` and check if it is generating the password as expected. + +### Step 1: Creating A Maven Project + +First, we need to create a maven project. You can refer to the article [How To Create A Maven Project In Eclipse?](/maven-project/) The maven project helps us organize the source code and test code separately. + +You will be able to see the project structure as shown below + +![A Maven project Structure in Eclipse](/assets/images/2022-08-30-junit-test-case/001-junit-project-structure.png) + +### Step 2: Creating A Class that needs to be tested + +> Since this is a tutorial we are creating this class so that we can use it for testing. + +Then we will create a sample class `PasswordGenerator.java` with a method `generatePassword()` as below. + +Please take note that here `PasswordGenerator.java` class is our System Under Test and we will be writing a unit test case to test the `generatePassword()` method. + +```java +package com.coderolls.SampleProject; + +public class PasswordGenerator { + /** + * A method generates a password from name and year of birth + * + * Ex. For the name 'Thomas' and Year of birth '1992', it will generate the password as 'Thom1992'. + * + * If the name is equal to or less than 4 characters then it will return name+YearOfith as password. + * + * Ex. For name 'Mary' and year of birth '2003', it will return 'Mary2003' as password. + * + * @param name + * @param yearOfBirth + * @return + */ + public String generatePassword(String name, int yearOfBirth) { + String password = null; + + if(name.length()<=4) { + password = name+yearOfBirth; + }else { + String str = name.substring(0, 4); + password =str+yearOfBirth; + } + return password; + } +} +``` + +In the above class. the method generatePassword() will generate a password from name and year of birth. + +Ex. For the name 'Thomas' and the Year of birth '1992', it will generate the password as 'Thom1992'. + +If the name has equal to or less than 4 characters then it will return name+YearOfith as the password. + +Ex. For the name 'Mary' and year of birth '2003', it will return 'Mary2003' as the password. And for 'Om' and '2001', it will return 'Om2001' as the password. + +### Step 3: Creating A JUnit Test Case + +To create a JUnit test case, write click on the `src/test/java` and `New`>`JUnit Test Case`. You will see the screen as given below. + +![Create A JUnit Test Case](/assets/images/2022-08-30-junit-test-case/002-junit-test-case.png) + +Enter the package for your JUnit test case. Make sure the package of the class that needs to be tested and the JUnit test case should be the same. + +Junit test case name should be ClassName+"Test", so in our case, the Junit test case name will be 'PasswordGeneratorTest'. + +Then browse the class that needs to be tested. +Once all details are filled in properly click on finish. + +![Naming Junit Test Case and Adding Class Under Test](/assets/images/2022-08-30-junit-test-case/003-junit-test-case-create.png) + +### Step 4: Writing First Junit Test Case method + +Here we will be writing our first unit test case. We will be using the @Test annotation for our test case. + +Since we will be testing the generatePassword() method our test method name will be testGenaratePassword(). It is a convention to add 'test before the test method name + the name of the method that needs to be tested. And finally, we will adjust this name in camelCase. + +Our first unit test method will look like the one given below. + +```java + @Test + public void testGeneratePassword() { + String name= "Joseph"; + int yearOFBirth = 1998; + + String expected = "Jose1998"; + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String actual = passwordGenerator.generatePassword(name, yearOFBirth); + + assertEquals(expected, actual); + } +``` + +In the above unit test case method, we have used the `assertEquals(expected, actual)` method of JUnit's Assert class to test the `generatePassword()` method. + +Here we are checking if the expected and actual results are the same or not. + +Here, expected is the result that we expect from our method. In this case, we know the working of the `generatePassword()` method. We know that it will return the first 4 characters from the name with the year of birth. + +So, we created our expected string manually and then we invoked the method `generatePassword()` by passing the same parameter (i.e. `name` and `yearOfBirth`) and storing the returned string in the actual string variable. + +Once we have expected and actual, we can use the `assertEquals(expected, actual)` method to check if both strings are the same or not. + +To run this unit test case, we can right-click and then select `Run As` > `JUnit Test`. + +If the test passes, we can see the Green bar in the output console as shown below. + +![Green Bar showing the JUnit Test Case Success](/assets/images/2022-08-30-junit-test-case/004-junit-test-case-run-green-bar.png) + +To check whether the code is covered by the unit test we can check the code coverage. To test the code coverage, right-click in the test case editor and select `Coverage As`>`JUnit Test Case` or the shortcut is `alt+shift+E, T` + +We can check how many lines of the `PasswordGenerator.java` class are covered by the unit test case we have written till now. + +In the below screenshot of `PasswordGenerator.java`, we can see + +Green lines - Fully covered by the unit test case + +Yellow Lines - Partially covered + +For example. If it is an `if ` statement, then only one case (branch) is covered. i.e either true or false + +Red Line - Not covered yet + +![Green, Yellow and Red lines showing code coverage in eclipse](/assets/images/2022-08-30-junit-test-case/005-class-covered-by-junit.png) + +In eclipse, even the unit test code goes green if everything seems fine, otherwise, it will show in red if there are some errors in the test code. + +![JUnit Test Case code is green](/assets/images/2022-08-30-junit-test-case/006-junit-test-code-goes-green-when-no-errors.png) + +As we can see in `PasswordGenerator.java`, the `generatePassword()` method `else` part is covered where we are creating a password with a name length of more than 4 characters. + +### Step 5 : Adding More Junit Test Case Methods + +So, let's add one more unit test method to test the condition where we can receive a name with a length of fewer than 4 characters. + +Give this unit test method a specific name. Here we will continue with the `testGeneratePassword` and then we will write a specific condition we are going to test here. + +So the complete name should be `testGeneratePassword_nameLessThan4Charaters()`. + +```java + @Test + public void testGeneratePassword_nameLessThan4Charaters() { + String name= "Nic"; + int yearOFBirth = 2002; + + String expected = "Nic2002"; + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String actual = passwordGenerator.generatePassword(name, yearOFBirth); + + assertEquals(expected, actual); + } +``` + +Now our `PasswordGneratorTest` unit test class has two unit test methods and we can see both are passed. + +In `PasswordGnerator.java` we can see both if and else condition code is highlighted in green. + +![Code for both if and Else condition is covered](/assets/images/2022-08-30-junit-test-case/007-junit-covered-if-and-else-condition.png) + +Also, in the beginning, we checked if the name was null or not. If it is null, we will return the password as `null`. + +Currently, we have not covered it by writing any unit test case in the `PasswordGneratorTest.java` JUnit Test case. + +We can check this with the `assertNull()` method of the Assert class. + +```java + @Test + public void testGeneratePassword_nameIsNull() { + String name= null; + int yearOFBirth = 2002; + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String actual = passwordGenerator.generatePassword(name, yearOFBirth); + + assertNull(actual); + } +``` + +We can see all the code from `PasswordGnerator.java` is now Green i.e. covered. Also for `PasswordGnerator.java`, the code coverage percentage is showing 100% in the coverage window. + +![Showing All code covered and code coverage percentage](/assets/images/2022-08-30-junit-test-case/008-all-code-covered.png) + +Also, our `PasswordGneratorTest.java` unit test class has three unit test methods and we can see all tests are passed. + +![All Three Unit Test cases Passed](/assets/images/2022-08-30-junit-test-case/009-all-three-unit-test-show-success.png) + +This is how we have written our first unit test case using the JUnit - Unit Testing framework for Java Programming language. + +## Conclusion + +We have written three unit test methods in the `PasswordGneratorTest` JUnit test case to test the `generatePassword()` method of the `PasswordGenerator.java` + +We have used `assertEquals(expected, actual)` and `assertNull(actual) ` methods of the Assert class. + +In the first and second test methods, the test passes if the `expected` and `actual` results are the same. + +```java +assertEquals(expected, actual) +``` + +In the third test method test passes if the `actual` is `null`. + +```java +assertNull(actual) +``` + +--- + +The example Java programs used in the above article can be found at this GitHub repository, [coderolls/junit-tutorial](https://github.com/coderolls/junit-tutorial). + +Please write your thoughts in the comment section below. diff --git a/_posts/junit/2022-10-10-assertTrue-and-assertFalse-in-junit.md b/_posts/junit/2022-10-10-assertTrue-and-assertFalse-in-junit.md new file mode 100644 index 0000000..b8216a9 --- /dev/null +++ b/_posts/junit/2022-10-10-assertTrue-and-assertFalse-in-junit.md @@ -0,0 +1,103 @@ +--- +layout: post +title: "assertTrue() and assertFalse() in JUnit With Example" +author: gaurav +categories: [Unit Testing in Java, JUnit] +toc: true +description: "In This tutorial, we will see the assertTrue() and assertFalse() assertion methods from the JUnit with various examples." +--- + +In this tutorial, we will see the `assertTrue()` and `assertFalse()` assertion methods from the JUnit with various examples. + +The `Assertions` is a collection of utility methods that support asserting conditions in tests. + +## assertTrue(boolean condition) + +`assertTrue(boolean condition)` asserts that the supplied `condition` is `true`. + +Example: + +Here we will take a sample class `NumberHelper.java`. It has `isEven()` which checks if the number is even or not. + +The code for `NumberHelper.java` is given below. + +```java +package com.coderolls.SampleProject; + +public class NumberHelper { + + public boolean isEven(int num) { + + if(num%2==0) { + return true; + } + return false; + } +} +``` + +To test the `isEven()` method of the `NumberHelper.java` class we will create `NumberHelperTest.java` under `src\test\java` in [our maven project](/maven-project/). + +In `NumberHelperTest.java` we will create a test method `testIsEven()` method to test the `isEven()` method. + +```java +package com.coderolls.SampleProject; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class NumberHelperTest { + + @Test + public void testIsEven() { + int sampleNum = 2; + + NumberHelper numberHelper = new NumberHelper(); + assertTrue(numberHelper.isEven(sampleNum)); + } + +} +``` + +As shown in the code, I have taken a sample even number 2. + +We know that 2 is an even number so the `isEven()` method must return a `true` value. That's why we are using `assertTrue()` to assert the behaviour of the `isEven()` method. + +Once you run it as a JUnit test case (right-click in the unit test editor, Run as > JUnit Test) you can see the test is passed. + +## assertFalse(boolean condition) + +`assertFalse(boolean condition)` asserts that the supplied `condition` is `false`. + +Example: + +We will take the same class and method (`NumberHelper.java` and `isEven()` method) for the `assertFalse(boolean condition)` example. + +We will add an additional test method in the `NumberHelperTest.java` as `testIsEven_FalseCondition()`. + +Here we will take a `sampleNum` as `3`. + +We know 3 is not an even number, so the `isEven()` method must return `false`. To check it we can use `assertFalse()`. + +```java +@Test +public void testIsEven_FalseCondition() { + + int sampleNum2 = 3; + + NumberHelper numberHelper = new NumberHelper(); + assertFalse(numberHelper.isEven(sampleNum2)); +} +``` + +Once you run this test, it will pass. + +I have attached a screenshot below. It shows the test code with the `assertTrue()` and `assertFalse()` test method as well as both the unit test has passed. + +![NumberHelperTest.java code and showing both test passed](/assets/images/2022-10-10-assert-true-assert-false/001-assert-true-assert-false.png) + +--- + +The example Java programs used in the above article can be found at this GitHub repository, [coderolls/junit-tutorial](https://github.com/coderolls/junit-tutorial). + +Please write your thoughts in the comment section below. diff --git a/_posts/mongodb/mongodb-atlas/2023-10-19-connecting-to-mongodb-atlas-cluster-in-java-application.md b/_posts/mongodb/mongodb-atlas/2023-10-19-connecting-to-mongodb-atlas-cluster-in-java-application.md new file mode 100644 index 0000000..fe1e72f --- /dev/null +++ b/_posts/mongodb/mongodb-atlas/2023-10-19-connecting-to-mongodb-atlas-cluster-in-java-application.md @@ -0,0 +1,64 @@ +--- +layout: post +title: "How to Connect to a MongoDB Atlas Cluster in a Java Application" +author: gaurav +categories: [Java, MongoDB, MongoDB Atlas] +toc: true +description: "In this tutorial, we will see how to connect to a MongoDB Atlas cluster ina Java Application." +--- + +In this tutorial, we will see how to connect to a MongoDB Atlas cluster ina Java Application. + +Your Java application must use the [official MongoDB driver](https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-sync/4.10.2) to connect to a MongoDB Atlas cluster. + +You will add the MongoDB driver as dependency in your maven projects `pom.xml` file. + +```git + + + org.mongodb + mongodb-driver-sync + 4.10.2 + +``` +You can check the latest version at https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-sync + +To connect to MongoDB Atlas Cluster you need a valid connection String. The connection String is available in Atlas UI. You can get it by login to your Atlas account. + +The format of the Connection String is as given below. +```git +mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]mongodb+srv://[username:password@]host[/[defaultauthdb][?options]] +``` + +For example, +```git +mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority +``` +Here, `user123` is username and `password123` is a password. + +Once you have a valid connection string, you can create a MongoClient using connection string and connect to Atlas cluster as shown below. + +```java +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import org.bson.Document; + +import java.util.ArrayList; +import java.util.List; + +public class ConnectToMongoDBCluster { + + public static void main(String[] args) { + String connectionString = "mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority"; + try (MongoClient mongoClient = MongoClients.create(connectionString)) { + List databases = mongoClient.listDatabases().into(new ArrayList<>()); + databases.forEach(db -> System.out.println(db.toJson())); + } + } +} +``` + +When you run the main class `ConnectToMongoDBCluster`, it will connect to MongoDB Atlas cluster and print all the database. + + + diff --git a/_posts/mongodb/mongodb-crud-operations/2023-10-23-inserting-documents-in-mongodb-in-java.md b/_posts/mongodb/mongodb-crud-operations/2023-10-23-inserting-documents-in-mongodb-in-java.md new file mode 100644 index 0000000..73d1033 --- /dev/null +++ b/_posts/mongodb/mongodb-crud-operations/2023-10-23-inserting-documents-in-mongodb-in-java.md @@ -0,0 +1,77 @@ +--- +layout: post +title: "How To Insert A Document in MongoDB Collection in Java Applications?" +author: gaurav +categories: [Java, MongoDB, MongoDB CRUD Operations] +toc: true +description: "In this tutorial, we will see how to insert a document in MongoDB in Java applications." +--- + +In this tutorial, we will see how to insert a document in MongoDB in Java applications. + +To insert a document in the MongoDB collection, first, we should have a MongoClient. Let's see how to create one. Or You can read more at [How to Connect to a MongoDB Atlas Cluster in a Java Application](/connecting-to-mongodb-atlas-cluster-in-java-application) + +```java +String connectionString = "mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority"; +MongoClient mongoClient = MongoClients.create(connectionString); +``` + +The above `connectionString` is just an example, kindly get your valid connection String. + +We can insert a single or multiple documents in MongoDB Collections. + +Let's see how to insert a single document in MongoDB. + +## Insert a Single Document in the MongoDB Collection + +We can use the `insertOne()` method to insert a single document. + +The `insertOne()` method accepts an Object that contains Document data and returns an `InsertOneResult` Object. + +We can get the id of the inserted document from `InsertOneResult` (like `insertOneResult.getInsertedId()`. + +**Java Code to Insert a Single Document in a Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("apple_corp"); +MongoCollection collection = database.getCollection("employees"); + +Document employee = new Document("_id", new ObjectId()) + .append("id", "2023-06-1256") + .append("name", "Tee Wilson") + .append("joining_date", Date.from(LocalDate.of(2023, 6, 20).atStartOfDay(ZoneId.systemDefault()).toInstant())) + .append("status", "onboarding") + .append("bu", "newyork") + .append("address", new Document().append("city", "NEW YORK").append("zip", 10022).append("street", "PARK AVENUE").append("number", 25626)); + +InsertOneResult insertOneResult = collection.insertOne(inspection); +BsonValue id = insertOneResult.getInsertedId(); +System.out.println(id); +``` + +The above code will insert a single document `employee` in the `employees` Mongo collection. It will print the inserted document id on the console. + +## Insert Multiple Documents in MongoDB Collection + +We can use the `insertMany()` method to insert multiple documents. + +The `insertMany()` method accepts a list of Objects that contains Document data and returns the `InsertManyResult` Object. + +We can get the `id` of the inserted documents from `InsertManyResult` (like `insertManyResult.getInsertedIds().forEach((x,y)-> System.out.println(y.asObjectId()))`. + +**Java Code To Insert Multiple Documents in Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Document student1 = new Document().append("name","jack sparrow").append("roll_number","202306NJ253").append("due",1256).append("status","checking"); + +Document student2 = new Document().append("name","mary nelson").append("roll_number","202306NJ073").append("due",25).append("status","ready"); + +List students = Arrays.asList(student1, student2); +InsertManyResult insertManyResult = collection.insertMany(students); +insertManyResult.getInsertedIds().forEach((x,y)-> System.out.println(y.asObjectId())); +``` + +The above code will insert the `student1` and `student2` documents in the `students` collection. Also, it will print the ids of inserted documents. diff --git a/_posts/mongodb/mongodb-crud-operations/2023-10-26-finding-document-in-mongodb-in-java.md b/_posts/mongodb/mongodb-crud-operations/2023-10-26-finding-document-in-mongodb-in-java.md new file mode 100644 index 0000000..a1a6321 --- /dev/null +++ b/_posts/mongodb/mongodb-crud-operations/2023-10-26-finding-document-in-mongodb-in-java.md @@ -0,0 +1,64 @@ +--- +layout: post +title: "How To Find A Document in MongoDB Collection in Java Applications?" +author: gaurav +categories: [Java, MongoDB, MongoDB CRUD Operations] +toc: true +description: "In this tutorial, we will see how to find a document in MongoDB in Java applications." +--- + +In this tutorial, we will see how to find a document in MongoDB in Java applications. + +To insert a document in the MongoDB collection, first, we should have a MongoClient. Let's see how to create one. Or You can read more at [How to Connect to a MongoDB Atlas Cluster in a Java Application](/connecting-to-mongodb-atlas-cluster-in-java-application) + +```java +String connectionString = "mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority"; +MongoClient mongoClient = MongoClients.create(connectionString); +``` + +The above `connectionString` is just an example, kindly get your valid connection String. + +We can find the documents in MongoDB collection using `find()` and `find().first()` methods. + +Let's see how to find documents in the MongoDB collection using the `find()` method first. + +## Finding documents in MongoDB collection using the `find()` method + +The `find()` method accepts a query filter and returns documents that match the filter. + +In the following code, we will try to find all the students who have dues greater than 250 and status as checking. + +**Java Code to Find Documents in a Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +try(MongoCursor cursor = collection.find( + and(gte("due", 250),eq("status","checking"))) + .iterator()) +{ + while(cursor.hasNext()) { + System.out.println(cursor.next().toJson()); + } +} +``` + +## Finding a document in mongodb collection using the ``find().first()`` method + +The ``find().first()`` method accepts a query filter and returns the first document that matches the filter. + +In the following code, we will try to find the first student who has dues greater than 250 and status as checking. + +**Java Code to Find Single Documents in a Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Document doc = collection.find(Filters.and( + gte("due", 1000), Filters.eq("status", "checking"))).first(); + +System.out.println(doc.toJson()); +``` + diff --git a/_posts/mongodb/mongodb-crud-operations/2023-11-02-updating-documents-in-mongodb-in-java.md b/_posts/mongodb/mongodb-crud-operations/2023-11-02-updating-documents-in-mongodb-in-java.md new file mode 100644 index 0000000..b03cb63 --- /dev/null +++ b/_posts/mongodb/mongodb-crud-operations/2023-11-02-updating-documents-in-mongodb-in-java.md @@ -0,0 +1,65 @@ +--- +layout: post +title: "How To Update A Document in MongoDB Collection in Java Applications?" +author: gaurav +categories: [Java, MongoDB, MongoDB CRUD Operations] +toc: true +description: "In this tutorial, we will see how to update a document in MongoDB in Java applications." +--- + +In this tutorial, we will see how to update a document in MongoDB in Java applications. + +To update a document in the MongoDB collection, first, we should have a MongoClient. Let's see how to create one. Or You can read more at [How to Connect to a MongoDB Atlas Cluster in a Java Application](/connecting-to-mongodb-atlas-cluster-in-java-application) + +```java +String connectionString = "mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority"; +MongoClient mongoClient = MongoClients.create(connectionString); +``` + +The above `connectionString` is just an example, kindly get your valid connection String. + +We can update a single or multiple documents in MongoDB Collections. + +Let's see how to update a single document in MongoDB. + +## Update a Single Document in the MongoDB Collection + +We can use the `updateOne()` method to insert a single document. + +The `updateOne()` method accepts a filter that matches the document that we want to update, and a statement with the updates for the matching document. + +The `updateOne()` method only updates the first document that matches the filter. And it returns `UpdateResult`. + +**Java Code to Update a Single Document in a Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Bson query = Filters.eq("roll_number","202306NJ253"); +Bson updates = Updates.combine(Updates.set("status","ready"),Updates.inc("due",-1200)); +UpdateResult updateResult = collection.updateOne(query, updates); +``` + +The above code will update a single document `student` in the `students` Mongo collection that has `roll_number` as `202306NJ253`. The `status` will be updated to `ready` and the `due` will be decreased by the amount of `1200`. + +## Update Multiple Documents in MongoDB Collection + +We can use the `updateMany()` method to update multiple documents. + +The `updateMany()` method accepts a filter that matches the documents that we want to update, and a statement with the updates for the matching document. + +The `updateMany()` method updates all the documents that match the filter. And it returns `UpdateResult`. + +**Java Code To Update Multiple Documents in Collection** + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Bson query = Filters.eq("status","ready"); +Bson updates = Updates.combine(Updates.set("due",0)); +UpdateResult upResult = collection.updateMany(query, updates); +``` + +The above code will update all the documents of the `students` Mongo collection that have `status` as `ready`. It will set `due` for all the matching documents to `0`. diff --git a/_posts/mongodb/mongodb-crud-operations/2023-11-09-delete-documents-from-mongodb-collections.md b/_posts/mongodb/mongodb-crud-operations/2023-11-09-delete-documents-from-mongodb-collections.md new file mode 100644 index 0000000..a4e2265 --- /dev/null +++ b/_posts/mongodb/mongodb-crud-operations/2023-11-09-delete-documents-from-mongodb-collections.md @@ -0,0 +1,59 @@ +--- +layout: post +title: "How To Delete Documents in MongoDB Collection in Java Applications?" +author: gaurav +categories: [Java, MongoDB, MongoDB CRUD Operations] +toc: true +description: "In this tutorial, we will see how to delete documents in MongoDB in Java applications." +--- + +We have seen how to [insert](/inserting-documents-in-mongodb-in-java), [find](/finding-document-in-mongodb-in-java) and [update](/updating-documents-in-mongodb-in-java) documents in mongodb collection. In this tutorial, we will see how to delete documents in MongoDB in Java applications. + +To delete a document in the MongoDB collection, first, we should have a MongoClient. Let's see how to create one. Or You can read more at [How to Connect to a MongoDB Atlas Cluster in a Java Application](/connecting-to-mongodb-atlas-cluster-in-java-application) + +```java +String connectionString = "mongodb+srv://user123:password123@cluster0.example.mongodb.net/?retryWrites=true&w=majority"; +MongoClient mongoClient = MongoClients.create(connectionString); +``` + +The above `connectionString` is just an example, kindly get your valid connection String. + +We can delete a single document using `deleteOne()` or multiple documents using `deleteMany()` in MongoDB Collections. + +Let's see how to delete a single document in MongoDB. + +## Delete a single document using `deleteOne()` method + +We can use the `deleteOne()` method to delete a single document. The method accepts a query filter that matches the document that needs to be deleted. It will delete only the first documents that match. + +Let's see a code where we want to delete a student document where the roll number is + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Bson query = Filters.eq("roll_number","202306NJ253"); +DeleteResult deleteResult = collection.deleteOne(query); +System.out.println("Deleted a document:"); +System.out.println("\t" + deleteResult.getDeletedCount()); +``` + +## Delete multiple documents using `deleteMany()` method with a Query Object + +To delete multiple documents from a Mongodb collection we can use the `deleteMany()` method. + +We can pass a query filter that matches the objects that need to be deleted. If we pass an empty object, it will match with all the documents and delete all the documents. + +Let's see an example of deleting the student documents whose status is `rejected` + +```java +MongoDatabase database = mongoClient.getDatabase("texas_school"); +MongoCollection collection = database.getCollection("students"); + +Bson query = Filters.eq("status","rejected"); +DeleteResult deleteResult = collection.deleteMany(query); +System.out.println("Deleted a document:"); +System.out.println(deleteResult.getDeletedCount()); +``` + +The `deleteMany()` method returns a `Deleteresult` object. We can get the deleted documents to count from it like `deleteResult.getDeletedCount()`. diff --git a/ads.txt b/ads.txt deleted file mode 100644 index 80bc996..0000000 --- a/ads.txt +++ /dev/null @@ -1 +0,0 @@ -google.com, pub-4206814002327904, DIRECT, f08c47fec0942fa0 \ No newline at end of file diff --git a/assets/css/screen.css b/assets/css/screen.css index bdd2321..24f6482 100644 --- a/assets/css/screen.css +++ b/assets/css/screen.css @@ -4,20 +4,20 @@ Copyright: Sal, WowThemes.net, https://www.wowthemes.net License: https://www.wowthemes.net/freebies-license/ */ @media screen and (min-width:1500px) { - html { font-size:18px; } /* Increase the font size on higher resolutions */ - .container {max-width:80%;} + html { font-size:19px; } /* Increase the font size on higher resolutions */ + .container {max-width:90%;} } .mainheading { padding: 1rem 0rem; } a { - color: #00ab6b; + color: #6C63FF; transition: all 0.2s; } a:hover { - color: #038252; + color: #9400d3; text-decoration: none; } @@ -305,7 +305,7 @@ span.post-read-more a:hover { } .mainheading h1.sitetitle { - font-family: Roboto; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; } .mainheading h1.posttitle { @@ -330,7 +330,7 @@ span.post-read-more a:hover { } .article-post { - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 1.1rem; line-height: 1.84; color: rgba(0, 0, 0, .8); @@ -685,7 +685,7 @@ h3, h4, h5, h6 { - font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif; } .article-post .h1, @@ -711,7 +711,7 @@ h6 { } .layout-page .article-post { - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 1rem; } @@ -786,6 +786,12 @@ iframe { .jumbotron.fortags .row { margin: 0; } + + .related-posts-sidebar { + top: 100px; + margin-left: -120px; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + } } .jumbotron.fortags { diff --git a/assets/images/2019-12-20-basic-git-commands/git-clone.gif b/assets/images/2019-12-20-basic-git-commands/git-clone.gif index 6d98e57..14e2ec7 100644 Binary files a/assets/images/2019-12-20-basic-git-commands/git-clone.gif and b/assets/images/2019-12-20-basic-git-commands/git-clone.gif differ diff --git a/assets/images/2019-12-20-basic-git-commands/git-push.gif b/assets/images/2019-12-20-basic-git-commands/git-push.gif index 8e45323..cbfdddb 100644 Binary files a/assets/images/2019-12-20-basic-git-commands/git-push.gif and b/assets/images/2019-12-20-basic-git-commands/git-push.gif differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/001-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/001-maven-project.png new file mode 100644 index 0000000..c2fce18 Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/001-maven-project.png differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/002-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/002-maven-project.png new file mode 100644 index 0000000..3579948 Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/002-maven-project.png differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/003-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/003-maven-project.png new file mode 100644 index 0000000..97e3a26 Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/003-maven-project.png differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/004-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/004-maven-project.png new file mode 100644 index 0000000..53989ec Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/004-maven-project.png differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/005-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/005-maven-project.png new file mode 100644 index 0000000..36c8d63 Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/005-maven-project.png differ diff --git a/assets/images/2022-08-06-eclipse-maven-project/006-maven-project.png b/assets/images/2022-08-06-eclipse-maven-project/006-maven-project.png new file mode 100644 index 0000000..365cd07 Binary files /dev/null and b/assets/images/2022-08-06-eclipse-maven-project/006-maven-project.png differ diff --git a/assets/images/2022-08-30-junit-test-case/001-junit-project-structure.png b/assets/images/2022-08-30-junit-test-case/001-junit-project-structure.png new file mode 100644 index 0000000..f6e29b4 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/001-junit-project-structure.png differ diff --git a/assets/images/2022-08-30-junit-test-case/002-junit-test-case.png b/assets/images/2022-08-30-junit-test-case/002-junit-test-case.png new file mode 100644 index 0000000..a1aeaf8 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/002-junit-test-case.png differ diff --git a/assets/images/2022-08-30-junit-test-case/003-junit-test-case-create.png b/assets/images/2022-08-30-junit-test-case/003-junit-test-case-create.png new file mode 100644 index 0000000..2f3f2a6 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/003-junit-test-case-create.png differ diff --git a/assets/images/2022-08-30-junit-test-case/004-junit-test-case-run-green-bar.png b/assets/images/2022-08-30-junit-test-case/004-junit-test-case-run-green-bar.png new file mode 100644 index 0000000..6164ead Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/004-junit-test-case-run-green-bar.png differ diff --git a/assets/images/2022-08-30-junit-test-case/005-class-covered-by-junit.png b/assets/images/2022-08-30-junit-test-case/005-class-covered-by-junit.png new file mode 100644 index 0000000..917b608 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/005-class-covered-by-junit.png differ diff --git a/assets/images/2022-08-30-junit-test-case/006-junit-test-code-goes-green-when-no-errors.png b/assets/images/2022-08-30-junit-test-case/006-junit-test-code-goes-green-when-no-errors.png new file mode 100644 index 0000000..267bf90 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/006-junit-test-code-goes-green-when-no-errors.png differ diff --git a/assets/images/2022-08-30-junit-test-case/007-junit-covered-if-and-else-condition.png b/assets/images/2022-08-30-junit-test-case/007-junit-covered-if-and-else-condition.png new file mode 100644 index 0000000..b21cd6f Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/007-junit-covered-if-and-else-condition.png differ diff --git a/assets/images/2022-08-30-junit-test-case/008-all-code-covered.png b/assets/images/2022-08-30-junit-test-case/008-all-code-covered.png new file mode 100644 index 0000000..4b85592 Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/008-all-code-covered.png differ diff --git a/assets/images/2022-08-30-junit-test-case/009-all-three-unit-test-show-success.png b/assets/images/2022-08-30-junit-test-case/009-all-three-unit-test-show-success.png new file mode 100644 index 0000000..4c711ec Binary files /dev/null and b/assets/images/2022-08-30-junit-test-case/009-all-three-unit-test-show-success.png differ diff --git a/assets/images/2022-10-10-assert-true-assert-false/001-assert-true-assert-false.png b/assets/images/2022-10-10-assert-true-assert-false/001-assert-true-assert-false.png new file mode 100644 index 0000000..cbe5dc8 Binary files /dev/null and b/assets/images/2022-10-10-assert-true-assert-false/001-assert-true-assert-false.png differ diff --git a/assets/images/2023-11-04/java-platform-independent.png b/assets/images/2023-11-04/java-platform-independent.png new file mode 100644 index 0000000..060a2b2 Binary files /dev/null and b/assets/images/2023-11-04/java-platform-independent.png differ diff --git a/assets/images/2023-11-08/jdk-vs-jre-vs-jvm.png b/assets/images/2023-11-08/jdk-vs-jre-vs-jvm.png new file mode 100644 index 0000000..662b13b Binary files /dev/null and b/assets/images/2023-11-08/jdk-vs-jre-vs-jvm.png differ diff --git a/assets/images/coderolls_display.svg b/assets/images/coderolls_display.svg new file mode 100644 index 0000000..2e7d451 --- /dev/null +++ b/assets/images/coderolls_display.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/index.html b/index.html index fcf06c0..4998397 100644 --- a/index.html +++ b/index.html @@ -5,11 +5,57 @@ {% if page.url == "/" %} + + +
+ +