Reversing a string is a popular problem that is often encountered during technical interviews or daily coding practice. In this post, we’ll discuss two different ways to reverse a string in Java: using an iterative approach and using built-in functions.
1. Iterative approach
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed += original.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
2. Using StringBuilder
public class ReverseStringWithBuilder {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println("Reversed String using StringBuilder: " + reversed);
}
}
© 2024, https:. All rights reserved. On republishing this post, you must provide link to original post