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
More tutorials on String handling in Java: