Reversing a String In Java | How to Reverse a String in Java uisng charAt() Method.
Hello Readers...
In this post we are going to learn how to reverse a String in Java using for loop and charAt() method of String class. see example.
Output
In the above example i have created a simple class named as Reverse_String with main method. I have created a method named as reverseString() which takes String as an argument and declared a String empty/blank variable rev and performing the task of reversing of given String and print reverse of string. For any query use comment box, thanks.
Hello Readers...
In this post we are going to learn how to reverse a String in Java using for loop and charAt() method of String class. see example.
public class Reverse_String {
public static void reverseString(String str) {
String rev="";
for(int i=str.length()-1;i>=0;) {
rev=rev+str.charAt(i);
i--;
}
System.out.print("Reverse of "+str+" is : "+rev);
}
public static void main(String[] args) {
reverseString("DCBA");
}
}
Output
Reverse of DCBA is : ABCD
In the above example i have created a simple class named as Reverse_String with main method. I have created a method named as reverseString() which takes String as an argument and declared a String empty/blank variable rev and performing the task of reversing of given String and print reverse of string. For any query use comment box, thanks.
No comments