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?
String sNumber = new StringBuilder(num).reverse().toString();?String sNumber = new StringBuilder(num).reverse().toString();and couldn't figure out why it doesn't work. When I came here, I wrote it the correct way and thought it was wrong.