Swapping Pairs of Characters in a String in Java

Swapping characters within a string is a common operation in Java programming, involving rearranging individual characters to achieve a desired order. The process holds significance in various scenarios, such as data encryption, algorithmic transformations, or enhancing string manipulation capabilities within Java applications.

Let's Explore various Java methods for character swapping and string generation.

Method 1 (Using toCharArray)

The Method involves converting the input string into a character array using the toCharArray Method, allowing direct manipulation of characters. It is suitable for scenarios where character-level modifications are needed.

Filename: StringSwapperDemo.java

Output:

After swapping characters at positions 6 and 8: javatpniot
After swapping characters at positions 0 and 9: tavatpoinj
Original String: javatpoint

Method 2 (Using subString())

Utilizing the substring() Method, this Method extracts and manipulates substrings within the input string, making it helpful for swapping pairs of characters or performing specific operations on portions of the string.

Filename: StringSwapperExample.java

Output:

After swapping characters at indices 6 and 8: javatpniot
After swapping first and last characters: tavatpoinj
Original String: javatpoint

Method 3 (Using StringBuilder or StringBuffer)

The technique utilizes the mutable StringBuilder or StringBuffer class, offering efficiency in string manipulations, especially for scenarios where multiple modifications are required in a string. It provides a dynamic and memory-efficient solution compared to immutable strings, allowing for in-place modifications.

Filename: StringBuilderStringSwapper.java

Output:

After swapping characters at indices 3 and 8: javntpoiat
After swapping first and last characters: tavatpoinj
Original String: javatpoint

Method 4 (Using XOR Operator)

In this Method, characters are swapped using the XOR operator, which is a bitwise exclusive OR operation. It provides a concise way to exchange values without a temporary variable, making it an interesting and bitwise-efficient approach for swapping characters.

Filename: StringSwapperXOR.java

Output:

After swapping characters at indices 3 and 8: javntpoiat
After swapping first and last characters: tavatpoinj
Original String: javatpoint





Latest Courses