Return to site

☕🎓JAVA CERTIFICATION QUESTION: StringBuilder capacity

· java,ocp

What is the output?

* 8

20

 

* 0

20

 

* 0

18

 

* 0

12

#java #certificationquestion #ocp

https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

 

Answer:

The output is:

0

18

public int length()

Returns the length (character count).

public int capacity()

Returns the current capacity. The capacity is the number of characters that can be stored (including already written characters), beyond which an allocation will occur.

If the current capacity is less than expected, then a new internal array is allocated with greater capacity.

The new capacity is the larger of:

- The current argument.

- Twice the old capacity, plus 2.

Here the current capacity is 8.

The value "I love Java!" requires 12.

So the new capacity is 8*2 + 2 say 18.