Tutorials Hut

Java Program to Reverse String Or Sentence

In this article we will discuss java programs to reverse string or sentence. We will look into two solutions, solution number one is using index of char in string and solution number two is using String builder class and its reverse method.

Example 1:

“Alex” reversed value of this string is “xelA”

Example 2:

“Alex is a boy” reversed value of this sentence is “yob a si xelA”

Java Program to Reverse String or Sentence

package problems;

class ReverseString {
static String reverseSol1(String str)
{
   //ed index
    int j = str.length() - 1;
    String result = "";
    while (j>=0) {
        result = result + str.charAt(j);
        j--;
    }
    return result;
}

static String reverseSol2(String str)
{
    StringBuilder strBuilder = new StringBuilder(str);
    //reverse with string builder
    return strBuilder.reverse().toString();
}

public static void main(String[] args)
{
    System.out.println("Solu 1, String 'Alex' is reversed to "+ reverseSol1("Alex"));
  System.out.println("Solu 2, String 'Dom' is reversed to "+ reverseSol2("Dom"));
    System.out.println("Solu 1, Sentence 'Alex is a boy' is reversed to "+ reverseSol1("Alex is a boy' is reversed to"));
    System.out.println("Solu 2, Sentence 'Alex is a boy' is reversed to "+ reverseSol2("Alex is a boy' is reversed to"));
}
}

Output

Solu 1, String 'Alex' is reversed to xelA
Solu 2, String 'Dom' is reversed to moD
Solu 1, Sentence 'Alex is a boy' is reversed to ot desrever si 'yob a si xelA
Solu 2, Sentence 'Alex is a boy' is reversed to ot desrever si 'yob a si xelA

 

 


















  • Leave a Reply

    Your email address will not be published. Required fields are marked *