JAVA program to reverse a string without using inbuilt method reverse()

JAVA program to reverse a string without using string method reverse()

This JAVA program is to reverse a string without using string method reverse().

For example, reverse of string ‘codedost’ would be ‘tsodedoc’.

Logic

We start our for loop from the end of the string and keep printing each character till we reach the first character.

Dry Run of the Program

Take input string ‘s’.Let us take s=”code”

Convert string to charArray str[]

1st iteration for(i=n-1;i>=0;i–)  i.e.  for(i=4-1;i>=0;i–) i.e. for(i=3;3>=0;i–)

print str[i] i.e. str[3]  hence print e

2nd iteration for(i=n-1;i>=0;i–)  i.e.  for(i=3-1;i>=0;i–) i.e. for(i=2;2>=0;i–)

print str[i] i.e. str[2]  hence print d

3rd iteration for(i=n-1;i>=0;i–)  i.e.  for(i=2-1;i>=0;i–) i.e. for(i=1;1>=0;i–)

print str[i] i.e. str[1]  hence print o

4tht iteration for(i=n-1;i>=0;i–)  i.e.  for(i=1-1;i>=0;i–) i.e. for(i=0;0>=0;i–)

print str[i] i.e. str[0]  hence print c

So final output will be edoc which is the reverse of string code.

Program

import java.util.*;

class stringReverse
{
	public static void main(String args[])
	{
                int i,n;

		String s;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the string");
	 	s=sc.nextLine();
		char str[] = s.toCharArray();
    		n=str.length;
    		System.out.println("Reversed string is");
    		for(i=n-1;i>=0;i--)
    		{
       			System.out.print(str[i]);
    		}
	}    
}

Output

Share Me!