Java Program to Reverse a String

Here is a Java program to reverse a string without using any library function. 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;

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;

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

Recommended Posts
Java Program to Find Length of a String
Java Program to Copy a String
Java Program to Concatenate Two Strings
Java Program to Delete a Word from Sentence
Java Program to Delete all Vowel Characters from String
Java Program to Delete All Spaces from a String
Java Program to Find Count of Each Character in a String
Java Program to Check Two Strings are Anagram or Not
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Count Words in a Sentence
All Java Programs