|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "How To Reverse A String In Java (5 ways)" |
| 4 | +author: gaurav |
| 5 | +image: assets/images/2019-12-02/alex-radelich.jpg |
| 6 | +categories: [ Java, Core Java, String] |
| 7 | +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!" |
| 8 | +featured: true |
| 9 | +comments: true |
| 10 | +hidden: true |
| 11 | +--- |
| 12 | + |
| 13 | +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! |
| 14 | + |
| 15 | +## Introduction |
| 16 | + |
| 17 | +This question is simple but important since it is asked in most of the java interviews. You will be asked to reverse a string using a ready to use library method (like `reverse()` of `StringBuilder`) or without using a library method. In this article, we will see both ways. |
| 18 | + |
| 19 | +Below I have listed the 5 ways to reverse a string in Java. In all 5 cases, I will explain the step by step logic and gave the Java program for the same. |
| 20 | + |
| 21 | +1. Using charAt() method of String |
| 22 | + |
| 23 | +2. Using getBytes() method of String |
| 24 | + |
| 25 | +3. Using toCharArray() method of String |
| 26 | + |
| 27 | +4. Using reverse() method of StringBuilder |
| 28 | + |
| 29 | +5. Using reverse() method of Collections |
| 30 | + |
| 31 | +## 1. Using `charAt()` method of String |
| 32 | +`charAt()` method of the Java String returns character value at the specified index of the string. |
| 33 | +```java |
| 34 | +public char charAt(int index) |
| 35 | + |
| 36 | +where 'index' is the index of the character specified |
| 37 | + |
| 38 | +returns - char at specified index |
| 39 | + |
| 40 | +ex. |
| 41 | +String blogName = "codeRolls.com"; |
| 42 | +char returnedChar = blogName.charAt(3); // returns e |
| 43 | +``` |
| 44 | +I hope you have understood how the `charAt()` works, now we will see how can we use the same `charAt()` method to reverse the string. |
| 45 | + |
| 46 | +1. Declare a string that you have to reverse. eg. `blogName` |
| 47 | + |
| 48 | +2. Initialize an empty string with the name `reversedString`. |
| 49 | + |
| 50 | +3. Apply `for` loop to get the characters of the `blogName` in the reverse order i.e `int i = blogName.length()-1; i <= 0; i- -;` |
| 51 | + |
| 52 | +4. Inside the for loop append each character with the `reversedString`. |
| 53 | + |
| 54 | +5. Print the `reversedString`. |
| 55 | + |
| 56 | +A Java program to reverse the string using `charAt()` method of the String class is given below |
| 57 | +```java |
| 58 | +/** |
| 59 | + * A Java program to reverse a string. |
| 60 | + * We are using 'charAt()' method of the String class to get all char and arrange it in |
| 61 | + * descending order to get a reverse string. |
| 62 | + * |
| 63 | + * @author Gaurav Kukade at coderolls.com |
| 64 | + */ |
| 65 | +public class ReverseString { |
| 66 | + public static void main(String[] args) { |
| 67 | + |
| 68 | + String blogName = "coderolls.com"; |
| 69 | + String reversedString = ""; |
| 70 | + |
| 71 | + for(int i = blogName.length()-1; i>=0; i--){ |
| 72 | + reversedString = reversedString + blogName.charAt(i); |
| 73 | + } |
| 74 | + |
| 75 | + System.out.print("The reversed string of the '"+blogName+"' is: " ); |
| 76 | + System.out.println(reversedString); |
| 77 | + } |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +Output: |
| 82 | +```java |
| 83 | +The reversed string of the 'coderolls.com' is: moc.slloredoc |
| 84 | +``` |
| 85 | +#### Note: |
| 86 | +In the `for` loop, I have assigned `blogName.length()-1` to i instead of `blogName.length()` because the characters in the string are indexed from 0. |
| 87 | + |
| 88 | +I have given an image below to show the string indexing. |
| 89 | + |
| 90 | + |
| 91 | + |
| 92 | +## 2. Using `getBytes()` method of String |
| 93 | +In the `getBytes()` method of Java String first encodes the specified string into the sequence of bytes using the platforms default charset and then save the result in the byte array. The same byte array will be returned. |
| 94 | +```java |
| 95 | +public byte[] getBytes() |
| 96 | + |
| 97 | +It encodes the string into sequence of the bytes and return the byte array with this result |
| 98 | + |
| 99 | +returns - byte array of the encoded sequence of bytes |
| 100 | + |
| 101 | +ex. |
| 102 | +String blogName = "coderolls.com"; |
| 103 | +byte [] stringByteArray = blogName.getBytes(); |
| 104 | +``` |
| 105 | +Now we will see the step by step logic to reverse the string using the `getBytes()` method |
| 106 | + |
| 107 | +1. Declare a string that you have to reverse. eg. `blogName` |
| 108 | + |
| 109 | +2. Create a `byte []` to store the byte array of the specified string. Let say `stringByteArray` |
| 110 | + |
| 111 | +3. Create another `byte []` with the same length of the previous `byte [] stringByteArray`. Let say `reversedStringByteArray` |
| 112 | + |
| 113 | +4. Create a string `reversedString`. |
| 114 | + |
| 115 | +5. Apply for loop to iterate over `stringByteArray`. |
| 116 | + |
| 117 | +6. Using for loop set all the elements of the `stringByteArray` in reverse order with `reversedStringByteArray`. |
| 118 | + |
| 119 | +7. Create a new String object using `reversedStringByteArray` and assign it to the `reversedString`. |
| 120 | + |
| 121 | +8. Print `reversedString`. |
| 122 | + |
| 123 | +The program to reverse the string using `getBytes()` method of the Java String is given below |
| 124 | +```java |
| 125 | +/** |
| 126 | + * A Java program to reverse a string. |
| 127 | + * |
| 128 | + * We are using 'getByets()' method of the String class to get byte array of the specified string |
| 129 | + * and assign it to the another byte array of the same length in the descending order. |
| 130 | + * |
| 131 | + * New String object of the reversed byte array will give reversed string. |
| 132 | + * |
| 133 | + * @author Gaurav Kukade at coderolls.com |
| 134 | + */ |
| 135 | + |
| 136 | +public class ReverseStringUsingGetBytes { |
| 137 | + public static void main(String[] args) { |
| 138 | + |
| 139 | + String blogName = "coderolls.com"; |
| 140 | + byte[] stringByteArray = blogName.getBytes(); |
| 141 | + byte[] reverseStringByteArray = new byte[stringByteArray.length] ; |
| 142 | + String reversedString; |
| 143 | + |
| 144 | + for(int i = 0; i<=stringByteArray.length-1; i++) { |
| 145 | + reverseStringByteArray [i] = stringByteArray[stringByteArray.length-i-1]; |
| 146 | + } |
| 147 | + |
| 148 | + reversedString = new String(reverseStringByteArray); |
| 149 | + |
| 150 | + System.out.print("The reversed string of the '"+blogName+"' is: " ); |
| 151 | + System.out.println(reversedString); |
| 152 | + } |
| 153 | + |
| 154 | +} |
| 155 | +``` |
| 156 | + |
| 157 | +Output: |
| 158 | +```java |
| 159 | +The reversed string of the 'coderolls.com' is: moc.slloredoc |
| 160 | +Note: Like character indexing of the string, elements of the array starts from 0; that’s why I have used stringByteArray.length-1 in the for loop. |
| 161 | +``` |
| 162 | +## 3. Using toCharArray() method of String |
| 163 | + |
| 164 | +`toCharArray()` is an instance method of the String class in Java. |
| 165 | + |
| 166 | +`toCharArray()` method returns a new character array of the string specified. |
| 167 | +```java |
| 168 | +public char [] toCharArray() |
| 169 | + |
| 170 | +This method converts the string into new character array of the same length containing the character sequence represented by the string. |
| 171 | + |
| 172 | +returns - new char array containing character sequence represented by the string. |
| 173 | +Now we will see how can we use the toCharArray() method to reverse the string. |
| 174 | +``` |
| 175 | +Below I have given the step by step logic for the program to reverse string using `toCharArray()` method. |
| 176 | + |
| 177 | +1. Declare a string that you have to reverse. eg. `blogName` |
| 178 | + |
| 179 | +2. Create a new char array using the `blogName` string. eg. `stringCharArray` |
| 180 | + |
| 181 | +3. Create an empty string, we will be using that string to append with elements of the `stringCharArray`. Let say the empty string is `reversedString`. |
| 182 | + |
| 183 | +4. Apply for loop to iterate `stringCharArray` in the reverse order. |
| 184 | + |
| 185 | +5. In the for loop, append the `reversedString` with the `i`th element of the `stringCharArray`. |
| 186 | + |
| 187 | +6. Print the `reversedString`. |
| 188 | + |
| 189 | +I have given the program as per the above logic. |
| 190 | +```java |
| 191 | +/** |
| 192 | + * A Java program to reverse a string. |
| 193 | + * |
| 194 | + * We are using 'toCharArray' method of the String class to get char array of the specified string |
| 195 | + * and append it with the temp string in reverse order. |
| 196 | + * |
| 197 | + * @author Gaurav Kukade at coderolls.com |
| 198 | + */ |
| 199 | +public class ReverseStringUsingToCharArray { |
| 200 | + public static void main(String[] args) { |
| 201 | + |
| 202 | + String blogName = "coderolls.com"; |
| 203 | + char [] stringCharArray = blogName.toCharArray(); |
| 204 | + String reversedString = ""; |
| 205 | + |
| 206 | + for(int i = stringCharArray.length-1; i>=0; i--) { |
| 207 | + reversedString = reversedString + stringCharArray[i]; |
| 208 | + } |
| 209 | + |
| 210 | + System.out.print("The reversed string of the '"+blogName+"' is: " ); |
| 211 | + System.out.println(reversedString); |
| 212 | + } |
| 213 | +} |
| 214 | +``` |
| 215 | + |
| 216 | +Output: |
| 217 | +```java |
| 218 | +The reversed string of the 'coderolls.com' is: moc.slloredoc |
| 219 | +``` |
| 220 | +## 4. Using reverse() method of StringBuilder |
| 221 | + |
| 222 | +`reverse()` method of the `StringBuilder` class replaces the character sequence represented by a string in the reverse order. |
| 223 | +```java |
| 224 | +public StringBuilder reverse() |
| 225 | + |
| 226 | +reverse() method reverse the char sequence of the string |
| 227 | + |
| 228 | +return - reference to the StringBuilder object with reverse char sequence |
| 229 | +``` |
| 230 | +I have given the step by step logic for the program to reverse the string using `reverse()` method of `StringBuilder` class. |
| 231 | + |
| 232 | +1. Declare a string that you have to reverse. eg. `blogName` |
| 233 | + |
| 234 | +2. Create a new instance of the `StringBuilder` class as a `stringBuilder` using `blogName` string. |
| 235 | + |
| 236 | +3. Apply `reverse()` on the `stringBuilder` instance and assign it to the same `stringBuilder` instance. |
| 237 | + |
| 238 | +4. Print the `stringBuilder` instance. |
| 239 | + |
| 240 | +I have written the Java program to reverse the string using `reverse()` method of the `StringBuilder` class below. |
| 241 | +```java |
| 242 | +/** |
| 243 | + * A Java program to reverse a string. |
| 244 | + * |
| 245 | + * We are using 'reverse()' method of the StringBuilder class. This method rverse the |
| 246 | + * character sequence represented by the string. |
| 247 | + * |
| 248 | + * @author Gaurav Kukade at coderolls.com |
| 249 | + */ |
| 250 | + |
| 251 | +public class ReverseStringUsingReverseMethodOfStringBuilder { |
| 252 | + public static void main(String[] args) { |
| 253 | + |
| 254 | + String blogName = "coderolls.com"; |
| 255 | + |
| 256 | + StringBuilder stringBuilder = new StringBuilder(blogName); |
| 257 | + |
| 258 | + stringBuilder = stringBuilder.reverse(); |
| 259 | + |
| 260 | + System.out.print("The reversed string of the '"+blogName+"' is: "); |
| 261 | + System.out.println(stringBuilder); |
| 262 | + } |
| 263 | +} |
| 264 | +``` |
| 265 | + |
| 266 | +Output: |
| 267 | +```java |
| 268 | +The reversed string of the 'coderolls.com' is: moc.slloredoc |
| 269 | +``` |
| 270 | +## 5. Using reverse() method of Collections |
| 271 | + |
| 272 | +`reverse()` method of the Collections take list as a parameter and reverse the order of elements. |
| 273 | +```java |
| 274 | +public static void reverse(List<?> list) |
| 275 | + |
| 276 | +this method reverse the order of elements in the specified list |
| 277 | + |
| 278 | +parameters |
| 279 | +list - list whose elements you have to reverse |
| 280 | +``` |
| 281 | +The logic for the program to reverse a string using the `reverse()` method of the Collections is given below. |
| 282 | + |
| 283 | +1. Declare a string that you have to reverse. eg. `blogName` |
| 284 | + |
| 285 | +2. Create a new char array using the `blogName` string. eg. `stringCharArray` |
| 286 | + |
| 287 | +3. Create a new `ArrayList`. eg. `arrayList` |
| 288 | + |
| 289 | +4. Create an empty string, we will be using that string to append with elements of the `arrayList`. Let say the empty string is `reversedString`. |
| 290 | + |
| 291 | +5. Apply `forEach` loop to iterate over the `stringCharArray`. In the `forEach` loop add each element of the `stringCharArray` to `arrayList` |
| 292 | + |
| 293 | +6. Use`reverse()` method of the Collections to reverse the order of elements in `arrayList`. |
| 294 | + |
| 295 | +7. Apply `forEach` loop to iterate over `arrayList`. In the `forEach` loop append the `reversedString` with each element of the `arrayList`. |
| 296 | + |
| 297 | +8. Print `reversedString`. |
| 298 | + |
| 299 | +The program for the above logic is given below. |
| 300 | +```java |
| 301 | +/** |
| 302 | + * A Java program to reverse a string. |
| 303 | + * |
| 304 | + * We are using 'reverse()' method of the Collections. This method reverse the |
| 305 | + * order of elements of the list specified. |
| 306 | + * |
| 307 | + * @author Gaurav Kukade at coderolls.com |
| 308 | + */ |
| 309 | +import java.util.ArrayList; |
| 310 | +import java.util.Collections; |
| 311 | +import java.util.List; |
| 312 | +public class ReverseStringUsingReeverseMethodOfCollections { |
| 313 | + public static void main(String[] args) { |
| 314 | + |
| 315 | + String blogName = "coderolls.com"; |
| 316 | + char [] stringCharArray = blogName.toCharArray(); |
| 317 | + List<Character> arrayList = new ArrayList<>(); |
| 318 | + String reversedString = ""; |
| 319 | + |
| 320 | + for(char ch : stringCharArray) { |
| 321 | + arrayList.add(ch); |
| 322 | + } |
| 323 | + |
| 324 | + Collections.reverse(arrayList); |
| 325 | + |
| 326 | + for( Character ch: arrayList) { |
| 327 | + reversedString = reversedString + ch; |
| 328 | + } |
| 329 | + |
| 330 | + System.out.print("The reversed string of the '"+blogName+"' is: "); |
| 331 | + System.out.println(reversedString); |
| 332 | + } |
| 333 | + |
| 334 | +} |
| 335 | +``` |
| 336 | +Output: |
| 337 | +```java |
| 338 | +The reversed string of the 'coderolls.com' is: moc.slloredoc |
| 339 | +``` |
| 340 | +So we have seen all five ways to reverse the string in Java. |
| 341 | + |
| 342 | +## Conclusion |
| 343 | +We can reverse the string in multiple ways. I have listed the five ways below. |
| 344 | + |
| 345 | +1. Using `charAt()` method of String |
| 346 | + |
| 347 | + In the first way, we have used `charAt()` method to get every character of the specified string and append it to an empty string in the reveres order. |
| 348 | + |
| 349 | +2. Using `getBytes()` method of String |
| 350 | + |
| 351 | + In a second way, I have converted a string into byte Array and created another byte array with same length. Then I have inserted elements of byte array in the new byte array in the reverse order. Finally, convert new byte array to string to get the reverse string. |
| 352 | + |
| 353 | +3. Using `toCharArray()` method of String |
| 354 | + |
| 355 | + In a third way, I have converted the string to the character array using the `toCharArray()` method. Then I have to append and an empty string with every character of the character array in the reverse order. |
| 356 | + |
| 357 | +4. Using reverse() method of `StringBuilder` |
| 358 | + |
| 359 | + In a fourth way, I have created a `stringBuilder` instance using the string, which I have to reverse. And finally, I have used the `reverse()` method of the `StringBuilder` class to get the reversed string. |
| 360 | + |
| 361 | +5. Using reverse() method of Collections |
| 362 | + |
| 363 | + In the last way, I have created an `ArrayList` using the string, which I have to reverse. Then I have used `reverse()` method of the Collections to reverse the order of elements in the `ArrayList`. And finally, I have appended an empty string with every element of the `ArrayList` to get the reversed string. |
| 364 | + |
| 365 | +These are the ways we can reverse the string in Java. |
| 366 | + |
| 367 | +If you found this article worth, please [Give me a cup of Coffee ☕](https://www.paypal.me/GauravKukade) |
| 368 | + |
| 369 | +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. |
| 370 | + |
| 371 | +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. |
0 commit comments