Consider the following Java code snippet: public class Main { public static…
2023
Consider the following Java code snippet:
public class Main
{
public static void main(String[] args)
{
String str = "2237\u3456\u7891" + "011";
int length = str.length();
System.out.println("Length of the string : " + length);
}
}
What will be the output of the program?
- A.
Length of the string : 19
- B.
Length of the string : 13
- C.
Length of the string : 17
- D.
Length of the string : 9
- E.
Compilation Error
Attempted by 3 students.
Show answer & explanation
Correct answer: D
Concept
In Java source code, a \uXXXX unicode escape is handled by the compiler in a very early translation step, before the text is split into tokens. Each escape stands for exactly ONE Unicode character. For any code point in the Basic Multilingual Plane (U+0000 to U+FFFF) that character is a single UTF-16 code unit, and String.length() returns the number of UTF-16 code units, not the number of characters you typed in the source.
Applying it to this code
The literal "2237\u3456\u7891" decodes to the characters 2, 2, 3, 7, then the one character U+3456, then the one character U+7891 — that is 6 characters in all.
The literal "011" is the 3 characters 0, 1, 1.
Concatenating the two literals gives 6 + 3 characters, so str holds 9 characters.
length = str.length() is therefore 9, and the program prints: Length of the string : 9.
Cross-check
Both U+3456 and U+7891 are below U+FFFF, so each lies in the Basic Multilingual Plane and occupies exactly one UTF-16 code unit — there is no surrogate pair that would add to the count. Counting 4 (from 2237) + 1 + 1 (the two decoded escapes) + 3 (from 011) again gives 9, confirming the result.