Interview Q&A · Java · 4 questions in this topic

ASCII, Unicode & Characters — Java Interview Q&A

All Java topics

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

Example.javajava
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

  1. 1ASCII range is 0–127 (7 bits).
  2. 2Extended 8-bit code pages pushed this to 0–255 but are not part of standard ASCII.
  3. 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

  1. 1Code points range from U+0000 to U+10FFFF; supplementary characters need two char (surrogate pair) units.
  2. 2Java identifiers and comments may use Unicode letters, so non-English names are legal.
  3. 3char is now understood as a UTF-16 code unit, not always a full character — use codePointAt / codePoints() for full code points.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits