If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To reverse a string in Java, you can use multiple approaches, such as using a StringBuilder
, StringBuffer
, or manually reversing the string by iterating through it. Here are three different methods to reverse a string:
javaCopy code
public class StringReverser {
public static String reverseString(String str) {
StringBuilder reversedString = new StringBuilder(str);
return reversedString.reverse().toString();
}
public static void main(String[] args) {
String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println("Original String: " + originalString);
System.out.println("Reversed String: " + reversedString);
}
}
Output:
yamlCopy code
Original String: Hello, World!
Reversed String: !dlroW ,olleH
javaCopy code
public class StringReverser {
public static String reverseString(String str) {
StringBuilder reversedString = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversedString.append(str.charAt(i));
}
return reversedString.toString();
}
public static void main(String[] args) {
String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println("Original String: " + originalString);
System.out.println("Reversed String: " + reversedString);
}
}
Output:
yamlCopy code
Original String: Hello, World!
Reversed String: !dlroW ,olleH
javaCopy code
import java.util.stream.Collectors;
public class StringReverser {
public static String reverseString(String str) {
return str.chars()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining(""))
.reverse();
}
public static void main(String[] args) {
String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println("Original String: " + originalString);
System.out.println("Reversed String: " + reversedString);
}
}
Output:
yamlCopy code
Original String: Hello, World!
Reversed String: !dlroW ,olleH
All three methods will produce the reversed string, and you can choose the one that suits your preference and requirements. The first two methods use StringBuilder
for better performance, while the third method uses Java 8 Streams for a more functional approach.
Comments: 0