Java Program to reverse a string without using StringBuffer


In this program, You will learn how to reverse a string without using StringBuffer in java.


Enter a string: Welcome

After reverse string is: emocleW

Example: How to reverse a string without using StringBuffer in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        String str;
        char temp;
        int l = 0, i;

        System.out.print("Enter a string:");
        str = s.nextLine();
        char a[] = str.toCharArray();

        for (i = 0; i < a.length; i++) {
            l++;
        }

        i = 0;
        l = l - 1;
        while (i < l) {
            temp = a[i];
            a[i] = a[l];
            a[l] = temp;

            l--;
            i++;
        }

        str = String.valueOf(a);
        System.out.print("Reverse string:" + str);
    }
}

Output:

Enter a string:Xiith
Reverse string:htiiX