Javatpoint Logo
Javatpoint Logo

Reverse a string Using a Byte array in Java

In this section, we will discuss the how to reverse a string using a byte array in Java.

The following are the steps to reverse a string in Java using a byte array.

  1. The first step in this method is to generate a temporary byte[] with a length equal to the input string.
  2. Put the bytes (that we obtained using the getBytes() function) further into temporary byte[] in reverse order.
  3. Establish a new String subject and use the byte[] to store the outcome.

The concept is pretty straightforward; to put it simply, it involves breaking a string down into bytes and then rearranging the bytes in the array in real time. We then change the byte array back into something like a string.

File name: ReverseStringUsingByteArray.java

Output:

The string after reversing is  tniopTavaJ ot emocleW

File name: ReverseStringUsingByteArray1.java

Output:

tniopTavaJ ot emocleW

The given string will be divided up into bytes or converted using the getBytes() method. The specified string's length will be the same as the size of the temporary byte array. Take the bytes and place them in some other byte array in reverse order.

The string is temporarily handled by a byte array formed in the code below. The built-in method getBytes() can also be used to translate a string into bytes.

Two-byte arrays are constructed, one to hold the converted bytes and the other to hold the outcome in reverse order.

Program:

File Name: ReverseStringUsingByteArray2.java

Output:

The string after Reversing is: tniopTavaJ ot emocleW olleH

That was all that was required for reversing a String in Java using a Byte array.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA