Lesson 5 of 34

Working with Strings

9 min 20 XP

Strings come with many useful methods. length() gives the length. charAt(i) gives the character at position i, counting from 0. substring(a, b) gives the part from a up to (not including) b.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Never compare Strings with ==; use equals(). Use equalsIgnoreCase() to compare without caring about capital letters. This is a favourite interview question!

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Strings are immutable: methods like toUpperCase() return a new String and leave the original unchanged.

Challenge

+20 XP

Read a word and print its first letter, last letter and length. Input: Chennai Output: First: C Last: i Length: 7

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.