Strings are represented as an array of characters.
Strings have a means of determining length:
Arrays in Java also have an explicit length attribute.
The difference between strings and character arrays is mainly conceptual:
Strings also have string-specific operations such as:
strlen()
is O(n).strlen()
O(1), but may take more space or limit string length.String.toCharArray()
String.charAt(int N)
where 0 <= N < string length
String.valueOf(char a[])
(static function)Character.toString(char c)
(static function)String.valueOf(char c)
(static function)Integer len = s.length();
String result = s1 + s2;
String result = s1 + "text";
Char by char:
String s = new String("");
for (...) {
s += ' '; // O(n²) since each addition involves copying the partial result.
}
StringBuilder:
StringBuilder sb = new StringBuilder();
for (...) {
sb.append(' '); // O(n) since `StringBuilder` updates a buffer in place.
}