Skip to content

Instantly share code, notes, and snippets.

@gauravkukade
Created August 12, 2019 10:58
Show Gist options
  • Save gauravkukade/caed0052c4c2e5b98a4537d331ac848a to your computer and use it in GitHub Desktop.
Save gauravkukade/caed0052c4c2e5b98a4537d331ac848a to your computer and use it in GitHub Desktop.
A Java program to reverse a string. We are using 'getByets()' method of the String class to get byte array of the specified string and assign it to the another byte array of the same length in the descending order. New String object of the reversed byte array will give reversed string. The program is embedded at https://coderolls.com/reverse-a-s…
/**
* A Java program to reverse a string.
*
* We are using 'getByets()' method of the String class to get byte array of the specified string
* and assign it to the another byte array of the same length in the descending order.
*
* New String object of the reversed byte array will give reversed string.
*
* @author Gaurav Kukade at coderolls.com
*/
public class ReverseStringUsingGetBytes {
public static void main(String[] args) {
String blogName = "coderolls.com";
byte[] stringByteArray = blogName.getBytes();
byte[] reverseStringByteArray = new byte[stringByteArray.length] ;
String reversedString;
for(int i = 0; i<=stringByteArray.length-1; i++) {
reverseStringByteArray [i] = stringByteArray[stringByteArray.length-i-1];
}
reversedString = new String(reverseStringByteArray);
System.out.print("The reversed string of the '"+blogName+"' is: " );
System.out.println(reversedString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment