Java Program to Reverse a String
So often Interviewer will ask you this question on how to reverse a String using Java. This has become one of the top favorite interview questions for the interviewers. If you are preparing for an interview and are under 5 years of experience, expect this question and be ready with your smart answer.
There are 2 ways to answer this question -
Program Explanation - We will be using StringBuilder class having reverse() function. Take the input from the user using Scanner class and use nextLine() function to get the input from the user. Create an object of StringBuilder class and pass the input into it. The last step is to use reverse() function in the string builder's object and convert the result into the string as shown above using toString() method.
Reverse a String using For loop -
Program Explanation - Take the user's input using Scanner Class and declare a variable having a null string as shown above. Loop will start from the length of the string until the last character to append the string's last character in reverse string.
There's one more concept which is often asked in the interview, to define the difference between StringBuilder and StringBuffer?
StringBuilder is more efficient than StringBuffer.
There are 2 ways to answer this question -
- Using a Reverse method (StringBuilder Class)
- Using for loop
We will be covering both the solutions, next time you are asked this question. Make sure you answer both the ways to have some confidence from the interviewer.
Reverse a String using Reverse Method(StringBuilder Class) -
Program Explanation - We will be using StringBuilder class having reverse() function. Take the input from the user using Scanner class and use nextLine() function to get the input from the user. Create an object of StringBuilder class and pass the input into it. The last step is to use reverse() function in the string builder's object and convert the result into the string as shown above using toString() method.
Reverse a String using For loop -
Program Explanation - Take the user's input using Scanner Class and declare a variable having a null string as shown above. Loop will start from the length of the string until the last character to append the string's last character in reverse string.
There's one more concept which is often asked in the interview, to define the difference between StringBuilder and StringBuffer?
StringBuilder is more efficient than StringBuffer.
Comments
Post a Comment