In this section, let's see how we can print a string in reverse. This is one of the questions that was asked in the Yahoo interview. Let's create a reversedemo
class for our example.
We have a string called Rahul
, and we want the output to be luhaR
. There is one more concept that we need to be aware of: a palindrome. If you type in a string, such as madam
, and we reverse the string, it would just give madam
as the output. Such types of strings are called palindromes. One such instance of a palindrome is shown in the following code:
package demopack; public class reversedemo { public static void main(String[] args) { String s = "madam"; String t= ""; for(int i=s.length()-1; i>=0; i--) { t= t+ s.charAt(i); } System.out.println(t); } }
We would start by creating a string, called s
, and an empty string, called t
. We create this empty string to concatenate each element after the for
loop to get...