How to reverse a string in Java without using String.reverse()
Reverse a string in Java without using String.reverse()
We can use the for loop and the StringBuilder class to reverse a string.
Example
public class Main{public static String reverse(String input) {if (input == null) return null;StringBuilder output = new StringBuilder();for (int i = input.length() - 1; i >= 0; i--) {output.append(input.charAt(i));}return output.toString();}public static void main(String[] args){String text = "educative";System.out.println("Original string - " + text);System.out.println("Reversed string - " + reverse(text));}}
Explanation
- Line 3: We define the
reverse()method. - Line 5: We perform a Null check.
- Line 7: We create an instance of the
StringBuilderclass. - Lines 9–11: We traverse the input string from the last index to the first and the characters are appended to the
StringBuilderinstance. - Line 17: We define the
text. - Line 19: We invoke the
reverse()method.
Reverse the character array
First, the string is converted to a character array. Then, the array is reversed. A new string is formed from the reversed array.
Example
public class Main{public static String reverse(String input) {char[] characters = input.toCharArray();int n = characters.length;for (int i = 0; i < n / 2; i++) {char c = characters[i];characters[i] = characters[n - i - 1];characters[n - i - 1] = c;}return new String(characters);}public static void main(String[] args){String text = "educative";System.out.println("Original string - " + text);System.out.println("Reversed string - " + reverse(text));}}
Explanation
- Line 3: We define the
reverse()method. - Line 4: We convert the input string to a character array.
- Line 5: We assign the length of the input string/text to a variable.
- Lines 7–11: We reverse the character array.
- Line 13: We return a new string from the reverse character array.
- Line 17: We define the
text. - Line 19: We invoke the
reverse()method.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved