Java Online Compiler
Example: Reverse String using Two Pointers on charArray in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Reverse String using Two Pointers on charArray public class Main { public static void main(String[] args) { String originalString = "world"; // Step 1: Convert the original string to a character array char[] charArray = originalString.toCharArray(); // Step 2: Initialize two pointers: 'left' at the start, 'right' at the end int left = 0; int right = charArray.length - 1; // Step 3: Loop while the left pointer is less than the right pointer while (left < right) { // Step 4: Swap characters at 'left' and 'right' positions char temp = charArray[left]; charArray[left] = charArray[right]; charArray[right] = temp; // Step 5: Move pointers towards the center left++; right--; } // Step 6: Convert the character array back to a string String reversedString = new String(charArray); System.out.println("Original String: " + originalString); System.out.println("Reversed String: " + reversedString); } }
Output
Clear
ADVERTISEMENTS