Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

How to Reverse a String in Java

Last updated by Swaminathan Iyer on Sep 25, 2024 at 11:01 PM | Reading time: 8 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

How to Reverse a String in Java
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

Tech interviews are tough, especially if you’re gunning for FAANG and other tier-1 tech companies. Software engineers or developers are expected to be masters at data structures and algorithms. Moreover, depending on the role you’re applying for, you would also require expertise in specific programming languages such as Java or Python.

So while you are planning your prep, be sure to include the basics. In this article, we’re focussing on Java — specifically, how to reverse a string in Java. Here’s how we’ll cover it:

  • What is reversing a string?
  • Different methods for reversing a string in Java
  • Examples of tech interview questions on reversing a string in Java 
  • FAQs on reversing a string in Java 

What Is Reversing a String?

The string is basically a sequence of characters. In Java, a string is an object, and there are a number of operations we can perform on the string. As the name suggests, Reversing a string is nothing but flipping the given string — that is, the last letter becomes the first, the second-to-last letter becomes the second, and so on.

For example: 

Input String: “InterviewKickstart”

Reversed String: “tratskciKweivretnI”

Input String: “12345”

Reversed String: “54321”

Input String: “Hello098”

Reversed String: “890olleH”

Different Methods for Reversing a String in Java

There are many ways to implement this; we’ll cover the following methods: 

  1. Using CharAt methods.
  2. Using a reverse iterative approach.
  3. Using String Buffer approach.
  4. By converting the string into bytes
  5. Using an ArrayList object.  

Method 1: Using CharAt Method

ChatAt method is used to access the character in a string at a particular index.

We create an empty string object first and then append the characters in that string. To append the characters, we first iterate over the original string from its last position and access the character in it by CharAt method. And hence our new string, which was empty, will now contain the reversed string of initial. 

Code for the CharAt Method

import java.util.*;

public class ReverseString {

    public static void main(String args[]) {

        // s1 will contain the initial string and rev will contain the string after reversing it. 

        String s1 = "InterviewKickstart", rev = "";

        System.out.println("Initial String: " + s1);

        int n = s1.length();

        // iterating over the original string from right. 

        for (int i = n - 1; i >= 0; i--)

            rev = rev + s1.charAt(i); // using CharAt() method to access   character at particular index.            

        // printing the result    

        System.out.println("Reversed string: " + rev);

    }

}

Time Complexity: O(n) 

Space Complexity: O(n) 

Method 2: Using a Reverse Iterative Approach

In this approach, we use the toCharArray method of string to convert it into a character array first. After converting the given string into a character array we just iterate the array from the last position and append the characters into an empty string similar to what we have done in method 1. 

Code for the Reverse Iterative Approach:

import java.util.*;

public class ReverseString {

    public static void main(String args[]) {

        // s1 will contain the initial string and rev will contain the string after reversing it. 

        String s1 = "InterviewKickstart", rev = "";

        System.out.println("Initial String: " + s1);

        int n = s1.length();

         // converting string into character array 

        char c[] = s1.toCharArray();

        // iterating over the array from right. 

        for (int i = n - 1; i >= 0; i--)

            rev = rev + c[i]; 

        // printing the result    

        System.out.println("Reversed string: " + rev);

    }

}

Time Complexity: O(n)

Space Complexity: O(n)

Method 3: Using the String Buffer Class Approach

In string buffer class, we have a built-in reverse() method, which can be used to reverse the string. This method takes in a string object as a parameter and returns the reversed string. We will use this in-built method in this approach to reverse the string. 

Code for the String Buffer Class Approach

import java.util.*;

public class ReverseString {

    // This Function reverses the string in Java using StringBuilder

    public static String rev(String s) {

       // We are passing the string 's' in the constructor of StringBuilder to create a new object of StringBuilder Class. The string 's' will remain unchanged. toString() will return the object of the string class.    

        return new StringBuilder(s).reverse().toString();

    }

    public static void main(String args[]) {

        // s1 will contain the initial string.

        String s1 = "InterviewKickstart";

        System.out.println("Initial String: " + s1);

        // reversing the string using StringBuilder class 

        s1 = rev(s1);

        // printing the result    

        System.out.println("Reversed string: " + s1);

    }

}


