简体   繁体   中英

java reference variable in void ref method

I am trying to figure out how to access the sb variable in the void ref method. Is it possible? This problem came up as I prepare for a test.

public class X{
  public void ref(String refStr, StringBuilder refSB){
    refStr = refStr + refSB.toString();
    refSB.append(refStr);
    refStr = null;
    refSB = null;
    //how can I access main variable sb here?  Not possible?
    //sb.append(str);
  }
  public static void main(String[] args){
    String s = "myString";
    StringBuilder sb = new StringBuilder("-myStringBuilder-");
    new X().ref(s, sb);
    System.out.println("s="+s+" sb="+sb);
  }
}

You're assigning a null to the reference value, this makes it point nowhere. When you pass a parameter, you're passing it by reference (memory pointer). Assigning a new value or null changes the reference, but not the memory object it points to.

So, you can work with the StringBuilder within the method and it will keep your changes outside the method, but you cannot assign something else to the pointer (because the pointer itself is local to the method).

For example:

public static void ref (StringBuilder refSB) {
  refSB.append("addedWithinRefMethod");  // This works, you're using the object passed by ref
  refSB = null;  // This will not work because you're changing the pointer, not the actual object
}

public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  ref(sb);
  System.out.println(sb.toString());  // Will print "addedWithinRefMethod".
}

To make the code do what you want, you need to use one more derreference, for example using an array:

public static void ref(StringBuilder[] refSB) {
  refSB[0] = null;  // This works, outside the method the value will still be null
}

public static void main(String[] args) {
  StringBuilder[] sb = new StringBuilder[] { new StringBuilder() };
  ref(sb);
  System.out.println(sb[0]);  // Will print "null"
}

However, keep in mind that side effects (a method that changes the objects defined outside it) is generally considered bad practice and avoided when possible.

Yes,it is possible to use sb reference in void ref() method.You are actually passing sb reference to ref() using new X().ref(s, sb); And in

 public void ref(String refStr, StringBuilder refSB){
    refStr = refStr + refSB.toString();
    refSB.append(refStr);
    refStr = null;

    //USe refSB variable here
    refSB.append(str);
  }

Don't do this refSB = null;.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM