606

I have "Hello World" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there is some kind of a function already built-in into Java that does that.

Related: Reverse each individual word of "Hello World" string with Java

Massimiliano Kraus
3,9025 gold badges32 silver badges51 bronze badges
asked Sep 27, 2011 at 12:44
2
  • 10
    @JRL should really be String ih = "dlroW olleH"; System.out.println(ih); Commented Sep 27, 2011 at 12:49
  • 4
    I wish I could retract my close vote (as a duplicate). I re-read the other question and realized it's subtly different than this. However, this question is still duplicated many times over across the site. Probably ought to just find a different question to mark this a dupe of. Commented Sep 27, 2011 at 13:31

37 Answers 37

1
2
1223

You can use this:

new StringBuilder(hi).reverse().toString()

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

M. Justin
23.4k12 gold badges134 silver badges168 bronze badges
answered Sep 27, 2011 at 12:47
Sign up to request clarification or add additional context in comments.

5 Comments

"Thanks commentators for pointing out that StringBuilder is preferred nowadays"? There is a clear statement that StringBuffer if thread-safety is a concern. otherwise, StringBuilder can be used. StringBuilder is not a replacement for StringBuffer.
@ha9u63ar For this scenario with a local throwaway StringBuilder concurrency is not a concern (and I think that's what he meant).
Here's the link to know the exact difference between the two: javatpoint.com/… in short: StringBuilder is more efficient than StringBuffer. It's not thread safe i.e. multiple threads can simultaneously call methods of StringBuilder.
This won't work for Unicode characters outside of BMP, as long as for combining characters.
Hi Sir, Subject: Request to Update Broken Link – Javatpoint.com to TpointTech.com I hope you’re doing well. I recently noticed that your website contains links to Javatpoint.com, which has now moved to TpointTech.com. Would it be possible to replace the broken links to Javatpoint.com with the corresponding pages on TpointTech.com? I’d be happy to provide the updated URLs if needed. Looking forward to your response. Best regards, Mahesh Sharma [email protected] TpointTech.com
128

For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

public static String reverse(String input){
 char[] in = input.toCharArray();
 int begin=0;
 int end=in.length-1;
 char temp;
 while(end>begin){
 temp = in[begin];
 in[begin]=in[end];
 in[end] = temp;
 end--;
 begin++;
 }
 return new String(in);
}
answered Sep 5, 2014 at 23:29

2 Comments

Just a note though. This will fail horribly for "characters" that occupy two bytes.
Actually, it typically works fine for most characters that occupy 2 bytes. What it actually fails for is Unicode codepoints that occupy 2 x 16 bit codeunits (in UTF-16).
73
public static String reverseIt(String source) {
 int i, len = source.length();
 StringBuilder dest = new StringBuilder(len);
 for (i = (len - 1); i >= 0; i--){
 dest.append(source.charAt(i));
 }
 return dest.toString();
}

http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm

answered Sep 27, 2011 at 12:47

3 Comments

Good solution (1+). One enhancement - StringBuilder (since java5) will be faster than StringBuffer. Regards.
This won't work in the general case as it doesn't take into account that some "characters" in unicode are represented by a surrogate pair i.e. two Java chars, and this solution results in the pair being in the wrong order. The reverse method of StringBuilder should be fine according to the JavaDoc: docs.oracle.com/javase/7/docs/api/java/lang/…
Does it reverse unicode diacriticals in the right order?
71
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
answered Sep 27, 2011 at 12:48

2 Comments

What is the complexity of it? O(N) or more ? N is equal to length of the string.
O(n) since it has to iterate through the chars of the string at least once.
32

I am doing this by using the following two ways:

Reverse string by CHARACTERS:

public static void main(String[] args) {
 // Using traditional approach
 String result="";
 for(int i=string.length()-1; i>=0; i--) {
 result = result + string.charAt(i);
 }
 System.out.println(result);
 // Using StringBuffer class
 StringBuffer buffer = new StringBuffer(string);
 System.out.println(buffer.reverse()); 
}

Reverse string by WORDS:

public static void reverseStringByWords(String string) {
 StringBuilder stringBuilder = new StringBuilder();
 String[] words = string.split(" ");
 for (int j = words.length-1; j >= 0; j--) {
 stringBuilder.append(words[j]).append(' ');
 }
 System.out.println("Reverse words: " + stringBuilder);
}
answered Jan 24, 2015 at 5:52

1 Comment

better to use StringBuilder/StringBuffer for the result variable to avoid multiple object creation!
21

Take a look at the Java 6 API under StringBuffer

String s = "sample";
String result = new StringBuffer(s).reverse().toString();
aioobe
423k115 gold badges831 silver badges844 bronze badges
answered Sep 27, 2011 at 12:48

3 Comments

is this better than StringBuilder?
@CamHart No, it's slower, but probably only a tiny little bit.
A little benchmark with almost 100 million method calls showed a significant difference between StringBuffer and StringBuilder: stackoverflow.com/questions/355089/… But in this case, there are only two calls (reverse() and toString()), so the difference probably won't even be measurable.
16

Here is an example using recursion:

public void reverseString() {
 String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
 if(index == 0){
 return stringToReverse.charAt(0) + "";
 }
 char letter = stringToReverse.charAt(index);
 return letter + reverse(stringToReverse, index-1);
}
answered Nov 3, 2014 at 15:36

7 Comments

There are already far better answers, especially @DanielBrockman's. If an algorithm already exists in a standard library, there is no need to handcraft it and reinvent the wheel.
A "far better answer" concept is subjective. This may be exactly what someone is looking for.
The OP already stated that "there is some kind of a function already built-in into Java that does that" so his goal was to know exactly which "function" this is. Just posting an answer that has little to do with the actual question asked is non-sense. If someone was to ask for a custom implementation your answer would be justified, in this case it is not.
Downvote. Most other solutions are O(n) and can handle strings of pretty much any length, this one is O(n^2) and tends to crash with a StackOverflowError for strings longer than about 5000 chars (on JDK 8 VM, default config).
Well, maybe you didn't read jonskeet.uk/csharp/stringbuilder.html , or maybe you didn't understand it. Hint: String concatenation is fine if you create a string in one fell swoop, but not if you build a string in a loop (and in this case, recursion is a loop). Yeah, I do get a bit personal when people post bad code on SO and don't even understand what's bad about it. Good bye.
|
14

Using charAt() method

String name = "gaurav";
String reversedString = "";
 
for(int i = name.length() - 1; i >= 0; i--){
 reversedString += name.charAt(i);
}
System.out.println(reversedString);

Using toCharArray() method

String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
 
for(int i = stringCharArray.length - 1; i >= 0; i--) {
 reversedString += stringCharArray[i];
}
System.out.println(reversedString);

Using reverse() method of the StringBuilder

String name = "gaurav";
 
String reversedString = new StringBuilder(name).reverse().toString();
 
System.out.println(reversedString);

Check https://coderolls.com/reverse-a-string-in-java/

Anton Kesy
8182 gold badges12 silver badges19 bronze badges
answered Dec 6, 2021 at 14:58

Comments

12

Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.

The Algorithm is based on :

1.(A XOR B) XOR B = A

2.(A XOR B) XOR A = B

Code snippet:

public class ReverseUsingXOR {
 public static void main(String[] args) {
 String str = "prateek";
 reverseUsingXOR(str.toCharArray());
 } 
 /*Example:
 * str= prateek;
 * str[low]=p;
 * str[high]=k;
 * str[low]=p^k;
 * str[high]=(p^k)^k =p;
 * str[low]=(p^k)^p=k;
 * 
 * */
 public static void reverseUsingXOR(char[] str) {
 int low = 0;
 int high = str.length - 1;
 while (low < high) {
 str[low] = (char) (str[low] ^ str[high]);
 str[high] = (char) (str[low] ^ str[high]); 
 str[low] = (char) (str[low] ^ str[high]);
 low++;
 high--;
 }
 //display reversed string
 for (int i = 0; i < str.length; i++) {
 System.out.print(str[i]);
 }
 }
}

Output:

keetarp

answered Jul 20, 2016 at 8:27

Comments

12

Here is a low level solution:

import java.util.Scanner;
public class class1 {
 public static void main(String[] args) {
 Scanner in = new Scanner(System.in);
 String inpStr = in.nextLine();
 System.out.println("Original String :" + inpStr);
 char temp;
 char[] arr = inpStr.toCharArray();
 int len = arr.length;
 for(int i=0; i<(inpStr.length())/2; i++,len--){
 temp = arr[i];
 arr[i] = arr[len-1];
 arr[len-1] = temp;
 }
 System.out.println("Reverse String :" + String.valueOf(arr));
 }
}
answered Oct 27, 2015 at 9:00

Comments

12

I tried, just for fun, by using a Stack. Here my code:

public String reverseString(String s) {
 Stack<Character> stack = new Stack<>();
 StringBuilder sb = new StringBuilder();
 for (int i = 0; i < s.length(); i++) {
 stack.push(s.charAt(i));
 }
 while (!stack.empty()) {
 sb.append(stack.pop());
 }
 return sb.toString();
}
answered Nov 1, 2015 at 2:06

Comments

12

As others have pointed out the preferred way is to use:

new StringBuilder(hi).reverse().toString()

But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.

The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.

This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).

