We are discussing java program to reverse a string using following ways
- Java program to reverse a string using StringBuffer or StringBuilder class
- Java program to reverse a string using Loops(Iteration)
Java program to reverse a string using StringBuffer or StringBuilder class
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a String");
String string = scanner.next();
StringBuilder sb = new StringBuilder(string);
String reverseString = sb.reverse().toString();
System.out.println("Your String is " + string);
System.out.println("Reverse String is " + reverseString);
}
}
Output
Enter a String Programming Your String is Programming Reverse String is gnimmargorP
Java program to reverse a string using Loops(Iteration)
Copy and reverse the string
write a program to reverse a string
import java.util.Scanner;
public class ReverseStringExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a String");
String string = scanner.next();
char[] c = string.toCharArray();
char[] r = new char[c.length];
int i = c.length - 1;
int j = 0;
while (i >= 0) {
r[j] = c[i];
i--;
j++;
}
String reverseString = new String(r);
System.out.println("String is " + string);
System.out.println("Reverse string is " + reverseString);
}
}
Here getting input from the user
converted into character array using toCharArray() of String
Initialize the other character array with the same length as c character array.
Loop char array c in reverse order and r in forwarding order.
this will copy character array c in reverse order to r.
converted char array r to String
print both character array
Output
Enter a String Java String is Java Reverse string is avaJ