Java Online Compiler
Example: Reverse String using Character Array in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Reverse String using Character Array public class Main { public static void main(String[] args) { // Step 1: Define the original string String originalString = "madam"; // Step 2: Convert the string to a character array char[] charArray = originalString.toCharArray(); // Step 3: Initialize two pointers: 'left' at the start, 'right' at the end int left = 0; int right = charArray.length - 1; // Step 4: Loop until the pointers cross each other while (left < right) { // Swap characters at the left and right positions char temp = charArray[left]; charArray[left] = charArray[right]; charArray[right] = temp; // Move pointers inward left++; right--; } // Step 5: Convert the modified character array back to a String String reversedString = new String(charArray); // Step 6: Print the original and reversed strings System.out.println("Original String: " + originalString); System.out.println("Reversed String: " + reversedString); } }
Output
Clear
ADVERTISEMENTS