public static String reverseString(String s) {
 char[] chars = new char[s.length()];
 boolean twoCharCodepoint = false;
 for (int i = 0; i < s.length(); i++) {
 chars[s.length() - 1 - i] = s.charAt(i);
 if (twoCharCodepoint) {
 swap(chars, s.length() - 1 - i, s.length() - i);
 }
 twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
 }
 return new String(chars);
}
private static void swap(char[] array, int i, int j) {
 char temp = array[i];
 array[i] = array[j];
 array[j] = temp;
}
public static void main(String[] args) throws Exception {
 FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
 StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
 sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
 sb.append(".");
 fos.write(sb.toString().getBytes("UTF-16"));
 fos.write("\n".getBytes("UTF-16"));
 fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
Ardent Coder
4,1259 gold badges35 silver badges62 bronze badges
answered Sep 5, 2016 at 11:04

1 Comment

Good solution, only part missing is now handling of combining diacritics :-D
6

It is very simple in minimum code of lines

public class ReverseString {
 public static void main(String[] args) {
 String s1 = "neelendra";
 for(int i=s1.length()-1;i>=0;i--)
 {
 System.out.print(s1.charAt(i));
 }
 }
}
mkobit
47.9k12 gold badges162 silver badges159 bronze badges
answered Feb 2, 2015 at 2:43

1 Comment

I was going to write this now.. Found you have already written it !
3
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);