Time Complexity: O(n) 

Space Complexity: O(1) 

Method 4: By Converting the String Into Bytes

getBytes() method of String is used to convert the string into bytes, and we will use this method to reverse the string. First, we’ll create a temporary byte array whose length will be equal to the length of the string, and then we’ll store the string in byte form in a reverse manner in that byte array. Now, we again convert it into the string and simply print it. 

Code for the Converting to Bytes Method

import java.util.*;

public class ReverseString {

    public static void main(String args[]) {

        // s1 will contain the initial string.

        String s1 = "InterviewKickstart";

        System.out.println("Initial String: " + s1); 

        byte[] tp = s1.getBytes();// converting string into bytes by using getBytes() method

        // storing result in reverse order

        for (int i = 0; i < tp.length / 2; i++) {

           byte temp = tp[i];

           tp[i] = tp[tp.length - i - 1];

           tp[tp.length - i - 1] = temp;   

       }   

        // printing result by converting it into string. 

        System.out.println("Reversed string: " + new String(tp));

    }

}

Time Complexity: O(n)

Space Complexity: O(n) 

Method 5: Using an ArrayList Object 

Collection class in Java has a built-in reverse() method to reverse the object. In this method, we use the reverse() method and ArrayList object of Java to reverse the string. First, we add each of the string characters into the ArrayList object. We’ll pass this ArrayList object to the reverse() method to get it reversed. Then we iterate over the ArrayList and push all characters in StringBuilder. And then, by using the toString() method, we get our reversed string.   

Code for the ArrayList Object Approach

import java.util.*;

import java.util.Arrays;

import java.util.List;

public class ReverseString {

    public static void main(String args[]) {

        // s1 will contain the initial string.

        String s1 = "InterviewKickstart";

        System.out.println("Initial String: " + s1);    

        List<Character> a = new ArrayList<>(); // creating array list object       

        // adding characters into array list object

        for (char c : s1.toCharArray()){ 

                 a.add(c); 

        }

        Collections.reverse(a); // using inbuilt reverse method to reverse the list.  

        // convert in string

        String res = “”;

        // appending characters to the result string.

        (Character c : a) {

              res += c;

         }

        // printing result.

        System.out.print("Reversed string: ");

        // printing the string

        System.out.println(res);   

    }

}

Time Complexity: O(n)

Space Complexity: O(n) 

Examples of Tech Interview Questions on Reversing a String in Java 

Here are a few examples of the types of questions you can expect at tech interviews at FAANG and other tech companies,

  1. Write a recursive function in java to reverse a string. 
  2. What are the possible ways to reverse the string in java? 
  3. What are the classes related to string in Java? 
  4. Define your own method to reverse the string in Java.
  5. What is the difference between the String and StringBuffer classes in Java? 
For more tech interview questions and problems, check out the following pages: Interview Questions, Problems, Learn.

FAQs on Reversing a String in Java 

Question 1: What is StringBuilder in Java, and how is it different from String class?

Answer: StringBuilder is a class in Java. It represents a mutable sequence of characters. This class is similar to the String, but it is one of the alternatives to the String class. However, StringBuilder is faster than String. equals() method can be used to compare two Strings in Java. StringBuilder does not override the equals() So, this method can not compare two StringBuilder objects. 

A new StringBuilder object cannot be created without using a new operator, while a String object can be. Length of the String object is fixed, while StringBuilder has a method setLength(), which can be used to change the length of its object. 

Question 2: Why is the string immutable in Java?

Answer: Immutable string means we can not change the state of the object, but we can change the reference to the object. It simply means strings are unmodified. In Java, string objects are cached in the string pool, making strings immutable because we can’t directly change the objects. For example, when we use the += operator to append the string, it will create a new object each time because strings are immutable, and once they are created, they can’t be changed.

Ready to Nail Your Next Coding Interview?

If you’re looking for guidance and help with getting your prep started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

----------

Article contributed Omkar Deshmukh

Last updated on: 
October 10, 2024
Author

Swaminathan Iyer

Product @ Interview Kickstart | Ex Media.net | Business Management - XLRI Jamshedpur. Loves building things and burning pizzas!

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

How to Reverse a String in Java

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image