- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Reverse a String
Reversing a string is a classic exercise that every developer encounters, whether in a technical interview or while performing data manipulation in a real-world application. In Java, because String objects are immutable (meaning they cannot be changed once created), we can't simply flip the characters in place on the original object. Instead, we have to create a new representation of the string.
The following program demonstrates the most common logic-based approach: converting the string into a character array and using the "two-pointer" technique to swap characters from the outside in.
public class ReverseString {
public static void main(String[] args) {
// Input string - this could come from a database, user input, or a file
String str = "Hello, World!";
// Call the reverseString method and print the result
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reverseString(str));
}
/**
* Method to reverse a string using a two-pointer approach.
* This is highly efficient as it performs the swap in O(n/2) time.
*/
public static String reverseString(String str) {
// Handle edge cases like null or empty strings
if (str == null || str.isEmpty()) {
return str;
}
// Convert the string to a character array so we can modify it
char[] charArray = str.toCharArray();
// Initialize variables for indices
int left = 0;
int right = charArray.length - 1;
// Iterate through the character array and swap characters
while (left < right) {
// Swap characters at left and right indices using a temporary variable
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
// Move indices towards the center to meet in the middle
left++;
right--;
}
// Convert the character array back to a string and return it
return new String(charArray);
}
}
for loop and concatenating characters (e.g., newString += str.charAt(i)). In Java, this creates a new String object in every iteration of the loop, which is very slow and memory-intensive for long strings.
This program defines a reverseString method that takes a string as input, converts it to a character array, and then iterates through the array to swap characters from both ends until the entire string is reversed. Finally, it returns the reversed string. The main method demonstrates how to use this method by passing a sample string and printing the original and reversed strings.
How the Logic Works
The algorithm used above is known as the Two-Pointer Technique. We place one pointer at the start (index 0) and another at the end (length - 1). As we move the start pointer forward and the end pointer backward, we swap the characters at those positions. This process stops when the pointers meet or cross in the middle, ensuring every character is moved exactly once.
StringBuilder class. It includes a highly optimized .reverse() method: return new StringBuilder(str).reverse().toString();.
null values before performing operations on a string. Calling .toCharArray() or .length() on a null object will trigger a NullPointerException, crashing your application.
codePoints() to ensure multi-byte characters are handled correctly.
Real-World Applications
While reversing "Hello World" is a simple exercise, string manipulation like this is used in several practical scenarios:
- Data Masking: Quickly obfuscating parts of a string for logging purposes.
- Palindrome Checking: Determining if a word reads the same forward and backward (e.g., "radar").
- Bioinformatics: Reversing DNA sequences (reversing "ATGC" to "CGTA") for genetic analysis.
- UI Effects: Creating interesting visual text animations or "typewriter" effects in CLI tools.