Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 66
Question ID: UKOCP20799
Consider below code of Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- StringBuilder sb = new StringBuilder(20); //Line n1
- sb.append("A".repeat(25)); //Line n2
- System.out.println(sb.toString().length()); //Line n3
- sb.setLength(10); //Line n4
- System.out.println(sb.toString().length()); //Line n5
- }
- }
What will be the result of compiling and executing Test class?
-
A
20
20
-
B
25
10
-
C
20
10
-
D
25
25
-
E
10
10
Reveal correct answer
Correct answer: B
Explanation
UKOCP20799:
new StringBuilder(20); creates a StringBuilder instance, whose capacity (internal char array's length) is 20. This initial capacity is not fixed and changes on adding / removing characters to the StringBuilder object.
Instance method 'repeat()' has been added to String class in Java 11 and it has the signature: public String repeat(int count) {}
It returns the new String object whose value is the concatenation of this String repeated 'count' times. For example,
"A".repeat(3); returns "AAA".
Line n2 successfully appends 25 A's to the StringBuilder object.
Line n3 prints 25 on to the console.
At Line n4, sb.setLength(10); sets the length of StringBuilder object referred by 'sb' to 10 (it is reducing the length of StringBuilder object from 25 to 10), hence 'sb' refers to StringBuilder object containing 10 A's (last 15 A's are gone).
Line n5 prints 10 on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
