arrow
arrow
arrow
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?
Question



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?

A.

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

B.

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

C.

Compilation Error

D.

Runtime Error: String cannot be null

E.

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

Correct option is A

The correct output of the code is "The length of the string 'Hello, World!' is: 13".
· The method customStringLength() iterates through each character of the string using a for-each loop and increments a counter (length) for every character.
· The input string "Hello, World!" has 13 characters, including the comma , and the space between Hello and World.
· The if (str == null) condition ensures the method throws an exception if the input string is null.
Important Key Points:
1. Manual String Length Calculation: The method counts characters using a loop, avoiding the built-in length() method.
2. Handling Null Input: The method validates the input string and throws an exception for null values, preventing runtime errors.
3. String Details: "Hello, World!" includes 13 characters:

test-prime-package

Access ‘IBPS SO IT Officer’ Mock Tests with

  • 60000+ Mocks and Previous Year Papers
  • Unlimited Re-Attempts
  • Personalised Report Card
  • 500% Refund on Final Selection
  • Largest Community
students-icon
171k+ students have already unlocked exclusive benefits with Test Prime!

Free Tests

Free
Must Attempt

Current Affairs (Jun 24, 2025 - Jun 30, 2025)

languageIcon English
  • pdpQsnIcon35 Questions
  • pdpsheetsIcon35 Marks
  • timerIcon15 Mins
languageIcon English
Free
Must Attempt

grammar

languageIcon English
  • pdpQsnIcon10 Questions
  • pdpsheetsIcon10 Marks
  • timerIcon7 Mins
languageIcon English
Free
Must Attempt

Series

languageIcon English
  • pdpQsnIcon10 Questions
  • pdpsheetsIcon10 Marks
  • timerIcon8 Mins
languageIcon English