Java Code to Reverse a String using toCharArray() & charAt()

There are many ways to reverse a string in Java. The following two programs show that how to reverse a string using java program.

In Program1, toCharArray() is used to convert the input string into character array, then the characters in the array are reversed using the for loop and converted to string using String() which is reverse string. Inputs are accepted using command line arguments.

In Program2, we are getting input using showInputDialog, then using charAt(), characters from the last are read and concatenated in a new string.

Program1:

package com.javaonline;
import java.io.*;
public class StrRev {
    
    /**
     * Converts a String to a character array
     */
    public void StrRev(String str) {

    	int len=str.length();
    	char[] revArray = new char[len];
        char[] cArray = str.toCharArray();
        int i=0;
		for (int l=len-1;l>=0; l--)
		{
		revArray[i] =cArray[l];
		i++;
		    }


		String reversestr = new String(revArray);
		System.out.println("Reverse of  " + str + " is " + reversestr);
}
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
                 			int length = args.length;
                                if (length <= 0) {
                                    System.out.println("Insufficent Argument. Format : java StrRev String.  eg. java StrRev CNN");
                                    System.exit(0);
                              }

                             new StrRev().StrRev(args[0]);
    	}
} 

Input : java StrRev National
Output : Reverse of National is lanoitaN

Program2:

package com.javaonline;
import java.io.*;
import javax.swing.JOptionPane;

public class StrReverse {
    
    /**
     * Converts a String to a character array
     */
 public void StrReverse() {
    String reverse="";
    String rev1="";
    String str = JOptionPane.showInputDialog("Enter any String: "); // Displays Input Dialog Box to enter String
    int len=str.length();
        int i=0;
		for (int l=len-1;l>=0; l--)
		{
		reverse=reverse+str.charAt(l);
		           // System.out.println(n);
		i++;
		    }


		String reversestr = new String(reverse);
		System.out.println("Reverse of  " + str + " is " + reversestr);
}
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new StrReverse().StrReverse();
    }
}

Run the Java Program

java StrReverse
Type the input in input dialog box
Output : Reverse of String is gnirtS

You may also like

Leave a Reply