Reverse a string in Java

  • Using built in reverse() method of the StringBuilder class:

// Java program to ReverseString using StringBuilder
import java.lang.*;
import java.io.*;
import java.util.*;

// Class of ReverseString
class ReverseString
{
	public static void main(String[] args)
	{
		String input = "StringToReverse";

		StringBuilder input1 = new StringBuilder();

		// append a string into StringBuilder input1
		input1.append(input);

		// reverse StringBuilder input1
		input1 = input1.reverse();

		// print reversed String
		System.out.println(input1);
	}
}
  • Converting String to character array:

// Java program to Reverse a String by converting string to characters one by one
import java.lang.*;
import java.io.*;
import java.util.*;

// Class of ReverseString
class ReverseString
{
	public static void main(String[] args)
	{
		String input = "StringToReverse";

		// convert String to character array by using toCharArray
		char[] try1 = input.toCharArray();

		for (int i = try1.length-1; i>=0; i--)
			System.out.print(try1[i]);
	}
}
Advertisements

Leave a Reply