How to Reverse a String

A String can be reversed using reverse() method of StringBuider class and StringBuffer class. Below examples illustrates as to how to reverse a String.

Reverse a String using StringBuffer class :

package com.mathapachi;
public class StringReverseDemo {
	public static void main(String[] args) {
		 String str = "HelloWorld";
		 System.out.println("Original String = "+str);
		 StringBuffer stringBuffer = new StringBuffer(str);
		 String reversedStr = stringBuffer.reverse().toString();
		 System.out.println("Reversed String = "+reversedStr);
	}
}

Output of the above program is :

Original String = HelloWorld
Reversed String = dlroWolleH

The String can also be reversed using reverse() method of StringBuilder class.

Reverse a String using StringBuilder class :

package com.mathapachi;
public class StringReverseDemo {
	public static void main(String[] args) {
		 String str = "HelloWorld";
		 System.out.println("Original String = "+str);
		 StringBuilder stringBuilder = new StringBuilder(str);
		 String reversedStr = stringBuilder.reverse().toString();
		 System.out.println("Reversed String = "+reversedStr);
	}
}

Output of the above program is:

Original String = HelloWorld
Reversed String = dlroWolleH

How to Convert List into Array

The below method can be used to convert list into array.

Method Declaration


<T> T[] toArray(T[] a)

It returns an array containing all of the elements in the list in proper sequence; the runtime type of the returned array is that of the specified array.

Demo Program to Convert List into Array

ListIntoArrayConversionDemo.java

package com.mathapachi;

import java.util.ArrayList;
import java.util.List;

public class ListIntoArrayConversionDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		 List list = new ArrayList();
		 list.add("Lucknow");
		 list.add("Calcutta");
		 list.add("Mumbai");
		 
		 String[] listArray = list.toArray(new String[0]);
		 for(String str : listArray){
			 System.out.println(str); 
		 }
	}

}

Output of the above program is as below:

Lucknow
Calcutta
Mumbai