Reversing a string is a common programming problem faced by developers. While Java provides built-in methods such as reverse()
and reverseOrder()
to reverse a string, it is often required to develop a custom function that can reverse a string without using any built-in methods. Here's a Java function that can do the same:
public static String reverseString(String str){
String result = "";
for (int i = str.length()-1;
i>=0;
i--){
result += str.charAt(i);
}
return result;
}
In this function, we have taken a string as input and used a for loop to iterate over the characters in the string. Starting from the last character, we have appended each character to a new string called result
. Finally, we have returned the reversed string result
.
This function can be called by passing the input string as an argument. For example:
String str = "example";
String reversed = reverseString(str);
System.out.println("Reversed string:
"+reversed);
The above code will output:
Reversed string:
elpmaxe
This function can be useful in scenarios where built-in methods are not allowed or when developing coding solutions in environments that lack these methods.