Write a Java function that takes a string as input and returns the reverse of the string. For example, if the input string is Hello, World!, the function should return !dlroW ,olleH.
Solution:
Heres a possible solution to the problem:
javaCopy codepublic class StringReversal {
public static String reverseString(String input) {
StringBuilder reversed = new StringBuilder();
for (int i = input.length() 1; i >= 0; i) {
reversed.append(input.charAt(i));
}
return reversed.toString();
}
public static void main(String[] args) {
String inputString = Hello, World!;
String reversedString = reverseString(inputString);
System.out.println(reversedString);
}
}
In this solution, we use a StringBuilder to build the reversed string. We iterate over the characters of the input string in reverse order using a for loop and append each character to the StringBuilder. Finally, we convert the StringBuilder to a String using the toString() method and return the reversed string.
Please note that this is just one example of a common Java problem. There are many other challenging problems that you may come across when working with Java or during programming interviews.