Reverse a String

There are many ways of reversing a String in Java for whatever reason you may have. Today, we will look at a few simple ways of reversing a String in Java.

Method 1:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";

for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}

System.out.println("Reversed string is:");
System.out.println(reverse);
}
}

Method 2:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--)
{
sb.append(str.charAt(i));
}

System.out.println("Reversed string is:");
System.out.println(sb.toString());
}
}

Method 3:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder(str);

System.out.println("Reversed string is:");
System.out.println(sb.reverse().toString());
}
}

No comments:

Post a Comment