public class XorSwapProgram {
/**
* Swaps two characters in a character array using the XOR swap algorithm.
* <p>
* Note: This function demonstrates XOR swapping for educational purposes.
* In production code, standard temporary variable swaps are preferred
* for clarity and compiler optimization.
*
* @param text the character array containing characters to swap
* @param left the zero-based index of the first character
* @param right the zero-based index of the second character
*/
public static void xorSwapCharacters(char[] text, int left, int right) {
// Bounds checking and null validation
if (text == null || text.length == 0
|| left < 0 || left >= text.length
|| right < 0 || right >= text.length) {
return;
}
// XOR swap fails if left == right because (x ^ x) evaluates to 0
if (left == right) {
return;
}
text[left] ^= text[right];
text[right] ^= text[left];
text[left] ^= text[right];
}
public static void main(String[] args) {
String original = "hello";
char[] text = original.toCharArray();
System.out.println("Before: " + new String(text));
xorSwapCharacters(text, 1, 4);
System.out.println("After: " + new String(text));
}
}
/*
run:
Before: hello
After: holle
*/