Beginners Programs :

Reverse A String In Java – 4 Ways | Programs

Reverse A String In Java – Here, we have discussed the various methods to reverse a string using java. The compiler has been added so that you can execute the programs by yourself, alongside suitable examples and sample outputs. The methods are as follows:

The following program to find reverse a string has been written in Five different ways. If you do have any doubts please do let us know.

Reverse A String – Using Static Method

1) String reverse(String s) is the static method This method contains the logic to reverse the string.

2) Create the object for the class ReverseofaString and call the static method with the object as rev.reverse(str)) by passing the given string.

Output:

Java Code Reverse A String – Using Array

1) We are using a character array to reverse the given string.

2) Read the entered string using scanner object scan.nextLine() and store it in the variable str. We are converting the string an to character array the string class method toCharArray() and initialized to char[] ch.

3) j=length of the array, for loop iterates from i=length of the array to i>0. The loop prints the character which is at the index i-1 of the array “ch” i.e. it prints the characters from the last index of the char array.

Output:

Using Recursion

1) A method which calls itself is recursive. In this program reverse(String s) is recursive.

2) Create the object for the class ReverseofaString rev. Read the entered string using sc.nextLine() and store it in the string variable str. Call the reverse method as rev.reverse(str).

Output:

Using While Loop

1) Here i=length of the given string. While loop iterates until the condition i>0 is false, i.e. if the length of the string is zero then cursor terminates the loop.

2) While loop prints the character of the string which is at the index (i-1) until i>0. Then we will get the reverse of a string.

Output:

Using For Loop

1) For loop iterates from j=length of the string to j>0.

2) It prints the character of the string which is at the index (i-1), then we will get reverse of a string.

Output:

Word by Word

1) Read the string using scanner object scan.nextLine() and store it in the variable str. We are converting the string into the char array using the string class method toChatArray(), and initialized to char[] ch.

2) The 1st for loop iterates from i=0 to i< length of the array.

a) If ch[i]!=’ ‘ then adding ch[0] to the string word. If block adds the characters to the string word until we will get space i.e. word contains the 1st word.

b) If we get space then the else block to reverse the word which is read using else block.

3) 2nd for loop reverse the last word which is read by else block.

Output: