java

How to Reverse a String in Java in 2 different ways

In this tutorial, we are going to see different ways to reverse a String in Java.
 

Method 1: Using the reverse() method of the StringBuilder class

The String class does not have the reverse() method, we need to convert the input string to StringBuilder, for that we will use the append method of StringBuilder. Then, display the reversed String.

import java.lang.*; 
import java.util.*;
import java.io.*; 
 
public class Main 
{ 
    public static void main(String[] args) 
    { 
        String str = "StackHowTo"; 
  
        StringBuilder sb = new StringBuilder(); 
  
        // add the string in StringBuilder
        sb.append(str); 
  
        sb = sb.reverse(); 
  
        // display the reversed String
        System.out.println(sb); 
    } 
}

Output:

oTwoHkcatS

 

 

Method 2: Using for loop

In the example below, we’ve used a loop that will build the new reversed string. This is done in the “for” loop by retrieving the characters from the original string using the “charAt” function of the String class and concatenating them into a new string using the “+” operator.

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        String str = "StackHowTo"; 
        String newStr = "";
        
        for(int i = str.length() - 1; i >= 0; i--)
        {
            newStr = newStr + str.charAt(i);
        }
        System.out.println(newStr);
    }
}

Output:

oTwoHkcatS
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *