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.
- 1A
Stringin Java is immutable, so the first step is converting it to achar[]withtoCharArray(). - 2Two pointers,
leftandright, start at index0andlength - 1— the opposite ends of the array. - 3At each step, the characters at
leftandrightare swapped using a temp variable, thenleftincrements andrightdecrements. - 4The loop stops once
leftmeets or crossesright, meaning every character has been swapped exactly once. - 5The mutated array is rebuilt into a
Stringwithnew String(chars), giving the reversed result.
"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.