There are several ways to reverse a string in Java. Here are a few options:
class Main {
public static void main(String[] args) {
String str = "Hello World!";
String reversed = reverseString(str);
System.out.println(reversed);
}
public static String reverseString(String str) {
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
}
In this example, the reverseString method takes a string as an argument and returns a new string that is the reverse of the input string. The loop starts at the last character in the string and iterates backward, adding each character to the beginning of the result string.
StringBuilder class: You can use the StringBuilder class and its reverse method to reverse a string. The StringBuilder class provides efficient methods for modifying strings and is often used for building strings in Java.class Main {
public static void main(String[] args) {
String str = "Hello World!";
String reversed = reverseString(str);
System.out.println(reversed);
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
In this example, the reverseString method creates a StringBuilder object with the input string, then uses the reverse method to reverse the string. Finally, the toString method is used to convert the StringBuilder object to a String.
class Main {
public static void main(String[] args) {
String str = "Hello World!";
String reversed = reverseString(str);
System.out.println(reversed);
}
public static String reverseString(String str) {
if (str.length() == 1) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
}
In this example, the reverseString method takes a string as an argument and returns a new string that is the reverse of the input string. The method calls itself on the substring starting at the second character, and adds the first character to the end of the result. The base case is reached when the length of the string is 1, in which case the string itself is returned.