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 codepublic 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 codeOriginal String: Hello, World!
Reversed String: !dlroW ,olleH
javaCopy codepublic 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 codeOriginal String: Hello, World!
Reversed String: !dlroW ,olleH
javaCopy codeimport 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 codeOriginal 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.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0