In Java, you can reverse a string in several ways. Here are three common methods to reverse a string: String reverse program in java using StringBuilder
| public class StringReverseExample { public static void main(String[] args) { String original = "Hello, World!"; StringBuilder reversed = new StringBuilder(original).reverse(); String reversedString = reversed.toString(); System.out.println("Reversed string: " + reversedString); } } |
This program uses the StringBuilder class, which is a mutable sequence of characters. Here’s how it works: Using a loop to reverse the string character by character:
| public class StringReverseExample { public static void main(String[] args) { String original = "Hello, World!"; String reversed = reverseString(original); System.out.println("Reversed string: " + reversed); } public static String reverseString(String str) { StringBuilder reversed = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) { reversed.append(str.charAt(i)); } return reversed.toString(); } } |
… Read more