简体   繁体   中英

Returning String builder from a String function in Java?

I have the following program where I have to append string to another string and I do it the standard way using String builder. However the function does not allow me to return ab even after I have converted it toString() . I would like to ask why is that?

 import java.util.*;

 public class prog1 {

        public static String k(int i) {
            String a = "1";
            StringBuilder ab = new StringBuilder();
            int pos = 1;
            if (i == 1) {
               return a;
            }
            else{
                pos++;
                String first = Integer.toString(pos);
                ab.append(a).insert(0,first);
                ab.toString();
                return ab;
            }
        }
        public static void main (String[]args){
                k(2);
            }
        }

You don't return the String returned by StringBuilder.toString() :

ab.toString();
return ab;

To get the result returned by ab.toString(); you have to assign it to a variable. Then you can return it :

String s = ab.toString();
return s;

Or in your case you can directly return the result as you don't need to manipulate/transform the returned String :

return ab.toString();       
ab.toString();
return ab;

The toString() method does not magically transform your StringBuilder into a String . It returns a String representation (which you don't use).

Change it to:

return ab.toString();

You should

return ab.toString();

instead of

return ab;

the function does not allow me to return ab even after I have converted it toString()

Calling ab.toString() doesn't convert ab from a StringBuilder to a String . It returns a new String instance, which you didn't assign to any variable, and therefore couldn't return.

the toString() method does return the String which is contained in the StringBuilder. It does not modify the content of the it.

return ab.toString();

to solve the issue.

First of all, your code will not compile. Because in the else bock you have returned a StringBuilder rather than a String. Now, try to understand how these values will be stored in memory, then you will find out your problem.

Whenever we initialize a variable a new reference will be created in memory. If we want to operate any String operation on any reference, a value of that reference will be copied and will create a new reference in memory and then String that operation will occur.

    public class Test {
    public static String k(int i) {
        String ab = "ab ";    // -----------------------------------------------  1
        StringBuilder stringBuilder = new StringBuilder("stringBuilder "); // --  2
        String c = ab.concat("c "); // -----------------------------------------  3
        ab.concat(stringBuilder.toString()); // --------------------------------  4
        String d = ab.concat(stringBuilder.toString());  // --------------------  5
        System.out.println("c : "+c);
        System.out.println("d : "+d);
        System.out.println("ab : "+ab);
        return ab;
    }

    public static void main(String[] args) {
        k(2);
    }
}

output :

c : ab c 
d : ab stringBuilder 
ab : ab

在此输入图像描述

In this example,

  1. Line 1, a String reference will be created and value of that reference is ab (type String).
    1. Line 2, a StringBuffer reference will be created and value of that reference is buffer (type StringBuffer).
    2. Line 3, a String reference will be created and value of that reference is ab c (type String). Value of ab reference will be copied and concat with String c. Value will be stored in new String reference in c.
    3. Line 4, a String reference will be created and value of that reference is ab buffer (type String). Value of ab reference will be copied and concat with reference to stringBuffer. But for this, no reference will not be created.
    4. Line 5, a String reference will be created and value of that reference is ab buffer (type String). Value of ab reference will be copied and concat with reference to stringBuffer. The value will be stored in new String reference in d.

For these reasons, the value of reference ab will be same as initialization because every time new reference will be created and will do it's String operation.

But in the case of StringBuilder, all operations will have occurred in the same reference. Another reference will not be created.

In your code, you can solve the problem, by storing the ab.toString() value in a new reference and returning that value. Another approach is return ab.toString()

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