StringBuffer
Notes state "If the minimum capacity argument is non positive this method takes
no action and simply returns."
I've tried this and I observe the following
If I enter StringBuffer sba = new StringBuffer(-5); it compiles fine but i get a runtime error.
Exception in thread "main" java.lang.NegativeArraySizeException
at java.lang.AbstractStringBuilder.<init>(Unknown Source)
at java.lang.StringBuilder.<init>(Unknown Source)
at InitClass3.main(InitClass3.java:54)
I'm using java 1.7.0_17
If I create a StringBuilder string with initial capacity of zero, there is no runtime error.
I've just added this in with other code but the error message is clear where the issue is.
As the question asked "at least 100" (minimum), how "StringBuilder sb = new StringBuilder(100);" is correct?
Doesn't A option specified certain number of characters? or it defined the minimum number of characters and it could be more during coding?
I just assumed as the question asked "at least 100" (minimum) which means capacity 100 character is minimum and the variable could have more than 100 characters, but "StringBuilder sb = new StringBuilder(100);" has exact capacity not more.
Am I wrong?
If you create a StringBuffer with some capacity (or even without specifying capacity), it will always be created with a certain capacity.
Creating a StringBuffer with 100 doesn't mean it can store only 100 characters. It can store more if required. But initial capacity is 100, which satisfies the requirement given in the question.
StringBuilder sb = new StringBuilder();
System.out.println("new StringBuilder().capacity() = " + sb.capacity());
//capacity of new StringBuilder() is 16
sb.ensureCapacity(30);
// if current (currentCapacity*2+2)> argumetn of ensureCapacity()
// result will be (currentCapacity*2+2)
System.out.println(sb.capacity());
sb = new StringBuilder();
sb.ensureCapacity(34);
System.out.println(sb.capacity());
sb = new StringBuilder();
sb.ensureCapacity(35);
System.out.println(sb.capacity());
// if current (currentCapacity*2+2)< argumetn of ensureCapacity()
// result will be argumetn of ensureCapacity()
Observe that the question says "at least 100 characters". In the exam, you may get a question that says "100 characters", in that case, ensureCapacity() may not be a valid option.
Why would ensureCapacity() is not a valid option when question says "100 characters"?