1

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?

3
  • 6
    The code you've commented out will work absolutely fine. Please show a short but complete program demonstrating the problem - I strongly suspect that in trying to do so, you'll find that either it's no longer a problem (e.g. you misdiagnosed it before) or that you find the problem elsewhere. Commented Dec 23, 2014 at 23:39
  • 1
    Did you by any chance really say String sNumber = new StringBuilder(num).reverse().toString();? Commented Dec 23, 2014 at 23:45
  • You guys are all correct, particularly @ajb. In my workspace, I wrote 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. Commented Dec 24, 2014 at 6:20

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.