×

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the sequence of the characters, or in other words, reading a text backwards.

Reverse a String in Java

Program for  string reverse

//stringReverse.java — file name
import java.io.*;
import java.util.Scanner;
class rev {
    public static void main (String[] args) {
        String s= "what is your name", sb="";
        char c;
      System.out.print("Original string: ");
      System.out.println("what is your name"); //sample string       
      for (int i=0; i<s.length(); i++)
      {
        c= s.charAt(i); 
        sb= c+sb; 
      }
      System.out.print("Reversed word: "+ sb);
    }
}

Output

Reverse a String in Java

Explanation

In the above program, “what is your name” is the input string. Using for loop to iterate through the string, traverse through each character, and add it to the output string variable sb.

Different ways of reversing a string are as follow

  1. Using StringBuilder
  2. Using StringBuffer
  3. By Reverse Iteration
  4. String to Bytes
  5. String to a character array.

Generally, the String class doesn’t contain reverse() methods. Other techniques are used to reverse a string.

1)By StringBuilder

   StringBuilder is a Java class used to construct a mutable, or changeable, sequence of characters. The Java Strings class offers an immutable string of characters; similarly, to StringBuffer, the StringBuilder class offers an alternative.

Program to reverse a string using StringBuilder

import java. lang.*;
import java.io.*;
import java.util.*;
class reversestr {
    public static void main(String[] args)
    {
        String s = "welcome to the string reverse program";
        StringBuilder sb = new StringBuilder();
        sb.append(s);`
        sb.reverse();
        System.out.println(sb);
    } //main
}//Main

Output

Reverse a String in Java

2)StringBuffer

The string class does not have a reverse method inbuilt. We have to use StringBuffer to use the reverse method. A string buffer always contains a specific character sequence, but by calling specific methods, the length and content of the sequence can be altered. The use of string buffers by many threads is secure.

Example 1. Program to reverse a string using StringBuffer

public class rev {  
public static String reverseString(String str){  
    StringBuilder sb=new StringBuilder(str);  
    sb.reverse();  
    return sb.toString();  
}  
}
public class TestRev {  
public static void main(String[] args) {  
    System.out.println(rev.reverseString("welcome to the string reverse"));     
    }  
}

Output

Reverse a String in Java

Example 2. Program to reverse a string using StringBuffer

//second example
import java.lang.*;
import java.io.*;
import java.util.*;
 
public class Test {
    public static void main(String[] args)
    {
        String s = "hello";
        StringBuffer sb = new StringBuffer(s);
        sb.reverse();
        System.out.println(sb);
    }
}

Output

Reverse a String in Java

3)By Reverse Iteration

Given a string to reverse. Create an empty string variable. Use a for loop to get the characters of the string you wish to reverse in reverse order. Within the for loop, append each character to the name you've given as an empty string. Print the outcome.

Program to reverse a string using Iteration

//reverseString.java — file name
import java.io.*;
import java.util.*;
class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner (System.in);
        System.out.println("Enter the string to be reversed:");
        String s = sc.nextLine();
        char[] a = s.toCharArray();       
        String reverse = "";
 for(int i = s.length() - 1; i >= 0; i--)
 {
 reverse = reverse + s.charAt(i);
 }
 System.out.println("The reversed string is:");
 System.out.print(reverse);
    }
}

Output

Reverse a String in Java

4)Converting String into Bytes

Make a temporary byte[] that is the same size as the input string. Put the bytes into the temporary byte[] in reverse order. To store the result, create a new String object with byte[].

Program to reverse a string using Bytes function

import java. lang.*;
import java.io.*;
import java.util.*;
class Main {
    public static void main(String[] args)
    {
        String s = "hi there";
        byte[] sb = s.getBytes();
        byte[] r = new byte[sb.length];
        for (int i = 0; i < sb.length; i++)
{
            r[i] = sb[sb.length - i - 1];
}
     System.out.println("Original string is :"+s);
      System.out.println("Reversed string is:");
        System.out.println(new String(r));
    }
}

Output

Reverse a String in Java

5)Converting String to a character array

This string is converted to a character array in Java using the toCharArray() function. It produces a newly formed character array with the same length as this string and the same contents as this string.

Program to reverse a string using toCharArray function

import java.lang.*;
import java.io.*;
import java.util.*;
class reverseString {
    public static void main(String[] s)
    {
        String r = "hello everyone, good to see you";
        char[] t = r.toCharArray();
        for (int i = t.length - 1; i >= 0; i--)
            System.out.print(t[i]);
    }
}

Output

Reverse a String in Java

Related Topics

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.