I am trying to create a StringBuilder object with a given length, but every time I try to do so, the length of the StringBuilder object is printed as 0. Anyone know why?
String s = "i";
StringBuilder sb = new StringBuilder(s.length()+1);
System.out.println(sb.length());
In the above code, the length of the StringBuilder object should be 2 (1 from the length of "i" + 1), but when I print the StringBuilder's length in Eclipse, I get 0. I changed the length to 17 and 100, but I still got 0 as sb
's length.
You're not setting its length in that constructor, you're setting its capacity.
Its length is the number of chars
actually in it and you haven't yet appended any characters to it.