How to reverse a string without using default function in Java?

Learn how to reverse a string using pre-defined function and not using pre-defined function from this post. This will be useful when you are going for an Interview, most of the time interviewer ask us this kind of questions only!

With Pre-Defined Function ie., using StringBuffer() and reverse():

[code lang=”java”]

public class ReverseTest {

public static void main(String args[])
{
String mystring = “”;
mystring = “spiderman”;
StringBuffer buff = new StringBuffer(mystring);
System.out.println(buff.reverse());
}
}

Output: namredips


Without Pre-Defined Function ie., without using StringBuffer() and reverse():

[code lang=”java”]

public class Reverse {

public static void main(String args[])
{
String mystring, reverse = “”;
mystring = “spiderman”;
//find out the length of the string first
int length = mystring.length();
// loop through it using for loop
for ( int i = length – 1 ; i >= 0 ; i– ){
reverse = reverse + mystring.charAt(i);
}
System.out.println(“Reverse of the string is: “+reverse);
}
}

Output: Reverse of the string is : namredips

6 thoughts on “How to reverse a string without using default function in Java?

  1. Hi can any one tell me how to reverese a string with out using reverse and as well as length

Leave a Reply

Theme: Overlay by Kaira
Agurchand