Friday, 21 April 2017

Reverse given String in java

This question is generally asked to the fresh college pass outs or the java developer with 1-3 years of experience. 

It's quite simple question. The sole purpose of asking it is to find out if you will preserve the immutability of String or not. Many directly apply reverse() method on given String itself forgetting that no such method exists for String operation.

To reverse a immutable String you will need use of StringBuffer or StringBuilder. Both has a difference among them but using any of them will allow you to serve the purpose.

Here we are showing you the example of StringBuffer.

Source fileReverseString .java

package String_Programs;

public class ReverseString {
       public static void main(String[] args) {
              String str = "Rajneesh";  //Remember, String is immutable
              //use StringBuffer(or Builder) for modification
              StringBuffer sb = new StringBuffer(str); 
              sb.reverse();  //reverse the string builder data             
              String modifiedStr = sb.toString();  //StringBuffer to String conversion
              System.out.println(str" when reversed :" + modifiedStr);


Rajneesh when reversed :hseenjaR


If you want to use StringBuilder then replace this line 

StringBuffer sb = new StringBuffer(str); 

in the above program with 

StringBuilder sb = new StringBuilder(str); 

You may like to read:

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.