I used this method to turn names backwards and into lower case.

answered Oct 1, 2014 at 21:40

Comments

3

One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.

String s = "Hello My name is Sufiyan";

Put it in the stack frontwards

Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
 myStack.push(st.nextToken());
}

Print the stack backwards

System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
 System.out.print(myStack.pop());
 System.out.print(' ');
}
System.out.println('"');
answered Jan 7, 2015 at 9:48

Comments

3

This did the trick for me

public static void main(String[] args) {
 String text = "abcdefghijklmnopqrstuvwxyz";
 for (int i = (text.length() - 1); i >= 0; i--) {
 System.out.print(text.charAt(i));
 }
}
answered Nov 17, 2016 at 12:31

Comments

3

1. Using Character Array:

public String reverseString(String inputString) {
 char[] inputStringArray = inputString.toCharArray();
 String reverseString = "";
 for (int i = inputStringArray.length - 1; i >= 0; i--) {
 reverseString += inputStringArray[i];
 }
 return reverseString;
}

2. Using StringBuilder:

public String reverseString(String inputString) {
 StringBuilder stringBuilder = new StringBuilder(inputString);
 stringBuilder = stringBuilder.reverse();
 return stringBuilder.toString();
}

OR

return new StringBuilder(inputString).reverse().toString();
Gaslight Deceive Subvert
20.7k21 gold badges94 silver badges131 bronze badges
answered Feb 26, 2017 at 5:51

Comments

2
 public String reverse(String s) {
 String reversedString = "";
 for(int i=s.length(); i>0; i--) {
 reversedString += s.charAt(i-1);
 } 
 return reversedString;
 }
answered Nov 2, 2014 at 14:32

3 Comments

Again, surrogate pairs will become corrupted with this way.
@JamesSmith could you expand on this please?
Some unicode characters consist of two characters; if these two are switched around, the string is corrupted. Also, one commonly overlooked error is regex.
2

You can also try this:

public class StringReverse {
 public static void main(String[] args) {
 String str = "Dogs hates cats";
 StringBuffer sb = new StringBuffer(str);
 System.out.println(sb.reverse());
 }
}
Emil Sierżęga
2,1373 gold badges35 silver badges41 bronze badges
answered Nov 8, 2014 at 15:02

1 Comment

there are many method to reverse a string.this is one of them using stringbuffer class of java.accepted answer is using diff class to reverse which is not available in older version of JDK.
1
public class Test {
public static void main(String args[]) {
 StringBuffer buffer = new StringBuffer("Game Plan");
 buffer.reverse();
 System.out.println(buffer);
 } 
}
answered Feb 14, 2015 at 14:15

1 Comment

This doesn't answer the question.
1

All above solution is too good but here I am making reverse string using recursive programming.

This is helpful for who is looking recursive way of doing reverse string.

public class ReversString {
public static void main(String args[]) {
 char s[] = "Dhiral Pandya".toCharArray();
 String r = new String(reverse(0, s));
 System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
 if (source.length / 2 == i) {
 return source;
 }
 char t = source[i];
 source[i] = source[source.length - 1 - i];
 source[source.length - 1 - i] = t;
 i++;
 return reverse(i, source);
}
}
answered Mar 23, 2016 at 7:15

Comments

1

Procedure :

We can use split() to split the string .Then use reverse loop and add the characters.


Code snippet:

class test
{
 public static void main(String args[]) 
 {
 String str = "world";
 String[] split= str.split("");
 String revers = "";
 for (int i = split.length-1; i>=0; i--)
 {
 revers += split[i];
 }
 System.out.printf("%s", revers);
 } 
}
 //output : dlrow

