How To Convert Char To String and a String to char in Java
We will see two programs to reverse a string. First program reverses the given string using recursion and the second program reads the string entered by user and then reverses it.
To understand these programs you should have the knowledge of following core java concepts:
1) substring() in java
2) charAt() method
Program to reverse a string
public class JavaExample {
public static void main(String[] args) {
String str = "Welcome to Beginnersbook";
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output
The reversed string is: koobsrennigeB ot emocleW
Program to reverse a string entered by user
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
String str;
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
scanner.close();
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output
Enter your username:
How are you doing?
The reversed string is: ?gniod uoy era woH
You may also Find this interesting
Program to find even or odd numbers
Program to Display average of numbers
Program to Display Fabinocci Series
Program to Display Random Numbers
Program to Display Largest of Three numbers