How to Reverse a String in Java

Jul 4, 2024

How to Reverse a String in Java

Introduction

  • Welcome message and overview of the topic.
  • Understanding how to reverse a string using Java.
  • Discussion of 4 different ways to reverse a string.

Methods for Reversing a String

1. Using the toCharArray() Method

  • Converts string to a character array.
  • Example: String "HELLO" becomes ['H', 'E', 'L', 'L', 'O'].
  • Need to read characters from last index (length-1) to first (0).

Example Code

String str = "HELLO";
char[] charArray = str.toCharArray();
for (int i = charArray.length - 1; i >= 0; i--) {
    System.out.print(charArray[i]);
}
  • Output: OLLEH

2. Using the charAt() Method

  • Directly access each character using the charAt() method of String class.
  • Loop through the string from the end to the beginning.

Example Code

String str = "HELLO";
for (int i = str.length() - 1; i >= 0; i--) {
    System.out.print(str.charAt(i));
}
  • Output: OLLEH

3. Using the reverse() Method of StringBuffer Class

  • Create a StringBuffer object and call its reverse() method.

Example Code

StringBuffer sb = new StringBuffer("HELLO");
System.out.println(sb.reverse());
  • Output: OLLEH

4. Using the reverse() Method of StringBuilder Class

  • Similar to StringBuffer, but using StringBuilder.

Example Code

StringBuilder sb = new StringBuilder("HELLO");
System.out.println(sb.reverse());
  • Output: OLLEH

Interview Tips

  • Some interviews may require you to reverse a string without using the reverse() method.
  • In such cases, use Approach 1 (toCharArray()) or Approach 2 (charAt()).

Conclusion

  • Four approaches to reversing a string in Java discussed.
  • Tips for what to do in an interview setting.
  • Thank you message.