answered Mar 28, 2017 at 17:57

Comments

0

Sequence of characters (or) StringString's Family :

String testString = "Yashwanth@777"; // ~1 1⁄4→D80016«220

Using Java 8 Stream API

First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.

public static String reverseString_Stream(String str) {
 IntStream cahrStream = str.chars();
 final int[] array = cahrStream.map( x -> x ).toArray();
 int from = 0, upTo = array.length;
 IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
 String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
 .mapToObj( reverseMapper ) // array[ lastElement ]
 .collect(Collectors.joining()) // Joining stream of elements together into a String.
 .toString(); // This object (which is already a string!) is itself returned.
 System.out.println("Reverse Stream as String : "+ reverseString);
 return reverseString;
}

Using a Traditional for Loop

If you want to reverse the string then we need to follow these steps.

  • Convert String into an Array of Characters.
  • Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
 if( reverse != null && reverse != "" && reverse.length() > 0 ) {
 char[] arr = reverse.toCharArray();
 String temp = "";
 for( int i = arr.length-1; i >= 0; i-- ) {
 temp += arr[i];
 }
 System.out.println("Reverse String : "+ temp);
 }
 return null;
}

Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes

StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.

StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );

StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.

answered Dec 17, 2018 at 11:19

Comments

0
public static String revString(String str){
 char[] revCharArr = str.toCharArray();
 for (int i=0; i< str.length()/2; i++){
 char f = revCharArr[i];
 char l = revCharArr[str.length()-i-1];
 revCharArr[i] = l;
 revCharArr[str.length()-i-1] = f;
 }
 String revStr = new String(revCharArr);
 return revStr;
}
answered May 4, 2019 at 4:46

Comments

0

Simple For loop in java

 public void reverseString(char[] s) {
 int length = s.length;
 for (int i = 0; i < s.length / 2; i++) {
 // swaping character
 char temp = s[length - i - 1];
 s[length - i - 1] = s[i];
 s[i] = temp;
 }
}
answered Aug 17, 2019 at 19:00

Comments

0

The short answer is that Java does not provide a general solution to reversing a String due to the "surrogate pairs" problem, which you have to allow for.

If the requirement is that it is guaranteed to work for all Unicode and in all languages (including Welsh :), then you have to roll your own. Just do an in-place array swap of the string as its code points:

public static String reverse(String str)
{
 // You get what you ask for ;)
 if (str == null) return null;
 // str.length() is equal to the number of unicode code points in a string
 if (str.isEmpty() || str.length() == 1) return str;
 final int[] codePoints = str.codePoints().toArray();
 final int len = codePoints.length;
 // swap in place
 for(int i = 0; i < codePoints.length/2; i++)
 {
 int tmp = codePoints[i];
 codePoints[i] = codePoints[len-i-1];
 codePoints[len-i-1] = tmp;
 }
 return new String(codePoints,0,len);
}

If you do this by using String.getBytes(), then all the bytes will be reversed, which will reverse all UTF-8 encodings, and any attempt using a Character that isn't an int code point will fail with any "astral plane" code points (those outside the BMP).

As a general solution this is reasonably efficient, but it is extremely simple and guaranteed to work for any string, which is probably want you want from a "general solution".

The only gotcha is if you read the String out of a UTF8/16 encoded file, you might have a BOM at the start, but that's outside the scope of the question.

-Blue

answered Aug 17, 2022 at 3:32

Comments

0

Using apache.commons.lang3

StringUtils.reverse(hi)
answered Oct 25, 2022 at 18:45

Comments

0
 String str = "Hello World";
 char[] strCharArr = str.toCharArray();
 for(int i = 0, k= strCharArr.length-1;i != k; i++, k--) {
 char temp = strCharArr[i];
 strCharArr[i] = strCharArr[k];
 strCharArr[k] = temp;
 }
 System.out.println(String.valueOf(strCharArr));
answered Nov 1, 2022 at 20:26

Comments

0

The following Solution worked for me

public class ReverseString {
public static void reverseString(char[] s) {
 int i = 0;
 int j = s.length - 1;
 while (i < j) {
 char temp = s[i];
 s[i] = s[j];
 s[j] = temp;
 i++;
 j--;
 }
}
public static void main(String[] args) {
 char[] input = {'h', 'e', 'l', 'l', 'o'};
 reverseString(input);
 System.out.println(new String(input)); // Output: "olleh"
}
answered Nov 2, 2023 at 13:40

Comments

-1

It gets the value you typed and returns it reversed ;)

public static String reverse (String a){
 char[] rarray = a.toCharArray();
 String finalvalue = "";
 for (int i = 0; i < rarray.length; i++)
 {
 finalvalue += rarray[rarray.length - 1 - i];
 } 
return finalvalue;

}

answered Jan 13, 2015 at 15:24

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.