We may not have the course you’re looking for. If you enquire or give us a call on 01344203999 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
In Java programming, working with strings is a usual task, and there may be times when you need to reverse a string in Java. Java offers several tools to handle string manipulation. Reversing a String in Java can be completed using various methods, each with advantages and drawbacks. Knowing how to manipulate strings in Java is essential for any Java developer, and mastering String reversal is a good place to start.
According to the TIOBE index, Java is one of the top programming languages used in the world, with a contributing community of more than 13%. Being a part of the community of one of the largest known programming languages is great.
Strings play an important role in programming in Java, and various ways exist to reverse them. Strings are immutable objects, so we need to create another string to reverse them. Check out this blog to learn how to reverse a string in Java with examples.
Table of Contents
1) Introducing String in Java
2) How to Reverse a String in Java?
a) Using StringBuilder
b) Swapping characters
c) Creating a new String
d) Using a list
e) Using Stack
f) Using StringBuffer
g) Using XOR operation
h) Converting to a byte array
i) Using recursion
3) Conclusion
Introducing String in Java
String is a series of characters in Java, including letters, numbers, whitespace, and punctuation. Strings are used to store and manipulate text in Java programs. Understanding Strings is an important part of learning Java programming, as they are widely used in many applications. You can create a string variable by using the keyword 'String' and assigning it a value within double quotes.
For example, “Hello, world!” is a string in Java.
For Example:
public class PrintString
{
public static void main(String[] args)
{
String myString = "Hello, World!";
System.out.println(myString);
}
}
Output: "Hello, World!"
How to Reverse a string in Java?
Below are some general methods by which a String can be reversed:
Using StringBuilder
To reverse a string in Java using StringBuilder, you can use the 'reverse()' method of the StringBuilder class.
For example:
String originalString = "Hello World!";
StringBuilder reversedString = new StringBuilder();
reversedString.append(originalString);
reversedString = reversedString.reverse();
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString.toString());
Output: !dlroW ,olleH
Create a new object named 'reversedString' and add the original string to it using its 'append()' method. Then call the 'reverse()' method on the StringBuilder object to reverse the contents of the string. Finally, print the reversed and original strings using the 'System.out.println()' method."
Swapping characters
Using the swapping characters method, a two-pointer approach can be used where one pointer should start from the beginning while another from the end of the string. The characters pointed to by both pointers are then exchanged, and the pointers move towards each other until they meet at the middle of the string.
For example:
public class StringReverseExample
{
public static void main(String[] args)
{
String input = "Hello, world!";
char[] charArray = input.toCharArray();
int left = 0;
int right = charArray.length - 1;
while (left < right)
{
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp; left++;
right--;
}
String output = new String(charArray);
System.out.println(output);
}
}
Output: Reversed string: !dlroW ,olleH
In this code, 'Hello, world!' is converted to a character array using the 'toCharArray()' method. Two pointers, 'left' and 'right', are initialized to point to the first and last characters of the array, respectively. In the while loop, the characters pointed to by 'left' and 'right' are interchanged using a temporary variable, 'temp', and the pointers are moved towards each other until they meet at the middle of the array.
Creating a new String
To reverse a string using the creation of a new string, firstly, you must create an empty string to store the reversed string. Then repeat over the characters of the original string from the end to the beginning and add each character to the new string in reverse order. Finally, return the new string.
For example:
public class ReverseString
{
public static String reverse(String str)
{
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--)
{
reversed += str.charAt(i);
}
return reversed;
}
public static void main(String[] args)
{
String original = "Hello, world!";
String reversed = reverse(original);
System.out.println("Original string: " + original);
System.out.println("Reversed string: " + reversed);
}
}
Output: Reversed string: !dlroW olleH
In the above example, a new string called 'reversed' is being created, and then a loop is used to repeat over the characters of the original string 'str' from the end to the beginning. Each character must be added to the 'reversed' string in reverse order using the '+=' operator. Finally, return the 'reversed' string. In the main method, call the 'reverse' method with an example string and print out the original and reversed string to the console.
Understand the process of web application development by learning Java programming with our Web Development Using Java Training course now!
Using a list
In Java, you can reverse a string by converting it to a list of characters. Then, you can reverse the list and convert it back to a string.
For example:
import java.util.*;
public class StringReversal
{
public static void main(String[] args)
{
String originalString = "Hello, world!";
// Convert the string to a list of characters List
for (char c : originalString.toCharArray())
{
charList.add(c);
}
// Reverse the list Collections.reverse(charList);
// Convert the reversed list back to a string StringBuilder reversedString = new StringBuilder(charList.size());
for (Character c : charList)
{
reversedString.append(c);
}
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString.toString());
}
}
Output: Reversed string: !dlrow ,olleH
In the example above, the original string is converted to a list of characters using a for-each loop that iterates over the characters of the string. Then, the list is reversed using the Collections.reverse() method. Finally, the reversed list is converted back to a string using a StringBuilder and another for-each loop.
Using Stack
To reverse a String using a stack in Java, first, the character array should be converted into a String. Then, each character of the array should be pushed into the stack. The popped characters from the stack should be added to StringBuilder. Finally, return the reversed string.
Here is an example code:
import java.util.*;
public class StringReversal
{
public static void main(String[] args)
{
String originalString = "Hello, world!";
// Convert the string to a list of characters List
for (char c : originalString.toCharArray())
{
charList.add(c);
}
// Reverse the list Collections.reverse(charList);
// Convert the reversed list back to a string StringBuilder reversedString = new StringBuilder(charList.size());
for (Character c : charList)
{
reversedString.append(c);
}
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString.toString());
}
}
Output: Reversed string: !dlroW ,olleH
In the example given above, the 'reverseString' method takes an input String and converts it into a character array. It then pushes each character into a stack, pops each character from the stack, and adds it to a StringBuilder to create the reversed string. Finally, it returns the reversed string.
The main method creates an input string and calls the 'reverseString' method to reverse the String. Finally, the console prints the reversed string.
Using StringBuffer
In Java, you can reverse a string using the 'StringBuffer' class. It provides a 'reverse()' method that can be used to reverse the order of characters of the string. Below is a code snippet that shows how to reverse a String using StringBuffer.
For example:
public class StringBufferExample
{
public static void main(String[] args)
{
String str = "Hello World";
StringBuffer sb = new StringBuffer(str);
// Reverse the string using StringBuffer sb.reverse();
// Print the reversed string System.out.println("Reversed string: " + sb.toString());
}
}
Output: Reversed string: dlroW olleH
In the example given above, first, a 'Hello World' string is created. Then a new StringBuffer object is created, and the string is passed as a parameter to its constructor. The 'reverse()' method is called on the StringBuffer object to reverse the String. Finally, the reversed string is printed using the 'toString()' method.
Using XOR operation
XOR operation is not generally used to reverse a string in Java. The most common way to reverse a string in Java is by using the 'StringBuilder' class or by iterating through the characters in the string and reversing them manually.
However, if you are interested in using XOR operation to reverse a string, one way is to XOR each character in the string with the corresponding character from the reversed string. This method requires that you have a second string to XOR with, so you need to create a copy of the original string and reverse it first.
Here is an example showing the implementation of reversing a string using XOR operation:
public static String reverseStringUsingXOR(String str)
{
char[] chars = str.toCharArray();
char[] reversedChars = new char[chars.length];
// Reverse the original string for (int i = 0; i < chars.length; i++)
{
reversedChars[i] = chars[chars.length - i - 1];
}
// XOR each character in the original string with the corresponding character in the reversed string for (int i = 0; i < chars.length; i++)
{
chars[i] = (char) (chars[i] ^ reversedChars[i]);
reversedChars[i] = (char) (chars[i] ^ reversedChars[i]);
chars[i] = (char) (chars[i] ^ reversedChars[i]);
}
return new String(chars);
}
Output: Reversed string: dlroW olleH
Please note that this method of reversing a string using XOR operation is not a recommended or commonly used approach in Java.
Learn how to develop application using Java with our Java Swing Development Training course today!
Converting to a byte array
To reverse a String in Java using converting to a byte array, first, use the ‘getBytes()’ method to convert the string to a byte array. Create a new byte array with the same length as the original byte array. Copy each element to the new byte array after iterating over the original byte array in reverse order. Finally, convert the new byte array back to a string using the string constructor that takes a byte array as an argument.
Here is an example code snippet that demonstrates this approach:
public class ReverseStringExample
{
public static void main(String[] args)
{
String str = "Hello, world!";
byte[] byteArray = str.getBytes();
byte[] reversedArray = new byte[byteArray.length];
for (int i = byteArray.length - 1, j = 0; i >= 0; i--, j++)
{
reversedArray[j] = byteArray[i];
}
String reversedString = new String(reversedArray);
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reversedString);
}
}
Output: Reversed string: !draw, olleH
Using recursion
To reverse a string in Java using recursion, you can define a recursive function that takes the original string as input and returns the reversed string as output.
Given below is an example of the implementation:
public class StringReversal
{
public static void main(String[] args)
{
String str = "hello world";
String reversed = reverseString(str);
System.out.println(reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
{
return str;
} else
{
return reverseString(str.substring(1)) + str.charAt(0);
}
}
}
The example given above explains how to reverse a string in Java using recursion. The 'reverseString' function takes a 'String' argument 'str' and returns the reversed string. If the input string is empty, an empty string is returned. If the input string is not empty, the function recursively calls itself with a substring of the original string that excludes the first character. Then, it concatenates the first character of the original string to the end of the reversed substring.
For example, when the input string is "hello world", the first call to 'reverseString' will be 'reverseString("hello world")'. This call will result in a periodic call to 'reverseString("ello world")', which will further call to a periodic call to 'reverseString("llo world")', and so on, until the base case of an empty string is reached. At this point, the function will start returning the reversed substrings connected, resulting in the final reversed string "dlrow olleh".
Conclusion
Reversing a string in Java is a basic programming task that can be attained using several methods. The blog discusses several approaches, including using loops, recursion, and built-in methods like StringBuilder and StringBuffer. Nonetheless, regardless of which method you choose, it’s crucial to get the logic behind it and implement it in the right manner. Testing your code is also important to ensure that it works as intended and gives the proper results. By mastering the techniques outlined in the article and practicing with different examples, you can become proficient in reversing strings in Java. With the examples and techniques presented in this article, you now have the knowledge and skills necessary to confidently tackle any string reversal task in your Java programs.
Know the essentials of Java and give a boost to your career; register for our Java Training course now!
Frequently Asked Questions
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 9th Dec 2024
Mon 6th Jan 2025
Mon 13th Jan 2025
Mon 20th Jan 2025
Mon 27th Jan 2025
Mon 3rd Feb 2025
Mon 10th Feb 2025
Mon 17th Feb 2025
Mon 24th Feb 2025
Mon 3rd Mar 2025
Mon 10th Mar 2025
Mon 17th Mar 2025
Mon 24th Mar 2025
Mon 7th Apr 2025
Mon 14th Apr 2025
Mon 21st Apr 2025
Mon 28th Apr 2025
Mon 5th May 2025
Mon 12th May 2025
Mon 19th May 2025
Mon 26th May 2025
Mon 2nd Jun 2025
Mon 9th Jun 2025
Mon 16th Jun 2025
Mon 23rd Jun 2025
Mon 7th Jul 2025
Mon 14th Jul 2025
Mon 21st Jul 2025
Mon 28th Jul 2025
Mon 4th Aug 2025
Mon 11th Aug 2025
Mon 18th Aug 2025
Mon 25th Aug 2025
Mon 8th Sep 2025
Mon 15th Sep 2025
Mon 22nd Sep 2025
Mon 29th Sep 2025
Mon 6th Oct 2025
Mon 13th Oct 2025
Mon 20th Oct 2025
Mon 27th Oct 2025
Mon 3rd Nov 2025
Mon 10th Nov 2025
Mon 17th Nov 2025
Mon 24th Nov 2025
Mon 1st Dec 2025
Mon 8th Dec 2025
Mon 15th Dec 2025
Mon 22nd Dec 2025