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():


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():


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 Comments

Add a Comment

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