Java
Java
Java
Example
In this tutorial we will discuss how to reverse a string in java . Although
there are many ways to get the solution but we are sharing 6 different ways
to reverse a string. This question is frequently asked in the technical
interview of java.This question is easy , but please mark this question in
your to do list before attending any technical interview in java. First we will
understand the question by writing example.
3. Then , we will scan the string from end to start, and print the character
one by one.
import java.io.*;
import java.util.*;
1. In the second method , we will use the built in reverse() method of the
StringBuilder class ,.
Note : String class does not have reverse() method . So we need to
convert the input string to StringBuilder , which is achieved by using the
append method of the StringBuilder.
2. After that print out the characters of the reversed string by scanning
from the first till the last index.
import java.io.*;
import java.util.*;
1. Convert the input string into character array by using the toCharArray()
built in method of the String Class .
2. In this method we will scan the character array from both sides , that is
from the start index (left) as well as from last index(right) simultaneously.
3. Set the left index equal to 0 and right index equal to the length of the
string -1.
4. Swap the characters of the start index scanning with the last index
scanning one by one .After that increase the left index by 1 (left++) and
decrease the right by 1 i.e (right--) to move on to the next characters in the
character array .
5. Continue till left is less than or equal to the right .
import java.io.*;
import java.util.*;
2. Then add the characters of the array into the LinkedList object . We used
LinkedList because it maintains the insertion order of the input values.
3. Java also has built in reverse() method for the Collections class . Since
Collections class reverse() method takes a list object , to reverse the list ,
we will pass the LinkedList object which is a type of list of characters.
4. We will create the ListIterator object by using the listIterator() method on
the LinkedList object.
ListIterator object is used to iterate over the list.
5. ListIterator object will help us to iterate over the reversed list and print it
one by one to the output screen.
import java.io.*;
import java.util.*;
import java.util.*;
import java.lang.*;
import java.io.*;
1. The last method is converting string into bytes . getBytes() method is
used to convert the input string into bytes[].
2. Then we will create a temporary byte[] of length equal to the length of
the input string.
3. We will store the bytes(which we get by using getBytes() method) in
reverse order into the temporary byte[] .
import java.io.*;
import java.util.*;