Home Java How to reverse a String in Java

How to reverse a String in Java

In this code example we show you how to reverse a string in Java

To reverse the string, we will use the reverse() method of the StringBuilder class

The reverse() method does not take any parameters and will reverse the character sequence. It returns a StringBuilder not a String

Example

public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        String myString = "maxprogramming";
        //print string
	System.out.println(myString);
        //reverse the string
	StringBuilder myStringBuilder = new StringBuilder(myString);
	myStringBuilder.reverse();
        //print string
	System.out.println(myStringBuilder);
    }
}

This displayed the following

run:
maxprogramming
gnimmargorpxam

You may also like