Different ways to reverse a string in java program

There are multiple ways to reverse a string in java progarm


1. Using for loop:

import java.util.Scanner;

public class JavaReverseString{

     public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter the string to reverse: ");
        String str = sc.nextLine();
        System.out.println("String after reverse: ");
        for (int i = str.length()-1; i >=0; i--) {
           System.out.print(str.charAt(i));
        }
     }
}

2. Using StringBuffer


import java.util.Scanner;

public class JavaReverseString{
     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the string to reverse: ");
        String str = sc.nextLine();
        String reverse = new StringBuffer(str).reverse().toString();
        System.out.println("String after reverse:" + reverse);
     }
}

3. Using char[ ]

import java.util.Scanner;

public class JavaReverseString {
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter the string to reverse: ");
         String str = sc.nextLine();
         int len = str.length();
         char[] tempCharArray = new char[len];
         char[] charArray = new char[len];

         for (int i = 0; i < len; i++) {
             tempCharArray[i] = str.charAt(i);
         }

         for (int j = 0; j < len; j++) {
             charArray[j] = tempCharArray[len - 1 - j];
         }

         String reverseString = new String(charArray);
         System.out.println("String after reverse: "+reverseString);
     }
}

4. Using recursion

import java.util.Scanner;

public class JavaReverseString {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the string to reverse: ");
       String str = sc.nextLine();
       System.out.println("String after reverse: "+reverseMyString(str));
    }

    public static String reverseMyString(String str) {
       if ((null == str) || (str.length() <= 1)) {
            return str;
       }
     return reverseMyString(str.substring(1)) + str.charAt(0);
    }
}

Comments

Popular posts from this blog

Number Pattern programs in java

String Related programs in java