ArhamTechMind

Building future while learning

Reverse a String in java

1 min read
1.//Program to write  reverse a string

public class Reverse {
public static void main(String[] args) {

String s=”abcd”;
String rs=””;
for (int i=s.length()-1;i>=0;i–){
rs=rs+s.charAt(i);
}
System.out.println(s);
System.out.println(rs);
}
}

OutPut :

abc
cba

2. Using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString()

public class StringReverseExample{

   public static void main(String[] args){

      String string=”abcdef”;

      String reverse = new StringBuffer(string).

      reverse().toString();

      System.out.println(“nString before reverse:

      “+string);

      System.out.println(“String after reverse:

      “+reverse);

   }

}

3. Another  

public class Reverse {

public String reverseString(String s){

if (s.length()<=1){

return s;

}

else 

{

char c=s.charAt(0);

return reverseString(s.substring(1))+c;

}

}

}

class StringReverse{

public static void main(String[] args){

Reverse r=new Reverse();

String s1=”abcde”;

System.out.println(“Given String=”+ (s1));

System.out.println(“Reverse String=”+ r.reverseString(s1));

}

}

Output:

Given String=abcde

Reverse String=edcba

4. String Input from Keyword 

import java.util.Scanner;

public class A {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print(“Enter the String : “);

String value=sc.nextLine();

int len = value.length();

char[] ch = new char[len];

for(int i = 0;i<len;i++)

{

ch[i]= value.charAt(len-1-i);

}

String result = new String (ch);

System.out.println(result);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *