Task: Write a Java String Class Reverse Program. You have to use only String class objects and String class built-in methods to reverse a user supplied string.
Logic behind Java String Reverse Program
You will use the following standard methods provided in String class:
- length() method to know the length of the original string.
- charAt(index) method to get a particular character from a string at given index.
- You will use + operator for string concatenation.
The actual logic behind this Reverse string Java Program is to take the last character from original string and place it in a second string at start. Next time the second last character will be obtained and concatenated with second string, and so on. So we will use a for loop form s1.length()-1 down to zero.
The Code of Java String Reverse Program
/*How you will reverse a string using String class only.*/ import java.util.Scanner; /** * * @author www.EasyCodeBook.com */ public class StringReverse { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a String to Reverse: "); String s1=input.nextLine(); String s2=""; for(int i=s1.length()-1;i>=0;i--) s2=s2+s1.charAt(i); System.out.println("Original string=" + s1); System.out.println("Reverse string=" + s2); } }
Output of Java String Reverse Program
Enter a String to Reverse: Hello Java
Original string=Hello Java
Reverse string=avaJ olleH
Enter a String to Reverse: Cricket Match
Original string=Cricket Match
Reverse string=hctaM tekcirC