function in java to reverse a string code example

Example 1: reverse string java

// Use StringBuilder for non-thread environment, it is faster
String string="whatever";
String reverse = new StringBuilder(string).reverse().toString();
System.out.println(reverse);

Example 2: reverse a string in java using input

public class Main {

    public static void main(String[] args) {
	// Write a Java program to reverse a string.
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the String:");
        char[] letters = input.nextLine().toCharArray();
        System.out.println(" Reverse String");
        for(int i = letters.length -1; i >= 0; i--){
            System.out.print(letters[i]);
        }
    }
}

Tags:

Java Example