4.1.1.7 - Strings, character codes and dates (Java)
Select and join string content, convert characters and numbers, and parse or format Java date/time values with explicit formats.
Java route status: incomplete: runnable support pending. Examples and code responses are written Java.
Indexing, substring and concatenation
String operations work with positions and lengths, so the indexing convention must be clear.
String code = "LAB-27";
int length = code.length();
int dash = code.indexOf('-');
char first = code.charAt(0);
String prefix = code.substring(0, dash);
String numberText = code.substring(dash + 1);
String label = prefix + " " + numberText;
System.out.println(label);
The length is 6; valid indices are 0 through 5. indexOf returns the first matching position (3 here) and returns -1 if absent. charAt(0) returns 'L'. A substring's start is inclusive and its end is exclusive, so substring(0, 3) contains positions 0, 1, 2, giving LAB. The one-argument form runs to the end, giving 27. Concatenation joins the parts to display LAB 27.
Java strings are immutable. These operations return values; they do not change code. To store a changed text, assign the returned value. Empty text has length zero and no valid character index. A missing separator must be checked before using its position as a substring boundary. For these examples, each visible character is one Java char; Java indices count UTF-16 code units, so not every Unicode symbol occupies just one position.
Character-code conversions
A character code is a number representing a character, rather than the numeric value of the character's printed digit.
char letter = 'A';
int code = (int) letter;
char nextLetter = (char) (code + 1);
System.out.println(code);
System.out.println(nextLetter);
For these basic characters, the outputs are 65 and B. Widening a char to int gives its UTF-16 code-unit value; casting a suitable code to char gives a character. The familiar ASCII characters retain their codes in Unicode: '0' has code 48, not 0. Therefore (int) '7' is 55; for a known decimal digit, '7' - '0' gives the numeric value 7. Integer.parseInt("7") converts numeric text instead.
Do not assume every adjacent code is an alphabetic character: adding one to 'Z' yields '['. Case conversion should use a suitable operation, such as Character.toUpperCase, rather than an unexplained arithmetic shift. Characters outside the Basic Multilingual Plane require a pair of Java char units; the elementary single-character examples deliberately avoid that extension.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account