Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,778 answers

573 users

How to use XOR to swap two characters in a string in Java

1 Answer

0 votes
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

*/

 



answered Sep 29 by avibootz
...