Java

How to reverse a string in Java

Reversing a string entails totally changing the sequence of the characters, or making the string read backward. In this article, we will teach you how you can reverse any string using a Java programming language. Two different examples will be discussed in this article for this purpose, in the first one we will take a predefined string and reverse it, and in the second one, we will take input from the user and then reverse it.

How to reverse a user-defined string in Java

First, we will create a class with the name ‘StringReverse’ in which all the other coding will take place by typing:

public class StringReverse {

………

}

After defining the main function, we have a user-defined string that needs to be reversed which is ‘abcde’ assigned to the variable ‘str’:

String str="abcde";

Next, we have defined another variable in which the reverse string output will be stored:

String strRev= "";

Use the below-mentioned code to print the original string on the screen in which ‘+’ is a concatenate operator used to add the string together:

System.out.println("Original string: "+str);

Now, this is the most important part of the code where we have used the for loop to reverse the string. Here str.length() is used to measure the total number of characters of the string as shown below:

for (int i = 0; i <str.length(); i++)

Next, we have initialized a new variable with character (char) data type that will save one character from the whole string in one iteration. After that the character will be stored in ‘StrRev’ variable that will be concatenated with the ‘c’ in each iteration as shown below:

char c=str.charAt(i);  

strRev=c+strRev;

So the whole body of the for loop will be like:

for (int i = 0; i <str.length(); i++) {

            char c=str.charAt(i);  

            strRev=c+strRev;        
   
}

In the end, we will display the final result by typing:

System.out.println("Reverse of the string: "+strRev);

Now the whole code to reverse of a string:

public class StringReverse {

    public static void main(String[] args) {

        //Example 1. using a hard-coded string

        String str="abcde";

        String strRev= "";  

        System.out.println("String Reverse Example 1:\n");

        System.out.println("Original string: "+str);
   
        for (int i = 0; i < str.length(); i++) {

            char c=str.charAt(i);  

            strRev=c+strRev;    

        }

        //Display the value of strRev

        System.out.println("Reverse of the string: "+strRev);

        System.out.println("");

    }    

}

One of the easiest ways to write java code in Linux is by using any text editor. For that, you need to open any text editor of your choice and then write and save a java code in it. In our case, we are using a nano text editor as shown below:

$ nano StringReverse.java

Note: You need to install the Java Development Kit (JDK) to execute the Java based programs in the Linux operating system. For that, you can open a terminal and type:

$ sudo apt install default-jdk

Now after writing and saving the code, you need to compile it first which is mandatory for its execution by typing.

$ javac StringReverse.java

$ java StringReverse

How to reverse a string by taking an input from the user in Java

In this example, we will take input from the user to type any string, and then we will reverse it and enable this function we need to import java.util.scanner library:

import java.util.Scanner;

Now for taking input from the user, we need to write a scanner function that will scan the keys that a user will press from the keyboard:

Scanner in=new Scanner(System.in);

After that, we need to ask the user to enter any string from the keyboard as an input function and for that, we need to write:

String str=in.nextLine();

This is the only part that is different from the previous example so the whole code to reverse the string is shown below.

import java.util.Scanner;

public class StringReverse {

    public static void main(String[] args) {

        System.out.println("String Reverse Example 2:\n");

        System.out.println("Please enter a word or sentence.");

        Scanner in=new Scanner(System.in);

        String str=in.nextLine();  

  String strRev= "";

        System.out.println("Original string: "+str);

        for (int i = 0; i < str.length(); i++) {

            char c=str.charAt(i);  

            strRev=c+strRev;  

        }

        System.out.println("Reverse of the string: "+strRev);

        System.out.println("");

    }    

}

Now it’s time to execute the above code and for that, you need to save it in the nano editor file as we did in the first example as shown below.

You can see the output of the code after compiling and executing as shown below:

Conclusion

If you have any string and you want to read it backward then you need to use the reverse function. In this article, we have shown you how you can reverse the string using a java programming language. We have explained two examples in which we have used a pre-defined text and then reversed the string and on the other hand, we have taken input from the user and later reversed it.

About the author

Taimoor Mohsin