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
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