Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 18
Question ID: UKOCP20791
Consider below code of Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- StringBuilder sb = new StringBuilder(100);
- System.out.println(sb.length() + ":" + sb.toString().length());
- }
- }
What will be the result of compiling and executing Test class?
- A 100:100
- B 100:0
- C 16:16
- D 16:0
- E 0:0
Reveal correct answer
Correct answer: E
Explanation
UKOCP20791:
new StringBuilder(100); creates a StringBuilder instance, whose internal char array's length is 100 but length() method of StringBuilder object returns the number of characters stored in the internal array and in this case it is 0. So, sb.length() returns 0.
sb.toString() is the String representation of StringBuilder instance and in this case as there are no characters inside the StringBuilder object, hence sb.toString() returns an empty String "", so sb.toString().length() also returns 0.
Output is 0:0.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
