Interview Q&A · Java · 4 questions in this topic
ASCII, Unicode & Characters — Java Interview Q&A
How Java represents text, and the difference between a char constant and a String constant. Part of Core Java Basics · 294 questions in the Java bank.
What is the difference between length and length() in Java?
Answer
length() is a String method that returns the number of UTF-16 code units in the string. length (no parentheses) is a public final field on every array that holds the array’s fixed size. One is a method call on an object, the other is a field on an array — and for collections you use size() instead.
Example
String s = "Hello"; s.length(); // 5 — method on String int[] a = new int[6]; a.length; // 6 — field on the array java.util.List.of(1, 2).size(); // 2 — collections use size()
What is ASCII?
Answer
ASCII (American Standard Code for Information Interchange) is a 7-bit character-encoding standard covering 128 English letters, digits, punctuation marks and control codes. It is a subset of Unicode, so every ASCII character has the same code point in Unicode.
Key points
- 1ASCII range is 0–127 (7 bits).
- 2Extended 8-bit code pages pushed this to 0–255 but are not part of standard ASCII.
- 3Java source can freely contain ASCII, but the language is Unicode-based, not limited to ASCII.
What is Unicode?
Answer
Unicode is a universal character set that assigns a unique code point to virtually every character in every writing system, so text can be represented consistently across languages. Java was one of the first mainstream languages to adopt it: char is a 16-bit UTF-16 code unit, and String stores UTF-16 code units.
Key points
- 1Code points range from U+0000 to U+10FFFF; supplementary characters need two char (surrogate pair) units.
- 2Java identifiers and comments may use Unicode letters, so non-English names are legal.
- 3char is now understood as a UTF-16 code unit, not always a full character — use codePointAt / codePoints() for full code points.
What is the difference between a character constant and a String constant?
Answer
A character constant is a single char written in single quotes ('A') and holds one UTF-16 code unit. A String constant is a sequence of characters in double quotes ("Hello") and is an immutable object of type String. A char is a primitive, a String is a reference type.
Example
char c = 'A'; // primitive, 16-bit code unit String s = "Hello"; // immutable object, stored in the String pool
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission