When I create a new object with StringBuffer/StringBuilder inside a constructor, it seems I need to create a temporary variable and pass this along to the initialized class variable. That is, when I create a new instance, the changes I make to sNumber (example below) in the constructor don't affect the object variable's value -- unless I use a temp variable. For example:
public class Some_class {
public static class algorithm{
String sNumber = "";
algorithm(String num){
String temp = new StringBuilder(num).reverse().toString();
sNumber = temp;
//the below expression does not work:
//sNumber = new StringBuilder(num).reverse().toString();
}
I assumed that since I named the new StringBuilder/StringBuffer object the same name, it would override the value of the previously initialized sNumber variable -- but that's not the case. Is there a proper way to do this?
I assumed that since I named the new StringBuilder/StringBuffer object the same name, it would override the value of the previously initialized sNumber variable
No, if you name the StringBuilder the same name as the field, it will hide the field. (The only way to access the field would then be through this.sNumber
.)
You can solve it without a temporary variable as follows:
sNumber = new StringBuilder(num).reverse().toString();
(You say in your question that this does not work, but it should. Just make sure you don't declare sNumber
as a local variable in the constructor. If it still doesn't work, you need to include the error message in your question.)