What will be the output of the following Java code snippet that calculates the…

2023

What will be the output of the following Java code snippet that calculates the length of a string without using the built-in length() method?

image.png

  1. A.

    The length of the string "Hello, World!" is: 13

  2. B.

    The length of the string "Hello, World!" is: 12

  3. C.

    Compilation Error

  4. D.

    Runtime Error: String cannot be null

  5. E.

    The length of the string "Hello, World!" is: 14

Attempted by 4 students.

Show answer & explanation

Correct answer: A

Concept

A string's length is simply the total number of characters it contains — every letter, digit, space, and punctuation mark counts as exactly one character. An enhanced for-loop over str.toCharArray() visits each character once, so incrementing a counter inside the loop body produces that exact total. No characters are skipped and none are added.

Applying it to this code

The program calls customStringLength("Hello, World!"). The argument is a non-null literal, so the null guard does not fire and no exception is thrown. The loop then counts every character in turn:

  1. Letters of “Hello”: H, e, l, l, o → 5 characters.

  2. Punctuation and space: ',' (comma) and ' ' (space) → 2 more characters, running total 7.

  3. Letters of “World”: W, o, r, l, d → 5 more, running total 12.

  4. Closing punctuation: '!' → 1 more, final total 13.

So customStringLength returns 13, and the println builds the message by concatenating the literal text with this value, printing: The length of the string "Hello, World!" is: 13.

Cross-check

Counting directly by index confirms it: positions 1–13 map to H(1) e(2) l(3) l(4) o(5) ,(6) [space](7) W(8) o(9) r(10) l(11) d(12) !(13). The two halves “Hello” and “World” contribute 5 each (10), and the comma, space, and exclamation mark add 3 more, giving 13. Java's built-in "Hello, World!".length() would return the same value, which is exactly what this hand-rolled loop reproduces.

Explore the full course: Ibps So It Mains

Loading lesson…