Java Tutorial
🔍

Reverse a String in Java

Program Overview

Reversing a string means printing its characters in the opposite order — "hello" becomes "olleh". It looks trivial, but it's one of the most common warm-up questions in Java interviews because it checks whether you understand character arrays, indexing, and in-place mutation instead of just calling a library method.

You'll also hit this logic in real work — generating palindrome checks, formatting reversed IDs, or processing text streams back-to-front.

Program

Core Logic

This program reverses a string using a two-pointer swap on a char array — one pointer starts at each end, and they swap characters while moving toward the middle until the array is fully mirrored.

How It Works
  1. 1A String in Java is immutable, so the first step is converting it to a char[] with toCharArray().
  2. 2Two pointers, left and right, start at index 0 and length - 1 — the opposite ends of the array.
  3. 3At each step, the characters at left and right are swapped using a temp variable, then left increments and right decrements.
  4. 4The loop stops once left meets or crosses right, meaning every character has been swapped exactly once.
  5. 5The mutated array is rebuilt into a String with new String(chars), giving the reversed result.
For "hello", the pointers swap 'h'↔'o' then 'e'↔'l', stopping once left meets right at the middle — producing "olleh".
💡

Key Point: This runs in O(n) time with a single pass; because Java strings are immutable, the O(n) extra space for the char array is unavoidable in a manual, built-in-free solution.