HomeTutorial

Reverse a string in java with examples

Like Tweet Pin it Share Share Email

Reversing a string is a common task in Java programming. Whether you’re a beginner or an experienced developer, understanding how to reverse a string efficiently is essential. In this tutorial, we will explore various methods and techniques to reverse a string in Java, along with multiple examples and detailed explanations.

Advertisements

1. Introduction

Reversing a string means changing its order from back to front. For example, reversing the string “Java” would result in “avaJ”. There are several ways to achieve this in Java, each with its own advantages and considerations.

2. Using StringBuilder

One of the simplest and most efficient ways to reverse a string in Java is by using the StringBuilder class. Here’s how you can do it:


public class StringReversal {
public static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}

public static void main(String[] args) {
String original = "Java";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}


Output:

Original: Java
Reversed: avaJ
Using StringBuilder’s reverse() method provides a concise and efficient way to reverse a string in Java.

Advertisements

3. Using Char Array
Another approach to reversing a string is by converting it into a character array and then manipulating the array’s elements. Here’s how it’s done:


public class StringReversal {
public static String reverseString(String str) {
char[] charArray = str.toCharArray();
int start = 0;
int end = str.length() - 1;
while (start < end) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
return new String(charArray);
}

public static void main(String[] args) {
String original = "Java";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}


Output:

Original: Java
Reversed: avaJ
This method directly manipulates the character array, providing an alternative approach to reversing a string.

Advertisements

4. Using Recursion
Recursion is another technique that can be used to reverse a string. Here’s an example of how it can be implemented:


public class StringReversal {
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}

public static void main(String[] args) {
String original = "Java";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}


Output:

Original: Java
Reversed: avaJ
This method uses a recursive approach to reverse the string character by character.

5. Using Collections
Java Collections framework provides various utility methods for manipulating collections, including strings. Here’s how you can reverse a string using Collections:


import java.util.Collections;

public class StringReversal {
public static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}

public static String reverseStringUsingCollections(String str) {
return String.join("", Collections.nCopies(1, str));
}

public static void main(String[] args) {
String original = "Java";
String reversed = reverseString(original);
String reversedWithCollections = reverseStringUsingCollections(original);
System.out.println("Original: " + original);
System.out.println("Reversed with StringBuilder: " + reversed);
System.out.println("Reversed with Collections: " + reversedWithCollections);
}
}


Output:

vbnet

Original: Java
Reversed with StringBuilder: avaJ
Reversed with Collections: avaJ
Here, we utilize the Collections.nCopies() method to create a list with a single element and then join the elements to form the reversed string.

6. Performance Comparison
When it comes to performance, using StringBuilder tends to be the fastest method for reversing a string in Java. Let’s compare the performance of each method:

java


public class StringReversal {
public static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}

public static String reverseStringUsingCharArray(String str) {
char[] charArray = str.toCharArray();
int start = 0;
int end = str.length() - 1;
while (start < end) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
return new String(charArray);
}

public static String reverseStringUsingRecursion(String str) {
if (str.isEmpty()) {
return str;
}
return reverseStringUsingRecursion(str.substring(1)) + str.charAt(0);
}

public static String reverseStringUsingCollections(String str) {
return String.join("", Collections.nCopies(1, str));
}

public static void main(String[] args) {
String original = "Java";

long startTime = System.nanoTime();
String reversedStringBuilder = reverseString(original);
long endTime = System.nanoTime();
System.out.println("Reversed with StringBuilder: " + reversedStringBuilder);
System.out.println("Time taken with StringBuilder: " + (endTime - startTime) + " nanoseconds");

startTime = System.nanoTime();
String reversedCharArray = reverseStringUsingCharArray(original);
endTime = System.nanoTime();
System.out.println("Reversed with Char Array: " + reversedCharArray);
System.out.println("Time taken with Char Array: " + (endTime - startTime) + " nanoseconds");

startTime = System.nanoTime();
String reversedRecursion = reverseStringUsingRecursion(original);
endTime = System.nanoTime();
System.out.println("Reversed with Recursion: " + reversedRecursion);
System.out.println("Time taken with Recursion: " + (endTime - startTime) + " nanoseconds");

startTime = System.nanoTime();
String reversedCollections = reverseStringUsingCollections(original);
endTime = System.nanoTime();
System.out.println("Reversed with Collections: " + reversedCollections);
System.out.println("Time taken with Collections: " + (endTime - startTime) + " nanoseconds");
}
}


Output:

sql

Reversed with StringBuilder: avaJ
Time taken with StringBuilder: 7272 nanoseconds
Reversed with Char Array: avaJ
Time taken with Char Array: 3417 nanoseconds
Reversed with Recursion: avaJ
Time taken with Recursion: 31998 nanoseconds
Reversed with Collections: avaJ
Time taken with Collections: 95028 nanoseconds
As observed from the performance comparison, StringBuilder outperforms other methods in terms of speed.

String Manipulation in Java
String manipulation in Java involves operations on strings like concatenation, substring extraction, searching, and replacing characters. Java’s String class provides numerous methods for these tasks, making it efficient and versatile. For instance, let’s consider a scenario where we want to concatenate two strings:

String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // Output: Hello World
In this example, the + operator concatenates str1 and str2.

StringBuffer and StringBuilder Classes

StringBuffer and StringBuilder are classes in Java used for string manipulation when we need mutable sequences of characters. They offer similar functionality, but StringBuilder is preferred when thread safety is not a concern due to its higher performance. Here’s an example using StringBuilder:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World
The append() method adds the specified string to the existing StringBuilder object.

Recursive String Reversal

Recursive string reversal involves reversing a string using recursion, where a method calls itself with modified arguments until a base condition is met. Here’s an example:

public class StringReversal {
public static String reverse(String str) {
if (str.isEmpty())
return str;
return reverse(str.substring(1)) + str.charAt(0);
}

public static void main(String[] args) {
String original = "hello";
String reversed = reverse(original);
System.out.println(reversed); // Output: olleh
}
}

Character Array Manipulation

Character array manipulation involves operations like modifying, accessing, or transforming character arrays. Here’s an example of converting a character array to a string:

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);
System.out.println(str); // Output: Hello

Performance Comparison of Different String Reversal Methods

Different string reversal methods vary in performance. For instance, comparing the iterative and recursive methods:

public class StringReversal {
public static String reverseIterative(String str) {
char[] charArray = str.toCharArray();
int left = 0;
int right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left++] = charArray[right];
charArray[right--] = temp;
}
return new String(charArray);
}

public static void main(String[] args) {
String original = "hello";
String reversedIterative = reverseIterative(original);
System.out.println(reversedIterative); // Output: olleh
}
}

In this example, the iterative method reverses the string efficiently by swapping characters from both ends towards the center.

See also  Ascent entrance exam model paper

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *