Write a java program to reverse a string

We are discussing java program to reverse a string using following ways

  1. Java program to reverse a string using StringBuffer or StringBuilder class
  2. Java program to reverse a string using Loops(Iteration)

Java program to reverse a string using StringBuffer or StringBuilder class

import java.util.Scanner;
public class ReverseString {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a String");
        String string = scanner.next();
        StringBuilder sb = new StringBuilder(string);
        String reverseString = sb.reverse().toString();
        System.out.println("Your String is " + string);
        System.out.println("Reverse String is " + reverseString);
    }
}
 

Output

Enter a String
Programming
Your String is Programming
Reverse String is gnimmargorP
 

Java program to reverse a string using Loops(Iteration)

Copy and reverse the string

write a program to reverse a string

import java.util.Scanner;
public class ReverseStringExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a String");
        String string = scanner.next();
        char[] c = string.toCharArray();
        char[] r = new char[c.length];
        int i = c.length - 1;
        int j = 0;
        while (i >= 0) {
            r[j] = c[i];
            i--;
            j++;
        }
        String reverseString = new String(r);
        System.out.println("String is " + string);
        System.out.println("Reverse string is " + reverseString);
    }
}
 

Here getting input from the user

converted into character array using toCharArray() of String

Initialize the other character array with the same length as c character array.

Loop char array c in reverse order and r in forwarding order.

this will copy character array c in reverse order to r.

converted char array r to String

print both character array

Output

 
Enter a String
Java
String is Java
Reverse string is avaJ
 

Read More

  1. Duplicate Number between 1 to n numbers
  2. Print vowels in a String
  3. Sum of two numbers using command line arguments
  4. Prime number program in java using while loop
  5. Print vowels in a String
  6. Square Star Pattern