Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
            }
        }
like image 929
A.Petrov Avatar asked Apr 13 '26 14:04

A.Petrov


1 Answers

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();       
like image 165
davidxxx Avatar answered Apr 15 '26 02:04

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!