How to reverse a string in Java using for loop
Learn, how to reverse a string in Java by using the for loop
Here is an example, that reverses the name
string:
String name = "codejava";
// converting string into array of characters
char [] ch= name.toCharArray();
String reverse = ""; // initializing empty string
for(int i=0;i<ch.length;i++){
// looping through each character and adding it to reverse variable
reverse = ch[i]+reverse;
}
System.out.println(reverse); // printing the reverse string
Output:
avajedoc
In the above code, we first converted the string into a array of characters, then we initialized a empty string. At final, we loop through the each character inside a array from backwards and adding to the reverse variable.