Reverse A String in Java Using ByteArray

Programming is always a fun and creative task. The more creative you can think the better programmer you will become. However, programming isn’t always about solving problems sometimes there’s also a fun aspect to it which makes it way more satisfying. If you are a programmer then you might have already played with patterns, strings, etc multiple times. Well, it’s also like that you are already familiar with strings, but what about reversing a string. So in today’s article, we will Reverse a string in Java. With the help of this program, you will be able to read a string in reverse direction. Practicing these types of questions also helps getting a upper edge in Competitive Programming.

 

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat hard question you might get asked in an interview so make sure to practice it on your own after reading this article.

 

Also Read: Print Pascal Triangle in Java

 

What’s The Approach?

 

  • We will create a temporary array of type byte “byte[]” with length equal to the string which we are going to reverse.

 

  • In our temporary created byte array we will Store bytes of the input string in a reverse order.

 

  • We will create a new string and using the byte array. Eventually creating a string we have given as input in a reverse order.

Java Program To Reverse A String

 

Input: TechDecodeTutorials

How To Reverse an Array in Python

Output: slairotuTedoceDhceT

 

// Java program to ReverseString using ByteArray.
import java.lang.*;
import java.io.*;
import java.util.*;

// Class of ReverseString
class TechDecodeTutorials {
    public static void main(String[] args)
    {
        String input = "TechDecodeTutorials";

        // getBytes() method to convert string
        // into bytes[].
        byte[] strAsByteArray = input.getBytes();

        byte[] result = new byte[strAsByteArray.length];

        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i < strAsByteArray.length; i++)
            result[i] = strAsByteArray[strAsByteArray.length - i - 1];

        System.out.println(new String(result));
    }
}

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.