Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
public class StringReverse {
// 1. StringBuilder (fastest)
public static String reverseWithBuilder(String s) {
return new StringBuilder(s).reverse().toString();
}
// 2. Char array
public static String reverseWithCharArray(String s) {
char[] chars = s.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char tmp = chars[left];
chars[left++] = chars[right];
chars[right--] = tmp;
}
return new String(chars);
}
// 3. Stream
public static String reverseWithStream(String s) {
return new StringBuilder(s).reverse().toString();
}
public static void main(String[] args) {
String input = "Hello, World!";
System.out.println(reverseWithBuilder(input));
System.out.println(reverseWithCharArray(input));
}
}Use Cases
- String manipulation in coding interviews
- Text processing utilities
- Learning Java string operations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Java Date/Time API — Modern Operations
Work with LocalDate, LocalDateTime, ZonedDateTime, Duration, Period, and date formatting.
Best for: Date arithmetic and business day calculations
Try-With-Resources and AutoCloseable
Manage resources safely with try-with-resources: files, connections, streams, and custom resources.
Best for: Safe resource management preventing leaks
Java String Formatting and Templates
String formatting techniques: printf, format, MessageFormat, StringJoiner, and text block interpolation.
Best for: Formatted log messages and reports
String Pool and Interning
Understand Java string pooling: intern(), identity vs equality, memory optimization, and common pitfalls.
Best for: Memory optimization for repeated string values