Java program to reverse a String


In this article, we shall discuss how we can reverse a String or text using a Java program. This is also one of the most commonly asked interview questions in Java interviews.

Java Image


Using StringBuilder

To reverse a text in Java, we can use StringBuilder class. Here, we have to initialize a StringBuilder variable by passing the initial String which we want to reverse.

Once the StringBuilder object is initialized, we can use the reverse() method in this class as shown in the code snippet given below.

                
package com.samplequestions;

public class ReverseString {

	public static void main(String[] args) {
		String text = "I am a student";

		StringBuilder sb = new StringBuilder(text);
		System.out.println(sb.reverse());
	}
}
                
                


Without using StringBuilder

If you want to reverse a string without using this inbuilt reverse method, you can do this using a loop as shown below:

                    
package com.samplequestions;

public class ReverseStringWithoutStringBuilder {

	public static void main(String[] args) {
		String text = "I am a student";

		char[] textArray = text.toCharArray();

		String newText = "";
		for (int i = textArray.length - 1; i >= 0; i--) {
			newText += textArray[i];
		}
		
		System.out.println(newText);
	}

}

                    
                

In this program, we convert the text into an array of chars. Then we initialize a new variable to store the new reversed text. This variable is initialized with blank value.

Then we iterate through each char value in a for loop. Here, we start storing the char values in a new String variable in reverse order starting from the last character in the array.

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount