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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With