write a Java program for reverse string
Answers
Required Answer:-
Question:
- Write a Java program to reverse a String.
Solution:
Here is the program.
import java.util.*;
public class ReverseString {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String: ");
String s=sc.nextLine(), r="";
for(int i=s.length()-1;i>=0;i--)
r+=s.charAt(i);
System.out.println("Reversed String: "+r);
sc.close();
}
}
Explanation:
- We will ask the user to enter a String. Then, we will extract each characters of the string from the last and concatenate them to variable r. The reversed string is now stored in variable r. It is now displayed on the screen.
- Extracting characters from a specific location can be achieved by using charAt() function.
Sample I/O:
Enter a String: Brainly
Reversed String: ylniarB
Program:
import java.util.Scanner;
public class ReverseString {
public static void main(String[ ] args) {
System.out.print("Enter a string - ");
StringBuilder sb = new StringBuilder(new Scanner(System.in).nextLine( ));
// Using StringBuilder to reverse the String
System.out.println("Reversed String - " + sb.reverse( ).toString( ));
}
}