×

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

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

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.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Java Math sin() Method

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

1 minute read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.