Print String in reverse using java with example. This is most asked qustion in java interviews In below example we will see that.
Example
public class StringReverseExample {
public static void main(String[] args) {
String s = "java";
int stringLength = s.length();
// In Below for loop starting will be length-1
// The end will 0 the index
for (int i = stringLength - 1; i >= 0; i--) {
// we used charAt method to get value from the string
// instead of println we used print to print on same line
System.out.print(s.charAt(i));
}
}
}
Output
avaj
String reverse without for loop
public class StringReverse {
public static void main(String[] args) {
String s = "Java";
// Below we used StringBuilder to print string in reverse
StringBuilder builder = new StringBuilder(s);
System.out.println(builder.reverse());
}
}
Output
avaJ
To know more about StringBuilder, please refer below link
https://beginnersbug.com/stringbuilder-java/