Reverse a string in Java
To reverse a string in Java, you can use the following approaches:
- Using a
forloop:
public class Main {
public static void main(String[] args) {
String str = "Hello";
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(str.charAt(i));
}
String reversed = sb.toString();
System.out.println(reversed); // Output: "olleH"
}
}- Using the
reversemethod of theStringBuilderclass:
public class Main {
public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "olleH"
}
}- Using the
String.joinmethod (Java 8+):
public class Main {
public static void main(String[] args) {
String str = "Hello";
String reversed = String.join("", str.chars().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.toList()).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()));
System.out.println(reversed); // Output: "olleH"
}
}I hope this helps! Let me know if you have any other questions.