I want to reverse the string eithout using any temprory variables,String Buffer and arrays. I know that we can use charAt() method for reversing a string but how can u assigen the char value to string. Bcz for me the original string after any user defined method should contain exactly the revrese of the original one. Please Suggest me soln. Regrads Prasad
Java strings are immutable. They cannot be changed. You cannot reverse a string in place as you would be able to do with C String ore a Java StringBuffer. Immutable strings are good for security and the performance of substring(), however, you give up the ability to alter them.
"I want to reverse the string eithout using any temprory variables,String Buffer and arrays." Impossible. There is no way to do this without using some sort of temporary variable. Once you allow this, there are several possible ways - kawaii's second solution is the most efficient.
Also, Prasad - please change your display name to comply with our name policy. "CTS" does not look like it could possibly be a real last name - we ask that everyone use a real name (first and last) for their display name. You can fix this by going to "my profile" and then "Edit/View Profile". Thanks.
Prasad, As mentioned by other posters its not possible to reverse a string in java as strings are immutable. You need to either use StringBuffer or read your String in reverse order character at a time into an array and then create a "new" string object out of this array. Remember this is still a "new" object. Your code is not reversing a String.You'r just reading the characters in reverse order and printing them to console but your orginal String object is still unchanged. Kawaii has given code which should work correctly and solve your purpose Cheers Jayram
Effectively "changing" your original string to its own reverse.
But remember, Strings are immutable - you cannot change them. You can "point" a variable name to a new String. That is what has been done here. Here is a link to a discussion involving "immutable" with some good answers Good Luck, -Dirk Schreckmann [ February 14, 2002: Message edited by: Dirk Schreckmann ]