String reverse program in java

In Java, you can reverse a string in several ways. Here are three common methods to reverse a string:

String reverse program in java using StringBuilder

This program uses the StringBuilder class, which is a mutable sequence of characters. Here’s how it works:

  1. We start with the original string "Hello, World!".
  2. We create a StringBuilder object called reversed and initialize it with the original string using new StringBuilder(original).
  3. We use the reverse() method of the StringBuilder class to reverse the characters in the reversed object.
  4. Finally, we convert the StringBuilder back to a regular string toString() and store it in the reversedString variable. Then, we print the reversed string.

Using a loop to reverse the string character by character:

In this program, we reverse the string by iterating through its characters using a loop:

  1. We start with the original string "Hello, World!".
  2. We define a method reverseString that takes a string str as input.
  3. Inside the reverseString method, we create a StringBuilder call reversed to build the reversed string.
  4. We use a for loop to iterate through the characters of the input string from the end (length – 1) to the beginning (0).
  5. In each iteration, we append the character at the current position to the reversed StringBuilder.
  6. Finally, we convert the StringBuilder to a regular string using toString() and return the reversed string.

String reverse program in java Using recursion

This program uses a recursive approach to reverse the string:

  1. We start with the original string "Hello, World!".
  2. We define a method reverseString that takes a string str as input.
  3. Inside the reverseString method, we have a base case that checks if the input string is empty. If it’s empty, we return the same empty string.
  4. In the recursive case, we call reverseString with a substring of the input string str.substring(1), effectively removing the first character, and then we concatenate the first character str.charAt(0) to the reversed result.
  5. This process continues recursively until the base case is reached, and the characters are concatenated in reverse order.

These are three different approaches to reversing a string in Java, each with its own advantages and use cases.

The first method using StringBuilder is the most efficient and commonly used for reversing strings.

The second method using a loop is also straightforward and efficient. The third method using recursion is less efficient due to the overhead of recursive function calls but can be useful in certain situations or for educational purposes.

String reverse programs in Java can be done in the above three ways. Hope you learned all things.

Read More

If else nested and ladder if else statement in Java

Registration Form in Java | Student registration form using Java Swing source code

Java program to swap two numbers