Mon. Apr 29th, 2024

In Java, you can reverse a string using several different methods. Here are three common approaches:

  1. Using a StringBuilder or StringBuffer class:
String original = "hello world";
StringBuffer reversed = new StringBuffer(original);
reversed = reversed.reverse();
System.out.println(reversed);

This approach creates a StringBuffer object from the original string, then calls the reverse() method to reverse the order of its characters. The toString() method can then be used to get the reversed string as a String object.

  1. Using a char array:
String original = "hello world";
char[] chars = original.toCharArray();
int length = chars.length;
for (int i = 0; i < length / 2; i++) {
    char temp = chars[i];
    chars[i] = chars[length - 1 - i];
    chars[length - 1 - i] = temp;
}
String reversed = new String(chars);
System.out.println(reversed);

This approach converts the original string to a char array, then swaps the characters from the beginning of the array with the characters from the end of the array until the middle of the array is reached. Finally, the char array is converted back to a String object.

  1. Using recursion:
public static String reverseString(String str) {
    if (str.isEmpty()) {
        return str;
    }
    return reverseString(str.substring(1)) + str.charAt(0);
}

String original = "hello world";
String reversed = reverseString(original);
System.out.println(reversed);

This approach uses recursion to reverse the string. The reverseString() method takes the original string and recursively calls itself with a substring of the original string that excludes the first character. Once the base case is reached (when the string is empty), the method re

All three of these methods will produce the same output: dlrow olleh. You can choose the one that works best for your specific use case.

By nerampo

Related Post