Java Program to Reverse a String

  • Java program to reverse a string without using any library function.
  • Write a java program to reverse a string using reverse method of StringBuilder.

In this java program, to reverse a string we will first ask user to enter a string and then reverse the input string before printing it on screen.

For Example,
Input String : TechCrashCourse
Reversed String : esruoChsarChceT

Java program to reverse a string using for loop

In this java program, we will traverse the input string in reverse order and keep on appending the characters at the end of reversed string.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to Reverse a String
 */
public class ReverseString {
    public static void main(String args[]) {
        String str, reverse = "";
        int i, length;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a String");
        str = scanner.nextLine();
        length = str.length();

        // Reversing a string
        for (i = length - 1; i >= 0; i--) {
            reverse = reverse + str.charAt(i);
        }

        System.out.println("Reversed String : " + reverse);
    }
}
Output
Enter a String
TechCrashCourse
Reversed String : esruoChsarChceT

Java program to reverse a string using reverse method of StringBuilder class

In this java program, we will create an object of class StringBuilder and initialize it with input string. Then we call reverse method of StringBuilder class to print reversed string on screen.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to Reverse a String using String Builder
 */
public class ReverseStringBuilder {
    public static void main(String args[]) {
        String str;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a String");
        str = scanner.nextLine();

        // Reversing a string
        StringBuilder str2 = new StringBuilder(str);

        System.out.println("Reversed String : " + str2.reverse());
    }
}
Output
Enter a String
TechCrashCourse
Reversed String : esruoChsarChceT