Let us see the java program to reverse the string.
What is Reverse the string?
Content.
- What is Reverse the String.
- Logic for program.
- Program.
- Explanation.
- Output.
Revering string means the order of the string changes, it displays the string from backward.
Example:
our Input: name
Output: eman
Logic for the Program.
- We need to display the last string first.
- So, when we use that in a loop, to get the Reversed string.
Program
import java.io.*;
class exrev
{
public static void main(String args[]) throws IOException
{
String A, B="";
int x,y;
char c;
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter the string");
A=in.readLine();
x=A.length();
for(y=0;y<x;y++)
{
c=(A.charAt(y));
B=c+B;
}
System.out.println("Given string=" +A);
System.out.println("Reveresed string=" +B);
}
}
Explanation.
- We have given the class name has exrev.
- public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
- String A,B, int x,y, char c is declaring the variable, s is declared to store 0.
- InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
- BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
- Now, we have to give condition which satisfies all the above int the logic for the program. I choose, for loop with y=0,y<x,y++ as condition.
- A is the string we give, B is reversed string.
- System.out.println is used to display the given in output screen(make sure S in System is capital)
Know more about for loop here.
Output:
Compile : javac exrev.java
Run : java exrev
Enter the string
computer science
Given string: computer science
Reversed string: ecneics retupmoc
Compile : javac exrev.java
Run : java exrev
Enter the string
computer science
Given string: java
Reversed string: avaj
known how to execute java program here.
Comments
Post a Comment