Reverse a String in Java using + operator
In this post, we will show we how to reverse a string in Java using the + operator, which is also known as the string concatenation operator. We will also explain the advantages and disadvantages of this method, and provide some code examples to help us understand better.
The + operator is a binary operator that can be used to perform arithmetic addition and string concatenation in Java. When both operands are numeric values, such as int or double, the + operator performs arithmetic addition and returns the sum of the operands. When at least one of the operands is a string, the + operator performs string concatenation and returns a new string containing the characters of both operands.
We can use the string concatenation operator + to reverse a string in Java by reading characters from the end of it and concatenating them at the beginning of a new string. Please note that to increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the total number of intermediate string objects created by evaluation of an expression[1].
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class Main { // Reverse a string in Java using the string concatenation operator public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // variable to store the reversed string String rev = ""; // build the reversed string by reading character from the end // of the original string for (int i = str.length() - 1; i >=0 ; i--) { rev += str.charAt(i); } return rev; } public static void main(String[] args) { String str = "Reverse me!"; System.out.println("Original string: " + str); // "Reverse me!" str = reverse(str); // string is immutable System.out.println("Reversed string: " + str); // "!em esreveR" } } |
To conclude, using the + operator to reverse a string in Java is simple and intuitive. However, it is better to use StringBuilder or StringBuffer classes for manipulating strings, as they are more efficient and reliable than using + operator. We can learn more about these methods in this article.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)