Strings and StringBuilder

Strings: length, charAt, substring, immutability and StringBuilder.

A String is a sequence of characters. The main methods: • s.length() — the length; • s.charAt(i) — the character at index i (indices start at zero); • s.substring(a, b) — the substring from index a up to b, excluding b; • s.toLowerCase() / s.toUpperCase() — case; • s.equals(t) — content comparison (not ==, as you remember from the conditions lesson). Strings in Java are immutable: every "edit" creates a new string.
Java

Enter a word, for example: hello

Because strings are immutable, concatenating with + in a loop is slow: every operation copies the whole string. To build strings piece by piece there is StringBuilder — and it even has a ready-made reverse method. Below — a palindrome check done two ways: by comparing characters and via StringBuilder.
Java

Palindrome check. Enter: racecar

Task: read a word and count how many times the letter "a" occurs in it (a loop + charAt). The problems "Reverse a String", "Palindrome Check" and "Count the Vowels" are attached to this lesson — solve all three and mark the lesson as completed.

Practice problems

Доска