Reversing a string – Java

This is a program which accepts a string which is to be entered in by the user. It will then convert it and print out the outcome.


public class ReversingString
{
    public static String reverse ( String s )
    {
        int length = s.length(), last = length - 1;
        char[] chars = s.toCharArray();

        for ( int i = 0; i < length/2; i++ )
        {
            char c = chars[i];
            chars[i] = chars[last - i];
            chars[last - i] = c;
        }//for
        return new String(chars);
    }//reverse

    public static void main(String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
        String input;

        input = keyboard.nextLine();

        reverse(input);

        System.out.println(reverse(input));


    }//main

}//class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s