I am attempting to write a string reverse function in Java (I am aware I can simply call an existing function, but I am trying this to practice and learn)
public class HelloWorld{
public static void main(String []args){
String s = reverse("abcd");
System.out.println(s);
}
public static String reverse(String str){
int end = str.length() - 1;
int start = 0;
char[] arr = str.toCharArray();
while (start < end)
{
arr[start] = arr[start] ^ arr[end];
arr[end] = arr[start] ^ arr[end];
arr[start] = arr[start] ^ arr[end];
start++;
end--;
}
String ret = new String(arr);
return ret;
}
}
However, it gives me these errors:
HelloWorld.java:16: error: possible loss of precision
arr[start] = arr[start] ^ arr[end];
^
required: char
found: int
HelloWorld.java:18: error: possible loss of precision
arr[end] = arr[start] ^ arr[end];
^
required: char
found: int
HelloWorld.java:20: error: possible loss of precision
arr[start] = arr[start] ^ arr[end];
^
required: char
found: int
3 errors
I have tried casting like
arr[end] = (char) arr[start] ^ arr[end];
Didn't solve the problem. What is going on here?