Java Programs

Java Program for Reverse of String

Here we are going to write a program for Reverse of String in Java.

Reverse of String Example:

[java]

import java.util.Scanner;

public class StringReverse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Any Word : ");
        String input = sc.nextLine();
        System.out.println("Reverse is : "+reverse(input));
    }

    public static String reverse(String input) {
        String reverse = null;
        char[] data = null;
        try {
            if (input != null) {
                data = input.toCharArray();

                int start = 0;
                int end = input.length() – 1;

                while (start < end) {
                    data[start] ^= data[end];
                    data[end] ^= data[start];
                    data[start] ^= data[end];
                    ++start;
                    –end;
                }
                reverse = String.valueOf(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            data = null;
        }
        return reverse;
    }
}
[/java]

Output :

Enter Any Word : onlinetutorialspoint
 Reverse is : tniopslairotutenilno

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment