Home Java Beginners Reverse String Program in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Reverse String Program in Java

Advertisement
We are going to describe about reverse string program in java. In this example reverses a string entered by the user.

Reverse String Program in Java

We are going to describe about reverse string program in java. In this example reverses a string entered by the user. We have used charAt() method to extract characters from the string. we use for java.util.Scanner Class and it has call the hasNextLine() method. This method return a string on a separate line. We have use for loop statement has type loop control statement.

We first initialize the variable. After that check the condition, if true than it will execute further. If it is false, it will terminate loop. We initialize condition and the increment is same written in the for term.

Syntax of for loop:-

for( initialization; termination; increment)
{
statements;
}

Example

package Stringreverse;
import java.util.Scanner;

public class StringReverse {
	  public static void main(String args[])
	   {
	      String string, reverse = "";
	      Scanner in = new Scanner(System.in);
	 
	      System.out.println("Enter a String ");
	      string = in.nextLine();
	 
	      int length = string.length();
	 
	      for ( int i = length - 1 ; i >= 0 ; i-- )
	         reverse = reverse + string.charAt(i);
	 
	      System.out.println("Reverse of entered string is: "+reverse);
	   }
	}

Above example code takes the user input from console and then reverses the string and prints the output on console.

Output- Here is the output of the program:

Enter a String
Roseindia technology
Reverse of entered string is:  ygolonhcet aidniesoR

Download source code

More tutorials on String handling in Java:

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 20, 2013

Ask Questions?    Discuss: Reverse String Program in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com